import { Head, Link, router } from '@inertiajs/react';
import { ChevronRight, Search } from 'lucide-react';
import type { FormEvent } from 'react';
import { useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { InertiaPaginatorFooter, type InertiaPaginatorSlice } from '@/components/inertia-paginator-footer';
import { cn } from '@/lib/utils';

type UserRow = {
    id: number;
    first_name: string;
    last_name: string;
    email: string;
    is_admin: boolean;
    kyc_status: string;
    email_verified_at: string | null;
    referral_program_enabled: boolean;
    jabes_women_enabled: boolean;
    blocked_at: string | null;
    created_at: string | null;
};

type PaginatedUsers = InertiaPaginatorSlice & { data: UserRow[] };

type FilterId = 'all' | 'kyc_review' | 'blocked' | 'unverified';

type Props = {
    users: PaginatedUsers;
    filters: {
        q: string;
        filter: FilterId;
    };
};

const FILTER_TABS: { id: FilterId; label: string }[] = [
    { id: 'all', label: 'Todos' },
    { id: 'kyc_review', label: 'KYC pendiente' },
    { id: 'blocked', label: 'Bloqueados' },
    { id: 'unverified', label: 'Sin verificar correo' },
];

const KYC_LABEL: Record<string, string> = {
    approved: 'KYC aprobado',
    requires_submission: 'KYC sin enviar',
    pending_review: 'KYC en revisión',
    rejected: 'KYC rechazado',
};

const TH = 'text-muted-foreground px-4 py-3 text-left text-xs font-medium whitespace-nowrap';

function KycBadge({ status }: { status: string }) {
    const label = KYC_LABEL[status] ?? status;

    if (status === 'approved') {
        return (
            <Badge className="text-xs font-normal" variant="secondary">
                {label}
            </Badge>
        );
    }

    if (status === 'pending_review') {
        return (
            <Badge className="border-amber-500/40 bg-amber-500/10 text-xs font-normal text-amber-700 dark:text-amber-300" variant="outline">
                {label}
            </Badge>
        );
    }

    if (status === 'rejected') {
        return (
            <Badge className="text-xs font-normal" variant="destructive">
                {label}
            </Badge>
        );
    }

    return (
        <Badge className="text-xs font-normal" variant="outline">
            {label}
        </Badge>
    );
}

export default function AdminUsersDirectory({ users, filters }: Props) {
    const [searchQuery, setSearchQuery] = useState(filters.q);

    function navigate(filter: FilterId, q = searchQuery.trim()) {
        router.get(
            '/admin/usuarios',
            { q, filter },
            { preserveState: true, replace: true },
        );
    }

    function submitSearch(event: FormEvent) {
        event.preventDefault();
        navigate(filters.filter);
    }

    return (
        <>
            <Head title="Usuarios" />

            <div className="space-y-6">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Usuarios</h1>
                    <p className="text-muted-foreground mt-1 text-sm">
                        Directorio de cuentas. Abre un usuario para editar acceso, KYC y referidos.
                    </p>
                </div>

                <nav
                    aria-label="Filtros de usuarios"
                    className="flex gap-2 overflow-x-auto border-b pb-px"
                >
                    {FILTER_TABS.map((tab) => (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => navigate(tab.id)}
                            className={cn(
                                'inline-flex shrink-0 border-b-2 px-4 py-2.5 text-sm font-medium transition-colors',
                                filters.filter === tab.id
                                    ? 'border-primary text-foreground'
                                    : 'text-muted-foreground hover:text-foreground border-transparent',
                            )}
                        >
                            {tab.label}
                        </button>
                    ))}
                </nav>

                <Card>
                    <CardHeader className="flex flex-col gap-3 border-b py-4 sm:flex-row sm:items-center sm:justify-between">
                        <CardTitle className="text-lg tabular-nums">
                            {users.total} {users.total === 1 ? 'usuario' : 'usuarios'}
                        </CardTitle>
                        <form
                            className="flex w-full items-center gap-1 sm:max-w-xs"
                            onSubmit={submitSearch}
                        >
                            <div className="relative min-w-0 flex-1">
                                <Search
                                    aria-hidden
                                    className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2"
                                />
                                <Input
                                    aria-label="Buscar usuarios"
                                    className="h-9 pl-8 text-sm"
                                    placeholder="Buscar…"
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                />
                            </div>
                            {filters.q ? (
                                <Button
                                    className="shrink-0 px-2 text-xs"
                                    type="button"
                                    variant="ghost"
                                    onClick={() => {
                                        setSearchQuery('');
                                        router.get('/admin/usuarios', { filter: filters.filter });
                                    }}
                                >
                                    Limpiar
                                </Button>
                            ) : null}
                        </form>
                    </CardHeader>
                    <CardContent className="space-y-0 p-0">
                        {users.data.length === 0 ? (
                            <p className="text-muted-foreground px-4 py-10 text-center text-sm">
                                {filters.q
                                    ? 'Sin resultados para esta búsqueda.'
                                    : 'No hay usuarios con este filtro.'}
                            </p>
                        ) : (
                            <div className="overflow-x-auto">
                                <table className="w-full table-fixed text-sm">
                                    <colgroup>
                                        <col className="w-[38%]" />
                                        <col className="w-[28%]" />
                                        <col className="w-[18%]" />
                                        <col className="w-[10%]" />
                                        <col className="w-[6%]" />
                                    </colgroup>
                                    <thead className="bg-muted/30 border-b">
                                        <tr>
                                            <th className={TH}>Usuario</th>
                                            <th className={TH}>Estado</th>
                                            <th className={TH}>Programas</th>
                                            <th className={cn(TH, 'text-right')}>Alta</th>
                                            <th className={cn(TH, 'text-right')} aria-hidden />
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {users.data.map((row) => {
                                            const name =
                                                `${row.first_name} ${row.last_name}`.trim() ||
                                                row.email;
                                            const editHref = `/admin/usuarios/${row.id}/editar`;
                                            const kycHref = `/admin/verificacion-kyc/usuarios/${row.id}`;

                                            return (
                                                <tr key={row.id} className="hover:bg-muted/20">
                                                    <td className="px-4 py-3 align-middle">
                                                        <div className="truncate font-medium">
                                                            {name}
                                                        </div>
                                                        <div className="text-muted-foreground truncate text-xs">
                                                            {row.email}
                                                        </div>
                                                        {!row.email_verified_at ? (
                                                            <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
                                                                Correo sin verificar
                                                            </p>
                                                        ) : null}
                                                    </td>
                                                    <td className="px-4 py-3 align-middle">
                                                        <div className="flex flex-wrap gap-1">
                                                            {row.is_admin ? (
                                                                <Badge
                                                                    className="text-xs font-normal"
                                                                    variant="secondary"
                                                                >
                                                                    Administrador
                                                                </Badge>
                                                            ) : null}
                                                            <KycBadge status={row.kyc_status} />
                                                            {row.blocked_at ? (
                                                                <Badge
                                                                    className="text-xs font-normal"
                                                                    variant="destructive"
                                                                >
                                                                    Bloqueado
                                                                </Badge>
                                                            ) : (
                                                                <Badge
                                                                    className="text-xs font-normal"
                                                                    variant="outline"
                                                                >
                                                                    Activo
                                                                </Badge>
                                                            )}
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3 align-middle">
                                                        {row.is_admin ? (
                                                            <span className="text-muted-foreground text-xs">
                                                                —
                                                            </span>
                                                        ) : (
                                                            <div className="flex flex-wrap gap-1">
                                                                {row.referral_program_enabled ? (
                                                                    <Badge
                                                                        className="text-xs font-normal"
                                                                        variant="outline"
                                                                    >
                                                                        Referidos
                                                                    </Badge>
                                                                ) : null}
                                                                {row.jabes_women_enabled ? (
                                                                    <Badge
                                                                        className="border-primary/30 bg-primary/10 text-primary text-xs font-normal"
                                                                        variant="outline"
                                                                    >
                                                                        JabesWomen
                                                                    </Badge>
                                                                ) : null}
                                                                {!row.referral_program_enabled &&
                                                                !row.jabes_women_enabled ? (
                                                                    <span className="text-muted-foreground text-xs">
                                                                        —
                                                                    </span>
                                                                ) : null}
                                                            </div>
                                                        )}
                                                    </td>
                                                    <td className="text-muted-foreground px-4 py-3 text-right align-middle text-xs whitespace-nowrap tabular-nums">
                                                        {row.created_at
                                                            ? new Date(
                                                                  row.created_at,
                                                              ).toLocaleDateString('es', {
                                                                  day: 'numeric',
                                                                  month: 'short',
                                                                  year: 'numeric',
                                                              })
                                                            : '—'}
                                                    </td>
                                                    <td className="px-2 py-3 text-right align-middle">
                                                        <div className="flex items-center justify-end gap-0.5">
                                                            {row.kyc_status === 'pending_review' &&
                                                            !row.is_admin ? (
                                                                <Button
                                                                    asChild
                                                                    className="hidden text-xs sm:inline-flex"
                                                                    size="sm"
                                                                    variant="ghost"
                                                                >
                                                                    <Link href={kycHref}>KYC</Link>
                                                                </Button>
                                                            ) : null}
                                                            <Button
                                                                asChild
                                                                size="icon"
                                                                variant="ghost"
                                                            >
                                                                <Link
                                                                    href={editHref}
                                                                    title="Editar usuario"
                                                                >
                                                                    <ChevronRight className="size-4" />
                                                                    <span className="sr-only">
                                                                        Editar
                                                                    </span>
                                                                </Link>
                                                            </Button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        )}

                        <InertiaPaginatorFooter paginator={users} />
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

AdminUsersDirectory.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Usuarios', href: '/admin/usuarios' },
    ],
};
