'use client'

import { useState, useEffect, useCallback } from 'react'
import Header from '@/components/layout/Header'
import { useSession } from 'next-auth/react'
import { PlusIcon, XMarkIcon, CheckIcon, PencilSquareIcon } from '@heroicons/react/24/outline'

type OrgNode = {
  id: number; name: string; position: string | null; area: string | null
  email: string | null; phone: string | null; parentId: number | null; order: number
}

// ─── Tarjeta de nodo ─────────────────────────────────────────────────────────

const LEVEL_STYLE = [
  { ring: 'ring-2 ring-green-400', bg: 'bg-green-50', avatar: 'bg-green-600 text-white' },
  { ring: 'ring-2 ring-blue-300', bg: 'bg-blue-50', avatar: 'bg-blue-500 text-white' },
  { ring: 'ring-2 ring-indigo-200', bg: 'bg-indigo-50', avatar: 'bg-indigo-400 text-white' },
  { ring: 'ring-1 ring-gray-200', bg: 'bg-white', avatar: 'bg-gray-400 text-white' },
]

function NodeCard({ node, level, canEdit, onEdit, onAdd, onDel }: {
  node: OrgNode; level: number; canEdit: boolean
  onEdit: (n: OrgNode) => void
  onAdd: (n: OrgNode) => void
  onDel: (n: OrgNode) => void
}) {
  const s = LEVEL_STYLE[Math.min(level, LEVEL_STYLE.length - 1)]
  const initials = node.name.split(' ').filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase()

  return (
    <div className={`relative group rounded-xl shadow-sm ${s.ring} ${s.bg} p-3 w-44 text-center select-none`}>
      <div className={`w-10 h-10 rounded-full ${s.avatar} flex items-center justify-center text-sm font-bold mx-auto mb-2`}>
        {initials}
      </div>
      <p className="font-semibold text-gray-800 text-sm leading-snug">{node.name}</p>
      {node.position && <p className="text-xs text-gray-500 mt-0.5 leading-tight">{node.position}</p>}
      {node.area && <p className="text-xs text-gray-400 leading-tight">{node.area}</p>}
      {node.email && (
        <a href={`mailto:${node.email}`} className="text-xs text-green-600 hover:underline block mt-1 truncate" onClick={e => e.stopPropagation()}>
          {node.email}
        </a>
      )}

      {canEdit && (
        <div className="absolute -top-3 -right-3 hidden group-hover:flex items-center gap-1 z-10">
          <button
            onClick={e => { e.stopPropagation(); onAdd(node) }}
            title="Agregar subordinado"
            className="w-6 h-6 bg-green-500 hover:bg-green-600 text-white rounded-full flex items-center justify-center shadow-md text-sm leading-none"
          >+</button>
          <button
            onClick={e => { e.stopPropagation(); onEdit(node) }}
            title="Editar"
            className="w-6 h-6 bg-gray-400 hover:bg-gray-500 text-white rounded-full flex items-center justify-center shadow-md"
          ><PencilSquareIcon className="w-3 h-3" /></button>
          <button
            onClick={e => { e.stopPropagation(); onDel(node) }}
            title="Eliminar"
            className="w-6 h-6 bg-red-400 hover:bg-red-500 text-white rounded-full flex items-center justify-center shadow-md text-sm leading-none"
          >×</button>
        </div>
      )}
    </div>
  )
}

// ─── Rama recursiva ───────────────────────────────────────────────────────────

function OrgBranch({ node, allNodes, level = 0, canEdit, onEdit, onAdd, onDel }: {
  node: OrgNode; allNodes: OrgNode[]; level?: number; canEdit: boolean
  onEdit: (n: OrgNode) => void
  onAdd: (n: OrgNode) => void
  onDel: (n: OrgNode) => void
}) {
  const children = allNodes
    .filter(n => n.parentId === node.id)
    .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))

  return (
    <div className="flex flex-col items-center px-3">
      {/* Tarjeta */}
      <NodeCard node={node} level={level} canEdit={canEdit} onEdit={onEdit} onAdd={onAdd} onDel={onDel} />

      {children.length > 0 && (
        <>
          {/* Línea vertical desde la tarjeta hacia abajo */}
          <div className="w-px h-6 bg-gray-300 flex-shrink-0" />

          {/* Fila de hijos */}
          <div className="flex items-start">
            {children.map((child, i) => {
              const isFirst = i === 0
              const isLast = i === children.length - 1

              return (
                <div key={child.id} className="flex flex-col items-center">
                  {/*
                    Conector horizontal + vertical para este hijo.
                    h-6 = altura del conector
                    La barra horizontal está en top-0 (h-px)
                    La línea vertical baja desde top-0 hasta bottom-0
                  */}
                  <div className="relative h-6 w-full">
                    {/* Segmento izquierdo de la barra horizontal (→ hasta el centro) */}
                    {!isFirst && (
                      <div className="absolute top-0 left-0 right-1/2 h-px bg-gray-300" />
                    )}
                    {/* Segmento derecho de la barra horizontal (desde el centro →) */}
                    {!isLast && (
                      <div className="absolute top-0 left-1/2 right-0 h-px bg-gray-300" />
                    )}
                    {/* Línea vertical desde la barra hasta la tarjeta hijo */}
                    <div className="absolute top-0 bottom-0 left-0 right-0 flex justify-center">
                      <div className="w-px bg-gray-300" />
                    </div>
                  </div>

                  {/* Recurse */}
                  <OrgBranch
                    node={child}
                    allNodes={allNodes}
                    level={level + 1}
                    canEdit={canEdit}
                    onEdit={onEdit}
                    onAdd={onAdd}
                    onDel={onDel}
                  />
                </div>
              )
            })}
          </div>
        </>
      )}
    </div>
  )
}

// ─── Página principal ─────────────────────────────────────────────────────────

const emptyForm = { name: '', position: '', area: '', email: '', phone: '', parentId: '', order: '0' }

export default function OrganigramaPage() {
  const { data: session } = useSession()
  const canEdit = ['SUPER_ADMIN', 'ADMIN', 'EDITOR'].includes((session?.user as { role?: string })?.role ?? '')

  const [nodes, setNodes] = useState<OrgNode[]>([])
  const [loading, setLoading] = useState(true)
  const [modal, setModal] = useState(false)
  const [editing, setEditing] = useState<OrgNode | null>(null)
  const [form, setForm] = useState(emptyForm)
  const [saving, setSaving] = useState(false)
  const [confirmDel, setConfirmDel] = useState<OrgNode | null>(null)

  const load = useCallback(async () => {
    setLoading(true)
    const res = await fetch('/api/organigrama')
    setNodes(await res.json())
    setLoading(false)
  }, [])

  useEffect(() => { load() }, [load])

  function openNew(parent?: OrgNode) {
    setEditing(null)
    setForm({ ...emptyForm, parentId: parent ? String(parent.id) : '' })
    setModal(true)
  }

  function openEdit(n: OrgNode) {
    setEditing(n)
    setForm({
      name: n.name, position: n.position ?? '', area: n.area ?? '',
      email: n.email ?? '', phone: n.phone ?? '',
      parentId: n.parentId ? String(n.parentId) : '', order: String(n.order),
    })
    setModal(true)
  }

  async function save() {
    setSaving(true)
    await fetch(editing ? `/api/organigrama/${editing.id}` : '/api/organigrama', {
      method: editing ? 'PUT' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...form,
        order: parseInt(form.order) || 0,
        parentId: form.parentId ? parseInt(form.parentId) : null,
      }),
    })
    setSaving(false); setModal(false); load()
  }

  async function del(n: OrgNode) {
    await fetch(`/api/organigrama/${n.id}`, { method: 'DELETE' })
    setConfirmDel(null); load()
  }

  const roots = nodes
    .filter(n => !n.parentId)
    .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))

  return (
    <div>
      <Header title="Organigrama" />
      <div className="p-6">
        {canEdit && (
          <div className="flex justify-end mb-6">
            <button
              onClick={() => openNew()}
              className="flex items-center gap-1.5 bg-green-600 hover:bg-green-700 text-white text-sm font-medium px-4 py-2 rounded-lg"
            >
              <PlusIcon className="w-4 h-4" /> Agregar posición raíz
            </button>
          </div>
        )}

        {loading ? (
          <p className="text-gray-400 text-sm">Cargando...</p>
        ) : roots.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 text-gray-400">
            <p className="text-sm">Sin posiciones registradas.</p>
            {canEdit && <p className="text-xs mt-1">Empieza agregando el nivel raíz (ej. Gerente General).</p>}
          </div>
        ) : (
          /* Contenedor con scroll horizontal para organigramas anchos */
          <div className="overflow-auto">
            <div className="min-w-max flex gap-16 justify-center py-4 px-8">
              {roots.map(root => (
                <OrgBranch
                  key={root.id}
                  node={root}
                  allNodes={nodes}
                  level={0}
                  canEdit={canEdit}
                  onEdit={openEdit}
                  onAdd={openNew}
                  onDel={setConfirmDel}
                />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* ── Modal crear / editar ── */}
      {modal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md">
            <div className="flex items-center justify-between p-5 border-b border-gray-100">
              <h3 className="font-semibold text-gray-800">{editing ? 'Editar posición' : 'Nueva posición'}</h3>
              <button onClick={() => setModal(false)}><XMarkIcon className="w-5 h-5 text-gray-400" /></button>
            </div>
            <div className="p-5 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Nombre *</label>
                  <input
                    value={form.name}
                    onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                    placeholder="Nombre completo"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Cargo</label>
                  <input
                    value={form.position}
                    onChange={e => setForm(f => ({ ...f, position: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                    placeholder="ej. Gerente General"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Área</label>
                  <input
                    value={form.area}
                    onChange={e => setForm(f => ({ ...f, area: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Email</label>
                  <input
                    type="email"
                    value={form.email}
                    onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Teléfono</label>
                  <input
                    value={form.phone}
                    onChange={e => setForm(f => ({ ...f, phone: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Reporta a</label>
                  <select
                    value={form.parentId}
                    onChange={e => setForm(f => ({ ...f, parentId: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                  >
                    <option value="">Nivel raíz</option>
                    {nodes
                      .filter(n => n.id !== editing?.id)
                      .sort((a, b) => a.name.localeCompare(b.name))
                      .map(n => (
                        <option key={n.id} value={n.id}>
                          {n.name}{n.position ? ` — ${n.position}` : ''}
                        </option>
                      ))}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1.5">Orden</label>
                  <input
                    type="number"
                    value={form.order}
                    onChange={e => setForm(f => ({ ...f, order: e.target.value }))}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
                    min="0"
                  />
                </div>
              </div>
            </div>
            <div className="p-5 border-t border-gray-100 flex justify-end gap-3">
              <button onClick={() => setModal(false)} className="px-4 py-2 text-sm text-gray-600">Cancelar</button>
              <button
                onClick={save}
                disabled={saving || !form.name}
                className="flex items-center gap-1.5 px-4 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-60 font-medium"
              >
                <CheckIcon className="w-4 h-4" />{saving ? 'Guardando...' : 'Guardar'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── Confirmar eliminar ── */}
      {confirmDel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-sm p-6">
            <h3 className="font-semibold text-gray-800 mb-2">Eliminar posición</h3>
            <p className="text-sm text-gray-500 mb-1">¿Eliminar <strong>{confirmDel.name}</strong>?</p>
            <p className="text-xs text-gray-400 mb-5">Los subordinados directos quedarán sin nivel superior asignado.</p>
            <div className="flex justify-end gap-3">
              <button onClick={() => setConfirmDel(null)} className="px-4 py-2 text-sm text-gray-600">Cancelar</button>
              <button onClick={() => del(confirmDel)} className="px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700">
                Eliminar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
