'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent } from '@horux/shared-ui';
import { Header } from '@/components/layouts/header';
import { DespachoSubnav } from '@/components/despachos/despacho-subnav';
import { PeriodoSelector } from '@/components/periodo-selector';
import { apiClient } from '@/lib/api/client';
import { useAuthStore } from '@/stores/auth-store';
import { usePeriodoStore, añoMesFromFechaInicio } from '@/stores/periodo-store';
import { User, AlertTriangle, Loader2, ChevronDown, ChevronRight, CheckCircle2 } from 'lucide-react';

interface Miembro {
  userId: string;
  nombre: string;
  email: string;
  rol: 'supervisor' | 'auxiliar';
  contribuyentes: number;
  obligacionesAtrasadas: number;
  tareasAtrasadas: number;
  totalPendientes: number;
  totalPeriodo: number;
  completadasPeriodo: number;
  avancePct: number | null;
}

interface SupervisorConAuxiliares extends Miembro {
  auxiliares: Miembro[];
}

interface EquipoStatsResponse {
  supervisores: SupervisorConAuxiliares[];
  huerfanos: Miembro[];
}

const ROLES_SUPERVISORY = new Set(['owner', 'cfo', 'supervisor']);

function AvanceBar({ pct }: { pct: number | null }) {
  if (pct === null) return <span className="text-xs text-muted-foreground">Sin datos</span>;
  const color =
    pct >= 80 ? 'bg-success' :
    pct >= 50 ? 'bg-amber-500' :
    'bg-destructive';
  const text =
    pct >= 80 ? 'text-success' :
    pct >= 50 ? 'text-amber-600' :
    'text-destructive';
  return (
    <div className="flex items-center gap-2 min-w-[140px]">
      <div className="flex-1 h-2 rounded-full bg-muted overflow-hidden">
        <div className={`h-full transition-all ${color}`} style={{ width: `${pct}%` }} />
      </div>
      <span className={`text-xs font-medium tabular-nums ${text}`}>{pct}%</span>
    </div>
  );
}

function AtrasoBadge({ total }: { total: number }) {
  if (total === 0) {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs text-muted-foreground bg-muted">
        <CheckCircle2 className="h-3 w-3" /> Al día
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-destructive/10 text-destructive">
      <AlertTriangle className="h-3 w-3" />
      {total}
    </span>
  );
}

export default function EquipoPage() {
  const role = useAuthStore(s => s.user?.role);
  const enabled = role ? ROLES_SUPERVISORY.has(role) : false;
  const { fechaInicio } = usePeriodoStore();
  const { año, mes } = añoMesFromFechaInicio(fechaInicio);
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const { data, isLoading } = useQuery<EquipoStatsResponse>({
    queryKey: ['despacho-equipo-stats', año, mes],
    queryFn: async () => {
      const { data } = await apiClient.get<EquipoStatsResponse>(
        `/despachos/equipo-stats?año=${año}&mes=${mes}`,
      );
      return data;
    },
    enabled,
  });

  if (!enabled) {
    return (
      <>
        <Header title="Despacho — Equipo"><PeriodoSelector /></Header>
        <main className="p-6 max-w-6xl mx-auto">
          <DespachoSubnav />
          <Card>
            <CardContent className="py-8 text-center text-muted-foreground">
              Esta sección solo está disponible para owner y supervisor.
            </CardContent>
          </Card>
        </main>
      </>
    );
  }

  const supervisores = data?.supervisores ?? [];
  const huerfanos = data?.huerfanos ?? [];
  const sinDatos = !isLoading && supervisores.length === 0 && huerfanos.length === 0;

  return (
    <>
      <Header title="Despacho — Equipo"><PeriodoSelector /></Header>
      <main className="p-6 max-w-6xl mx-auto space-y-6">
        <DespachoSubnav />

        {isLoading ? (
          <div className="flex items-center gap-2 text-muted-foreground py-8 justify-center">
            <Loader2 className="h-4 w-4 animate-spin" />
            Cargando...
          </div>
        ) : sinDatos ? (
          <Card>
            <CardContent className="py-8 text-center text-muted-foreground">
              No hay supervisores ni auxiliares en el despacho.
            </CardContent>
          </Card>
        ) : (
          <>
            {supervisores.length > 0 && (
              <Card>
                <CardContent className="p-0">
                  <table className="w-full text-sm">
                    <thead className="border-b bg-muted/50">
                      <tr>
                        <th className="w-10"></th>
                        <th className="text-left px-4 py-3 font-medium">Miembro</th>
                        <th className="text-center px-3 py-3 font-medium">Contribuyentes</th>
                        <th className="text-left px-3 py-3 font-medium">Avance del periodo</th>
                        <th className="text-center px-3 py-3 font-medium">Atrasos</th>
                      </tr>
                    </thead>
                    <tbody>
                      {supervisores.map(sup => {
                        const expanded = expandedId === sup.userId;
                        const tieneAux = sup.auxiliares.length > 0;
                        return (
                          <FilaSupervisor
                            key={sup.userId}
                            sup={sup}
                            expanded={expanded}
                            tieneAux={tieneAux}
                            onToggle={() => setExpandedId(expanded ? null : sup.userId)}
                          />
                        );
                      })}
                    </tbody>
                  </table>
                </CardContent>
              </Card>
            )}

            {huerfanos.length > 0 && (
              <div>
                <h2 className="text-sm font-semibold mb-2 text-amber-700 dark:text-amber-400 uppercase tracking-wide flex items-center gap-2">
                  <AlertTriangle className="h-4 w-4" />
                  Auxiliares sin supervisor asignado
                </h2>
                <Card>
                  <CardContent className="p-0">
                    <table className="w-full text-sm">
                      <thead className="border-b bg-muted/50">
                        <tr>
                          <th className="text-left px-4 py-3 font-medium">Auxiliar</th>
                          <th className="text-center px-3 py-3 font-medium">Contribuyentes</th>
                          <th className="text-left px-3 py-3 font-medium">Avance del periodo</th>
                          <th className="text-center px-3 py-3 font-medium">Atrasos</th>
                        </tr>
                      </thead>
                      <tbody>
                        {huerfanos.map(aux => (
                          <tr key={aux.userId} className="border-b hover:bg-muted/30">
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-2">
                                <User className="h-4 w-4 text-muted-foreground" />
                                <div>
                                  <div className="font-medium">{aux.nombre}</div>
                                  <div className="text-xs text-muted-foreground">{aux.email}</div>
                                </div>
                              </div>
                            </td>
                            <td className="px-3 py-3 text-center text-muted-foreground">{aux.contribuyentes}</td>
                            <td className="px-3 py-3"><AvanceBar pct={aux.avancePct} /></td>
                            <td className="px-3 py-3 text-center"><AtrasoBadge total={aux.totalPendientes} /></td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </CardContent>
                </Card>
              </div>
            )}
          </>
        )}
      </main>
    </>
  );
}

function FilaSupervisor({
  sup, expanded, tieneAux, onToggle,
}: {
  sup: SupervisorConAuxiliares;
  expanded: boolean;
  tieneAux: boolean;
  onToggle: () => void;
}) {
  return (
    <>
      <tr
        className={`border-b ${tieneAux ? 'cursor-pointer hover:bg-muted/30' : ''} ${expanded ? 'bg-muted/30' : ''}`}
        onClick={tieneAux ? onToggle : undefined}
      >
        <td className="px-2 py-3 text-center">
          {tieneAux ? (
            expanded ? <ChevronDown className="h-4 w-4 text-muted-foreground inline" /> : <ChevronRight className="h-4 w-4 text-muted-foreground inline" />
          ) : null}
        </td>
        <td className="px-4 py-3">
          <div className="flex items-center gap-2">
            <User className="h-4 w-4 text-primary" />
            <div>
              <div className="font-medium">{sup.nombre}</div>
              <div className="text-xs text-muted-foreground">
                {sup.email} · {sup.auxiliares.length} auxiliar{sup.auxiliares.length === 1 ? '' : 'es'}
              </div>
            </div>
          </div>
        </td>
        <td className="px-3 py-3 text-center text-muted-foreground">{sup.contribuyentes}</td>
        <td className="px-3 py-3"><AvanceBar pct={sup.avancePct} /></td>
        <td className="px-3 py-3 text-center"><AtrasoBadge total={sup.totalPendientes} /></td>
      </tr>
      {expanded && sup.auxiliares.map(aux => (
        <tr key={aux.userId} className="border-b bg-muted/10">
          <td></td>
          <td className="px-4 py-2 pl-10">
            <div className="flex items-center gap-2">
              <User className="h-4 w-4 text-muted-foreground" />
              <div>
                <div className="text-sm">{aux.nombre}</div>
                <div className="text-xs text-muted-foreground">{aux.email}</div>
              </div>
            </div>
          </td>
          <td className="px-3 py-2 text-center text-muted-foreground">{aux.contribuyentes}</td>
          <td className="px-3 py-2"><AvanceBar pct={aux.avancePct} /></td>
          <td className="px-3 py-2 text-center"><AtrasoBadge total={aux.totalPendientes} /></td>
        </tr>
      ))}
      {expanded && sup.auxiliares.length === 0 && (
        <tr className="border-b bg-muted/10">
          <td></td>
          <td colSpan={4} className="px-4 py-3 pl-10 text-xs text-muted-foreground italic">
            Sin auxiliares asignados.
          </td>
        </tr>
      )}
    </>
  );
}
