import { Head, Link, router } from '@inertiajs/react';
import { ChevronRight, Search, ShieldCheck } from 'lucide-react';
import clsx from 'clsx';
import { useEffect, useState } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { Flash } from '@/components/Flash';
import { FilterSelect } from '@/components/dashboard';
import { Paginacion } from '@/components/Paginacion';
import { AvatarUsuario, EQUIPOS, equipoDe, EtiquetaEstado, EtiquetaRol, NuevoUsuario, ROL, TIPO_ALCANCE, visibilidad, type DatosUsuarios, type Equipo } from '@/components/admin-usuarios';
import { Input } from '@/components/ui/input';

const POR_PAGINA = 10;

/**
 * Administración → Usuarios: quién tiene acceso al BI, de qué equipo es y qué puede ver.
 * Las pestañas de equipo filtran; un clic en la fila abre la ficha (/admin/usuarios/{id}).
 */
export default function Usuarios(props: DatosUsuarios) {
    const { perfiles, scopes, dashboards, overrides, catalogos } = props;
    const [equipo, setEquipo] = useState<Equipo | 'todos'>('todos');
    const [buscar, setBuscar] = useState('');
    const [rol, setRol] = useState('TODOS');
    const [estado, setEstado] = useState('TODOS');
    const [pagina, setPagina] = useState(1);

    const norm = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
    const rolesElegidos = rol === 'TODOS' ? null : rol.split('|');
    const lista = perfiles.filter(
        (p) =>
            (equipo === 'todos' || equipoDe(p.role) === equipo) &&
            (!buscar || norm(`${p.full_name} ${p.email}`).includes(norm(buscar))) &&
            (!rolesElegidos || rolesElegidos.includes(ROL[p.role] ?? p.role)) &&
            (estado === 'TODOS' || (estado === 'Activos') === p.is_active),
    );
    useEffect(() => setPagina(1), [equipo, buscar, rol, estado]);

    const totalPaginas = Math.max(1, Math.ceil(lista.length / POR_PAGINA));
    const pag = Math.min(pagina, totalPaginas);
    const visibles = lista.slice((pag - 1) * POR_PAGINA, pag * POR_PAGINA);
    const rolesDelEquipo = (equipo === 'todos' ? catalogos.roles : EQUIPOS[equipo].roles).map((r) => ROL[r] ?? r);
    const activos = perfiles.filter((p) => p.is_active).length;

    const Pestana = ({ id, nombre, n, color }: { id: Equipo | 'todos'; nombre: string; n: number; color?: string }) => (
        <button
            type="button"
            onClick={() => (setEquipo(id), setRol('TODOS'))}
            className={clsx(
                'flex items-center gap-2 rounded-lg border px-3.5 py-2 text-sm transition-colors',
                equipo === id ? 'border-slate-300 bg-white font-semibold shadow-sm' : 'border-transparent text-muted-foreground hover:bg-white/70 hover:text-foreground',
            )}
        >
            {color && <span className="size-2.5 rounded-full" style={{ background: color }} />}
            {nombre}
            <span className={clsx('rounded-full px-1.5 text-xs tabular-nums', equipo === id ? 'bg-slate-100 text-foreground' : 'text-muted-foreground')}>{n}</span>
        </button>
    );

    return (
        <AppLayout>
            <Head title="Usuarios" />
            <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">Usuarios</h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {activos} de {perfiles.length} personas con acceso activo al BI.
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <Link href="/admin/roles" className="inline-flex h-9 items-center gap-2 rounded-md border border-border bg-white px-3 text-sm font-medium hover:bg-muted">
                        <ShieldCheck className="size-4 text-muted-foreground" /> Roles y permisos
                    </Link>
                    <NuevoUsuario roles={catalogos.roles} />
                </div>
            </div>

            <Flash />

            {/* Equipos */}
            <div className="mb-4 flex flex-wrap gap-1 rounded-xl bg-slate-100/80 p-1">
                <Pestana id="todos" nombre="Todos" n={perfiles.length} />
                {(Object.keys(EQUIPOS) as Equipo[]).map((e) => (
                    <Pestana key={e} id={e} nombre={EQUIPOS[e].nombre} n={perfiles.filter((p) => equipoDe(p.role) === e).length} color={EQUIPOS[e].solido} />
                ))}
            </div>

            <div className="overflow-hidden rounded-xl border border-border bg-white">
                {/* Búsqueda y filtros */}
                <div className="flex flex-wrap items-center gap-2 border-b border-border p-3">
                    <div className="relative min-w-60 flex-1 sm:max-w-80">
                        <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                        <Input value={buscar} onChange={(e) => setBuscar(e.target.value)} placeholder="Buscar por nombre o correo" className="h-10 pl-9" />
                    </div>
                    <FilterSelect multiple label="Rol" value={rol} all="TODOS" options={rolesDelEquipo} onChange={setRol} />
                    <FilterSelect label="Estado" value={estado} all="TODOS" options={['Activos', 'Inactivos']} onChange={setEstado} />
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-border bg-slate-50 text-left text-xs text-muted-foreground">
                                <th className="px-4 py-3 font-medium">Persona</th>
                                <th className="px-4 py-3 font-medium">Rol</th>
                                <th className="px-4 py-3 font-medium">Estado</th>
                                <th className="px-4 py-3 font-medium">Alcance de datos</th>
                                <th className="px-4 py-3 font-medium">Pantallas que ve</th>
                                <th className="w-10" />
                            </tr>
                        </thead>
                        <tbody>
                            {visibles.map((p) => {
                                const alc = scopes.filter((s) => s.user_id === p.user_id);
                                const ven = dashboards.filter((d) => visibilidad(props, p, d.route).v).length;
                                const exc = overrides.filter((o) => o.user_id === p.user_id).length;
                                const eq = EQUIPOS[equipoDe(p.role)];
                                return (
                                    <tr
                                        key={p.user_id}
                                        tabIndex={0}
                                        onClick={() => router.visit(`/admin/usuarios/${p.user_id}`)}
                                        onKeyDown={(e) => e.key === 'Enter' && router.visit(`/admin/usuarios/${p.user_id}`)}
                                        className="group cursor-pointer border-b border-border last:border-0 hover:bg-slate-50 focus-visible:bg-slate-50 focus-visible:outline-none"
                                    >
                                        <td className="px-4 py-3">
                                            <div className="flex items-center gap-3">
                                                <AvatarUsuario nombre={p.full_name} role={p.role} activo={p.is_active} />
                                                <div className="min-w-0">
                                                    <p className="truncate font-medium">{p.full_name}</p>
                                                    <p className="truncate text-xs text-muted-foreground">{p.email}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-4 py-3">
                                            <EtiquetaRol role={p.role} />
                                        </td>
                                        <td className="px-4 py-3">
                                            <EtiquetaEstado activo={p.is_active} />
                                        </td>
                                        <td className="max-w-80 px-4 py-3 text-xs">
                                            {['admin', 'ejecutivo'].includes(p.role) ? (
                                                <span className="text-muted-foreground">Toda la información</span>
                                            ) : alc.length === 0 ? (
                                                <span className="text-amber-700">Sin alcance configurado</span>
                                            ) : (
                                                <span className="flex flex-wrap gap-1">
                                                    {alc.slice(0, 3).map((s) => (
                                                        <span key={s.id} className="rounded-md bg-slate-100 px-1.5 py-0.5 text-slate-700">
                                                            <span className="text-slate-500">{TIPO_ALCANCE[s.scope_type] ?? s.scope_type}</span> {s.scope_value ?? s.etiqueta}
                                                        </span>
                                                    ))}
                                                    {alc.length > 3 && <span className="px-1 py-0.5 text-muted-foreground">+{alc.length - 3} más</span>}
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3 text-xs">
                                            <div className="flex items-center gap-2">
                                                <div className="h-1.5 w-20 overflow-hidden rounded-full bg-slate-100" role="img" aria-label={`${ven} de ${dashboards.length} pantallas`}>
                                                    <div className="h-full rounded-full" style={{ width: `${(ven / dashboards.length) * 100}%`, background: eq.solido }} />
                                                </div>
                                                <span className="tabular-nums whitespace-nowrap">
                                                    {ven} de {dashboards.length}
                                                </span>
                                            </div>
                                            {exc > 0 && <p className="mt-1 text-amber-700">{exc === 1 ? '1 excepción personal' : `${exc} excepciones personales`}</p>}
                                        </td>
                                        <td className="pr-3 text-slate-300 group-hover:text-slate-500">
                                            <ChevronRight className="size-4" />
                                        </td>
                                    </tr>
                                );
                            })}
                            {visibles.length === 0 && (
                                <tr>
                                    <td colSpan={6} className="px-4 py-12 text-center">
                                        <p className="font-medium">Nadie coincide con esa búsqueda</p>
                                        <p className="mt-1 text-sm text-muted-foreground">Prueba con otro nombre o quita algún filtro.</p>
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>

                <Paginacion pagina={pag} total={lista.length} porPagina={POR_PAGINA} onChange={setPagina} />
            </div>
        </AppLayout>
    );
}
