import { useEffect, useState } from 'react'
import { useParams, useNavigate, Link } from '@tanstack/react-router'
import { ArrowLeft, FileText, Users, FolderX, UserX, GitBranch } 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'

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

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)

  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, 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)
    setProcesses((procRes.data as OrgProcess[] | null) ?? [])
    setUsers((userRes.data as OrgUser[] | null) ?? [])
    setLoading(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()
    }
  }

  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>
        </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>
      </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>
    </>
  )
}

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>
  )
}
