'use client';

import { useState } from 'react';
import Link from 'next/link';
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 { useContribuyenteStore } from '@/stores/contribuyente-store';
import { usePeriodoStore, añoMesFromFechaInicio } from '@/stores/periodo-store';
import { Building2, Clock, AlertTriangle, CheckCircle2, Loader2, Search, FolderOpen, ChevronDown } from 'lucide-react';

interface Asignado {
  contribuyenteId: string;
  rfc: string;
  nombre: string;
  carteraNombre: string | null;
  obligacionesPendientes: number;
  obligacionesAtrasadas: number;
  obligacionesCompletadas: number;
  tareasPendientes: number;
  tareasAtrasadas: number;
  tareasCompletadas: number;
}

const ROLES_ASIGNADOS = new Set(['owner', 'cfo', 'supervisor', 'auxiliar', 'contador', 'visor']);
const PLATFORM_SUPERSET = new Set(['platform_admin', 'platform_ti']);

export default function MisAsignadosPage() {
  const [filtroCliente, setFiltroCliente] = useState('');
  const [filtroCartera, setFiltroCartera] = useState('');

  const role = useAuthStore(s => s.user?.role);
  const platformRoles = useAuthStore(s => s.user?.platformRoles);
  const isPlatformStaff = platformRoles?.some(r => PLATFORM_SUPERSET.has(r)) ?? false;
  const enabled = role ? (ROLES_ASIGNADOS.has(role) || isPlatformStaff) : false;
  const { setSelectedContribuyente } = useContribuyenteStore();
  const { fechaInicio } = usePeriodoStore();
  const { año, mes } = añoMesFromFechaInicio(fechaInicio);

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

  if (!enabled) {
    return (
      <>
        <Header title="Despacho — Mis asignados"><PeriodoSelector /></Header>
        <main className="p-6 max-w-6xl mx-auto">
          <DespachoSubnav />
          <Card>
            <CardContent className="py-8 text-center text-muted-foreground">
              No tienes contribuyentes asignados.
            </CardContent>
          </Card>
        </main>
      </>
    );
  }

  const items = data ?? [];

  const carterasUnicas = Array.from(new Set(items.map(it => it.carteraNombre || 'Sin cartera'))).sort((a, b) =>
    a.localeCompare(b, 'es', { sensitivity: 'base' })
  );

  const itemsFiltrados = items.filter((it) => {
    const coincideCliente = [it.nombre, it.rfc].some(v =>
      v.toLowerCase().includes(filtroCliente.trim().toLowerCase())
    );
    const coincideCartera =
      filtroCartera === '' || (filtroCartera === '__sin_cartera__' ? !it.carteraNombre : it.carteraNombre === filtroCartera);
    return coincideCliente && coincideCartera;
  });

  return (
    <>
      <Header title="Despacho — Mis asignados"><PeriodoSelector /></Header>
      <main className="p-6 max-w-6xl mx-auto">
        <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>
        ) : items.length === 0 ? (
          <Card>
            <CardContent className="py-8 text-center text-muted-foreground">
              No tienes contribuyentes asignados todavía. Pídele al owner que te los asigne en su cartera.
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardContent className="p-0">
              <div className="flex flex-col sm:flex-row gap-3 p-4 border-b bg-muted/30">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <input
                    type="text"
                    value={filtroCliente}
                    onChange={(e) => setFiltroCliente(e.target.value)}
                    placeholder="Buscar por cliente o RFC..."
                    className="w-full rounded-md border border-input bg-background pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  />
                </div>
                <div className="relative sm:w-64">
                  <FolderOpen className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <select
                    value={filtroCartera}
                    onChange={(e) => setFiltroCartera(e.target.value)}
                    className="w-full appearance-none rounded-md border border-input bg-background pl-9 pr-8 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  >
                    <option value="">Todas las carteras</option>
                    <option value="__sin_cartera__">Sin cartera</option>
                    {carterasUnicas.filter(c => c !== 'Sin cartera').map((c) => (
                      <option key={c} value={c}>{c}</option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
                </div>
              </div>

              {itemsFiltrados.length === 0 ? (
                <div className="py-8 text-center text-muted-foreground text-sm">
                  No hay resultados para los filtros seleccionados.
                </div>
              ) : (
              <table className="w-full text-sm">
                <thead className="border-b bg-muted/50">
                  <tr>
                    <th className="text-left px-4 py-3 font-medium">Contribuyente</th>
                    <th className="text-left px-4 py-3 font-medium">Cartera</th>
                    <th className="text-left px-4 py-3 font-medium w-[180px]">Avance</th>
                    <th className="text-center px-3 py-3 font-medium" title="Atrasos de periodos anteriores (obligaciones + tareas)">
                      Atrasos
                    </th>
                    <th className="text-center px-3 py-3 font-medium" title="Obligaciones del periodo">
                      Obl. periodo
                    </th>
                    <th className="text-center px-3 py-3 font-medium" title="Tareas del periodo">
                      Tareas periodo
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {itemsFiltrados.map(it => {
                    const total =
                      it.obligacionesPendientes + it.obligacionesAtrasadas + it.obligacionesCompletadas +
                      it.tareasPendientes + it.tareasAtrasadas + it.tareasCompletadas;
                    const completadas = it.obligacionesCompletadas + it.tareasCompletadas;
                    const pct = total > 0 ? Math.round((completadas / total) * 100) : null;
                    const barColor =
                      pct === null ? 'bg-muted' :
                      pct >= 80 ? 'bg-success' :
                      pct >= 50 ? 'bg-amber-500' :
                      'bg-destructive';
                    const totalAtrasos = it.obligacionesAtrasadas + it.tareasAtrasadas;
                    const tieneAtrasos = totalAtrasos > 0;
                    return (
                    <tr
                      key={it.contribuyenteId}
                      className={`border-b hover:bg-muted/30 ${tieneAtrasos ? 'bg-red-50/50 dark:bg-red-950/10' : ''}`}
                    >
                      <td className="px-4 py-3">
                        <Link
                          href="/configuracion/obligaciones"
                          onClick={() => setSelectedContribuyente(it.contribuyenteId, it.rfc, it.nombre)}
                          className="hover:underline"
                        >
                          <div className="flex items-center gap-2">
                            <Building2 className="h-4 w-4 text-muted-foreground" />
                            <div>
                              <div className="font-medium">{it.nombre}</div>
                              <div className="text-xs font-mono text-muted-foreground">{it.rfc}</div>
                            </div>
                          </div>
                        </Link>
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {it.carteraNombre ?? '—'}
                      </td>
                      <td className="px-4 py-3">
                        {pct === null ? (
                          <span className="text-xs text-muted-foreground">Sin datos</span>
                        ) : (
                          <div className="flex items-center gap-2" title={`${completadas} de ${total} completadas`}>
                            <div className="flex-1 h-2 rounded-full bg-muted overflow-hidden">
                              <div
                                className={`h-full transition-all ${barColor}`}
                                style={{ width: `${pct}%` }}
                              />
                            </div>
                            <span className={`text-xs font-medium tabular-nums ${
                              pct >= 80 ? 'text-success' :
                              pct >= 50 ? 'text-amber-600' :
                              'text-destructive'
                            }`}>
                              {pct}%
                            </span>
                          </div>
                        )}
                      </td>
                      <td className="px-3 py-3 text-center">
                        {tieneAtrasos ? (
                          <span
                            className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-destructive/10 text-destructive"
                            title={`Obligaciones: ${it.obligacionesAtrasadas} · Tareas: ${it.tareasAtrasadas}`}
                          >
                            <AlertTriangle className="h-3 w-3" />
                            {totalAtrasos}
                          </span>
                        ) : (
                          <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>
                        )}
                      </td>
                      <td className="px-3 py-3 text-center" title="Completadas / Pendientes">
                        <span className="text-success">{it.obligacionesCompletadas}</span>
                        <span className="text-muted-foreground"> / </span>
                        <span className={it.obligacionesPendientes > 0 ? 'text-amber-600 font-medium' : 'text-muted-foreground'}>
                          {it.obligacionesPendientes}
                        </span>
                      </td>
                      <td className="px-3 py-3 text-center" title="Completadas / Pendientes">
                        <span className="text-success">{it.tareasCompletadas}</span>
                        <span className="text-muted-foreground"> / </span>
                        <span className={it.tareasPendientes > 0 ? 'text-amber-600 font-medium' : 'text-muted-foreground'}>
                          {it.tareasPendientes}
                        </span>
                      </td>
                    </tr>
                    );
                  })}
                </tbody>
              </table>
              )}
            </CardContent>
          </Card>
        )}
      </main>
    </>
  );
}
