import { useEffect, useState } from 'react'
import { useParams, useNavigate, Link } from '@tanstack/react-router'
import { ArrowLeft, FileText, Users, FolderX, UserX, GitBranch, FolderOpen, Plus, Pencil, Trash2 } from 'lucide-react'
import { supabase } from '@/lib/supabase'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetFooter,
} from '@/components/ui/sheet'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { RoleBadge } from './RoleBadge'
import { supabaseAreaRepo } from '@/persistence/supabase/area-repo'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

interface OrgProcess {
  id: string
  name: string
  client: string | null
  area_id: string | null
  updated_at: string
}

interface AreaWithCount {
  id: string
  name: string
  description: string | null
  processCount: number
}

interface OrgUser {
  id: string
  name: string | null
  company: string | null
  platform_role: string
  avatar_url?: string | null
}

interface UnassignedProcess {
  id: string
  name: string
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('es-PY', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  })
}

export function OrganizationDetailPage() {
  const { orgId } = useParams({ from: '/admin/organizations/$orgId' })
  const navigate = useNavigate()

  const [orgName, setOrgName] = useState<string>('')
  const [processes, setProcesses] = useState<OrgProcess[]>([])
  const [users, setUsers] = useState<OrgUser[]>([])
  const [loading, setLoading] = useState(true)

  // Asignar proceso
  const [assignOpen, setAssignOpen] = useState(false)
  const [unassigned, setUnassigned] = useState<UnassignedProcess[]>([])
  const [loadingUnassigned, setLoadingUnassigned] = useState(false)
  const [selectedProcessId, setSelectedProcessId] = useState<string>('')
  const [assigning, setAssigning] = useState(false)
  const [assignError, setAssignError] = useState<string | null>(null)

  // Áreas de la org
  const [areas, setAreas] = useState<AreaWithCount[]>([])
  const [areasLoading, setAreasLoading] = useState(false)

  // Sheet crear/editar área
  const [areaSheetOpen, setAreaSheetOpen] = useState(false)
  const [editingAreaId, setEditingAreaId] = useState<string | null>(null)
  const [areaNameInput, setAreaNameInput] = useState('')
  const [savingArea, setSavingArea] = useState(false)
  const [areaFormError, setAreaFormError] = useState<string | null>(null)

  // Confirmación de delete
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)
  const [deletingAreaId, setDeletingAreaId] = useState<string | null>(null)

  const fetchDetail = async () => {
    const [orgRes, procRes, userRes] = await Promise.all([
      supabase.from('organizations').select('name').eq('id', orgId).single(),
      supabase
        .from('processes')
        .select('id, name, client, area_id, updated_at')
        .eq('org_id', orgId)
        .order('updated_at', { ascending: false }),
      supabase.from('users').select('id, name, company, platform_role, avatar_url').eq('org_id', orgId).order('name'),
    ])
    if (orgRes.data) setOrgName((orgRes.data as { name: string }).name)
    const loadedProcesses = (procRes.data as OrgProcess[] | null) ?? []
    setProcesses(loadedProcesses)
    setUsers((userRes.data as OrgUser[] | null) ?? [])
    setLoading(false)

    // Cargar áreas y calcular conteo de procesos
    setAreasLoading(true)
    try {
      const rawAreas = await supabaseAreaRepo.getByOrg(orgId)
      const withCount: AreaWithCount[] = rawAreas.map((a) => ({
        id: a.id,
        name: a.name,
        description: a.description,
        processCount: loadedProcesses.filter((p) => p.area_id === a.id).length,
      }))
      setAreas(withCount)
    } catch {
      setAreas([])
    } finally {
      setAreasLoading(false)
    }
  }

  useEffect(() => { void fetchDetail() }, [orgId])

  const openAssign = async () => {
    setSelectedProcessId('')
    setAssignError(null)
    setAssignOpen(true)
    setLoadingUnassigned(true)
    const { data } = await supabase
      .from('processes')
      .select('id, name')
      .is('org_id', null)
      .order('name')
    setUnassigned((data as UnassignedProcess[] | null) ?? [])
    setLoadingUnassigned(false)
  }

  const handleAssign = async () => {
    if (!selectedProcessId) {
      setAssignError('Seleccioná un proceso')
      return
    }
    setAssigning(true)
    const { error } = await supabase
      .from('processes')
      .update({ org_id: orgId })
      .eq('id', selectedProcessId)
    if (error) {
      setAssignError(error.message)
      setAssigning(false)
    } else {
      setAssignOpen(false)
      setAssigning(false)
      void fetchDetail()
    }
  }

  const openCreateArea = () => {
    setEditingAreaId(null)
    setAreaNameInput('')
    setAreaFormError(null)
    setAreaSheetOpen(true)
  }

  const openEditArea = (area: AreaWithCount) => {
    setEditingAreaId(area.id)
    setAreaNameInput(area.name)
    setAreaFormError(null)
    setAreaSheetOpen(true)
  }

  const handleSaveArea = async () => {
    const name = areaNameInput.trim()
    if (!name) { setAreaFormError('El nombre del área es requerido'); return }
    setSavingArea(true)
    setAreaFormError(null)
    try {
      if (editingAreaId) {
        await supabaseAreaRepo.update(editingAreaId, { name })
      } else {
        await supabaseAreaRepo.create({ orgId, name })
      }
      setAreaSheetOpen(false)
      void fetchDetail()
    } catch (e) {
      setAreaFormError(e instanceof Error ? e.message : 'Error al guardar el área')
    } finally {
      setSavingArea(false)
    }
  }

  const handleDeleteArea = async (areaId: string) => {
    setDeletingAreaId(areaId)
    try {
      await supabaseAreaRepo.delete(areaId)
      setDeleteConfirmId(null)
      void fetchDetail()
    } catch (e) {
      console.error('Error eliminando área:', e)
    } finally {
      setDeletingAreaId(null)
    }
  }

  if (loading) {
    return (
      <div className="flex flex-col gap-4">
        <Skeleton className="h-6 w-48" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => navigate({ to: '/admin/organizations' })}
          className="text-slate-500 hover:text-slate-900"
        >
          <ArrowLeft className="h-4 w-4 mr-1" />
          Volver
        </Button>
        <h2 className="text-lg font-semibold text-slate-900">{orgName}</h2>
      </div>

      <Tabs defaultValue="processes">
        <TabsList className="mb-4">
          <TabsTrigger value="processes">
            <FileText className="h-4 w-4 mr-1.5" />
            Procesos ({processes.length})
          </TabsTrigger>
          <TabsTrigger value="users">
            <Users className="h-4 w-4 mr-1.5" />
            Usuarios ({users.length})
          </TabsTrigger>
          <TabsTrigger value="areas">
            <FolderOpen className="h-4 w-4 mr-1.5" />
            Áreas ({areas.length})
          </TabsTrigger>
        </TabsList>

        {/* ─── Tab: Procesos ─────────────────────────────────────────────── */}
        <TabsContent value="processes">
          <div className="flex items-center justify-between mb-4">
            <p className="text-sm text-slate-500">
              {processes.length === 0
                ? 'No hay procesos asignados a esta organización.'
                : `${processes.length} proceso${processes.length !== 1 ? 's' : ''} asignado${processes.length !== 1 ? 's' : ''}.`}
            </p>
            <Button size="sm" variant="outline" onClick={openAssign}>
              <GitBranch className="h-4 w-4 mr-1.5" />
              Asignar proceso existente
            </Button>
          </div>

          {processes.length === 0 ? (
            <EmptyState
              icon={<FolderX className="h-10 w-10 text-slate-300" />}
              message="Esta organización no tiene procesos asignados. Podés asignar uno existente o importar uno nuevo."
            />
          ) : (
            <div className="rounded-lg border border-slate-200 overflow-hidden bg-white">
              <table className="w-full text-sm">
                <thead className="bg-slate-50 border-b border-slate-200">
                  <tr>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Proceso</th>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Última actualización</th>
                    <th className="py-2.5 px-4" />
                  </tr>
                </thead>
                <tbody>
                  {processes.map((p) => (
                    <tr key={p.id} className="border-b border-slate-100 last:border-0 hover:bg-slate-50/50">
                      <td className="py-3 px-4 font-medium text-slate-900">{p.name}</td>
                      <td className="py-3 px-4 text-slate-500">{formatDate(p.updated_at)}</td>
                      <td className="py-3 px-4 text-right">
                        <Link
                          to="/workspace/$processId"
                          params={{ processId: p.id }}
                          className="text-xs font-semibold text-[#F59845] hover:text-[#e0872e]"
                        >
                          Abrir workspace →
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </TabsContent>

        {/* ─── Tab: Usuarios ─────────────────────────────────────────────── */}
        <TabsContent value="users">
          {users.length === 0 ? (
            <EmptyState
              icon={<UserX className="h-10 w-10 text-slate-300" />}
              message="No hay usuarios en esta organización. Invitá usuarios desde la sección Usuarios."
            />
          ) : (
            <div className="rounded-lg border border-slate-200 overflow-hidden bg-white">
              <table className="w-full text-sm">
                <thead className="bg-slate-50 border-b border-slate-200">
                  <tr>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Nombre</th>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Rol</th>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Empresa</th>
                  </tr>
                </thead>
                <tbody>
                  {users.map((u) => (
                    <tr key={u.id} className="border-b border-slate-100 last:border-0">
                      <td className="py-3 px-4">
                        <span className="font-medium text-slate-900">{u.name || '—'}</span>
                        {!u.name && !u.avatar_url && (
                          <span className="ml-2 text-[10px] font-medium px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200">
                            Invitación pendiente
                          </span>
                        )}
                      </td>
                      <td className="py-3 px-4">
                        <RoleBadge role={u.platform_role} />
                      </td>
                      <td className="py-3 px-4 text-slate-500">{u.company ?? '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </TabsContent>
        {/* ─── Tab: Áreas ──────────────────────────────────────────────── */}
        <TabsContent value="areas">
          <div className="flex items-center justify-between mb-4">
            <p className="text-sm text-slate-500">
              {areasLoading
                ? 'Cargando áreas…'
                : areas.length === 0
                  ? 'No hay áreas en esta organización.'
                  : `${areas.length} área${areas.length !== 1 ? 's' : ''}.`}
            </p>
            <Button size="sm" variant="outline" onClick={openCreateArea}>
              <Plus className="h-4 w-4 mr-1.5" />
              Nueva área
            </Button>
          </div>

          {areasLoading ? (
            <div className="space-y-2">
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
            </div>
          ) : areas.length === 0 ? (
            <EmptyState
              icon={<FolderOpen className="h-10 w-10 text-slate-300" />}
              message="Las áreas agrupan procesos dentro de una organización (ej: Operaciones, RR.HH., Finanzas)."
            />
          ) : (
            <div className="rounded-lg border border-slate-200 overflow-hidden bg-white">
              <table className="w-full text-sm">
                <thead className="bg-slate-50 border-b border-slate-200">
                  <tr>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Área</th>
                    <th className="text-left py-2.5 px-4 font-medium text-slate-600">Procesos</th>
                    <th className="py-2.5 px-4" />
                  </tr>
                </thead>
                <tbody>
                  {areas.map((area) => (
                    <tr key={area.id} className="border-b border-slate-100 last:border-0 hover:bg-slate-50/50">
                      <td className="py-3 px-4 font-medium text-slate-900">{area.name}</td>
                      <td className="py-3 px-4 text-slate-500">
                        {area.processCount} {area.processCount === 1 ? 'proceso' : 'procesos'}
                      </td>
                      <td className="py-3 px-4">
                        {deleteConfirmId === area.id ? (
                          <div className="flex items-center justify-end gap-2">
                            <span className="text-xs text-slate-500">
                              {area.processCount > 0
                                ? `${area.processCount} proceso${area.processCount !== 1 ? 's' : ''} quedarán sin área.`
                                : '¿Eliminar esta área?'}
                            </span>
                            <Button
                              size="sm"
                              variant="destructive"
                              className="h-7 text-xs px-2"
                              disabled={deletingAreaId === area.id}
                              onClick={() => handleDeleteArea(area.id)}
                            >
                              {deletingAreaId === area.id ? 'Eliminando…' : 'Confirmar'}
                            </Button>
                            <Button
                              size="sm"
                              variant="ghost"
                              className="h-7 text-xs px-2"
                              onClick={() => setDeleteConfirmId(null)}
                            >
                              Cancelar
                            </Button>
                          </div>
                        ) : (
                          <div className="flex items-center justify-end gap-1">
                            <Button
                              size="sm"
                              variant="ghost"
                              className="h-7 w-7 p-0 text-slate-400 hover:text-slate-700"
                              onClick={() => openEditArea(area)}
                              title="Renombrar área"
                            >
                              <Pencil className="h-3.5 w-3.5" />
                            </Button>
                            <Button
                              size="sm"
                              variant="ghost"
                              className="h-7 w-7 p-0 text-slate-400 hover:text-red-600"
                              onClick={() => setDeleteConfirmId(area.id)}
                              title="Eliminar área"
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </TabsContent>
      </Tabs>

      {/* ─── Sheet: Asignar proceso ─────────────────────────────────────── */}
      <Sheet open={assignOpen} onOpenChange={setAssignOpen}>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Asignar proceso a {orgName}</SheetTitle>
          </SheetHeader>
          <div className="mt-5 flex flex-col gap-4">
            {loadingUnassigned ? (
              <Skeleton className="h-9 w-full" />
            ) : unassigned.length === 0 ? (
              <p className="text-sm text-slate-500">No hay procesos sin organización asignada.</p>
            ) : (
              <Select value={selectedProcessId} onValueChange={setSelectedProcessId}>
                <SelectTrigger>
                  <SelectValue placeholder="Seleccioná un proceso" />
                </SelectTrigger>
                <SelectContent>
                  {unassigned.map((p) => (
                    <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
            {assignError && <p className="text-xs text-red-600">{assignError}</p>}
            <SheetFooter>
              <Button
                onClick={handleAssign}
                disabled={assigning || loadingUnassigned || unassigned.length === 0}
              >
                {assigning ? 'Asignando…' : 'Asignar proceso'}
              </Button>
            </SheetFooter>
          </div>
        </SheetContent>
      </Sheet>
      {/* ─── Sheet: Crear/editar área ────────────────────────────────── */}
      <Sheet open={areaSheetOpen} onOpenChange={setAreaSheetOpen}>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>
              {editingAreaId ? 'Renombrar área' : `Nueva área en ${orgName}`}
            </SheetTitle>
          </SheetHeader>
          <div className="mt-5 flex flex-col gap-4">
            <div className="space-y-1.5">
              <Label htmlFor="area-name" className="text-sm font-medium">
                Nombre del área
              </Label>
              <Input
                id="area-name"
                value={areaNameInput}
                onChange={(e) => { setAreaNameInput(e.target.value); setAreaFormError(null) }}
                placeholder="ej. Operaciones, RR.HH., Finanzas"
                className="h-9"
                onKeyDown={(e) => { if (e.key === 'Enter') void handleSaveArea() }}
                autoFocus
              />
              {areaFormError && (
                <p className="text-xs text-red-600">{areaFormError}</p>
              )}
            </div>
            <SheetFooter>
              <Button onClick={handleSaveArea} disabled={savingArea || !areaNameInput.trim()}>
                {savingArea ? 'Guardando…' : editingAreaId ? 'Guardar cambios' : 'Crear área'}
              </Button>
            </SheetFooter>
          </div>
        </SheetContent>
      </Sheet>
    </>
  )
}

function EmptyState({ icon, message }: { icon: React.ReactNode; message: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 gap-3 text-center">
      {icon}
      <p className="text-sm text-slate-500 max-w-sm">{message}</p>
    </div>
  )
}
