import { Head, Link, router } from '@inertiajs/react';
import { Download, Search } from 'lucide-react';
import { useState } from 'react';
import {
    EmptyState,
    PageHeader,
    Panel,
    STATUS_LABEL,
    STATUS_ORDER,
    Stat,
    StatusPill,
    area,
    count,
    money,
} from '@/components/admin/primitives';
import type { LotStatus } from '@/types/portal';

interface InventoryLot {
    id: number;
    code: string;
    project: string | null;
    projectSlug: string | null;
    block: string | null;
    lotNumber: string | null;
    area: number;
    price: number;
    pricePerMeter: number | null;
    status: LotStatus;
    dimensions: string[];
    orientation: string;
    financing: string;
    needsReview: boolean;
}

interface Paginated<T> {
    data: T[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: Array<{ url: string | null; label: string; active: boolean }>;
}

interface InventoryProps {
    lots: Paginated<InventoryLot>;
    filters: { q: string; project: string; status: string };
    totals: { lots: number; available: number; area: number; value: number };
    projects: Array<{ name: string; slug: string }>;
}

export default function Inventory({
    lots,
    filters,
    totals,
    projects,
}: InventoryProps) {
    const [search, setSearch] = useState(filters.q);

    /** Filtering happens in the database, so every change is a fresh request. */
    const apply = (next: Partial<InventoryProps['filters']>) => {
        router.get(
            '/admin/inventario',
            {
                q: next.q ?? search,
                project: next.project ?? filters.project,
                status: next.status ?? filters.status,
            },
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    const exportUrl = `/admin/inventario/exportar?${new URLSearchParams({
        q: filters.q,
        project: filters.project,
        status: filters.status,
    }).toString()}`;

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

            <div className="space-y-6 p-5">
                <PageHeader
                    eyebrow="Operación"
                    title="Inventario"
                    description="Todos los lotes de todos los proyectos. Los precios y estatus se editan dentro de cada proyecto."
                    actions={
                        <a
                            href={exportUrl}
                            className="inline-flex items-center gap-2 rounded-xl border border-border bg-card px-3.5 py-2.5 text-xs font-semibold text-foreground/85 hover:bg-muted"
                        >
                            <Download className="size-4.5" />
                            Exportar CSV
                        </a>
                    }
                />

                {totals.lots === 0 &&
                filters.q === '' &&
                filters.project === '' &&
                filters.status === '' ? (
                    <EmptyState
                        title="El inventario está vacío"
                        description="Los lotes aparecen aquí en cuanto digitalizas el plano de un proyecto."
                        action={
                            <Link
                                href="/admin/digitalizador"
                                className="inline-flex items-center gap-2 rounded-xl bg-brand px-4 py-2.5 text-xs font-semibold text-brand-foreground hover:bg-brand/90"
                            >
                                Ir al digitalizador
                            </Link>
                        }
                    />
                ) : (
                    <>
                        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                            <Stat
                                value={count(totals.lots)}
                                label="Lotes en el filtro"
                            />
                            <Stat
                                value={count(totals.available)}
                                label="Disponibles"
                            />
                            <Stat
                                value={area(totals.area)}
                                label="Superficie"
                            />
                            <Stat
                                value={money(totals.value)}
                                label="Valor listado"
                                tone="accent"
                            />
                        </div>

                        <Panel
                            title="Lotes"
                            action={
                                <span className="text-[12px] text-muted-foreground">
                                    Página {lots.current_page} de{' '}
                                    {lots.last_page} · {count(lots.total)} lotes
                                </span>
                            }
                        >
                            <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-2.5">
                                <form
                                    className="relative"
                                    onSubmit={(event) => {
                                        event.preventDefault();
                                        apply({ q: search });
                                    }}
                                >
                                    <Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
                                    <input
                                        value={search}
                                        onChange={(event) =>
                                            setSearch(event.target.value)
                                        }
                                        placeholder="Manzana, lote o clave"
                                        aria-label="Buscar en el inventario"
                                        className="w-52 rounded-lg border border-border py-2 pr-2.5 pl-9 text-[13px] outline-none focus:border-ring"
                                    />
                                </form>
                                <select
                                    value={filters.project}
                                    onChange={(event) =>
                                        apply({ project: event.target.value })
                                    }
                                    aria-label="Filtrar por proyecto"
                                    className="rounded-lg border border-border px-2.5 py-2 text-[13px] outline-none focus:border-ring"
                                >
                                    <option value="">
                                        Todos los proyectos
                                    </option>
                                    {projects.map((project) => (
                                        <option
                                            key={project.slug}
                                            value={project.slug}
                                        >
                                            {project.name}
                                        </option>
                                    ))}
                                </select>
                                <select
                                    value={filters.status}
                                    onChange={(event) =>
                                        apply({ status: event.target.value })
                                    }
                                    aria-label="Filtrar por estatus"
                                    className="rounded-lg border border-border px-2.5 py-2 text-[13px] outline-none focus:border-ring"
                                >
                                    <option value="">Todos los estatus</option>
                                    {STATUS_ORDER.map((status) => (
                                        <option key={status} value={status}>
                                            {STATUS_LABEL[status]}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            {lots.data.length === 0 ? (
                                <p className="px-4 py-10 text-center text-[13px] text-muted-foreground">
                                    Ningún lote coincide con el filtro.
                                </p>
                            ) : (
                                <div className="overflow-x-auto">
                                    <table className="w-full min-w-[900px] text-left text-[13px]">
                                        <thead className="bg-muted/50 text-[11px] font-bold tracking-[0.08em] text-muted-foreground uppercase">
                                            <tr>
                                                <th className="px-3.5 py-2.5">
                                                    Proyecto
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    Manzana
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    Lote
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    Superficie
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    Medidas
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    Precio
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    $/m²
                                                </th>
                                                <th className="px-3.5 py-2.5">
                                                    Estatus
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-border">
                                            {lots.data.map((lot) => (
                                                <tr
                                                    key={lot.id}
                                                    className="hover:bg-muted/40"
                                                >
                                                    <td className="px-3.5 py-2.5 text-foreground/75">
                                                        {lot.projectSlug ? (
                                                            <Link
                                                                href={`/admin/proyectos/${lot.projectSlug}`}
                                                                className="font-semibold text-foreground hover:underline"
                                                            >
                                                                {lot.project}
                                                            </Link>
                                                        ) : (
                                                            '—'
                                                        )}
                                                    </td>
                                                    <td className="px-3.5 py-2.5 text-foreground/75">
                                                        {lot.block ?? '—'}
                                                    </td>
                                                    <td className="px-3.5 py-2.5 font-bold text-foreground">
                                                        L-{lot.lotNumber}
                                                    </td>
                                                    <td className="px-3.5 py-2.5 text-foreground/75">
                                                        {area(lot.area)}
                                                    </td>
                                                    <td className="px-3.5 py-2.5 text-foreground/75">
                                                        {lot.dimensions.length >
                                                        0
                                                            ? lot.dimensions.join(
                                                                  ' × ',
                                                              )
                                                            : '—'}
                                                    </td>
                                                    <td className="px-3.5 py-2.5 text-foreground/75">
                                                        {lot.price > 0
                                                            ? money(lot.price)
                                                            : '—'}
                                                    </td>
                                                    <td className="px-3.5 py-2.5 text-foreground/75">
                                                        {lot.pricePerMeter
                                                            ? money(
                                                                  lot.pricePerMeter,
                                                              )
                                                            : '—'}
                                                    </td>
                                                    <td className="px-3.5 py-2.5">
                                                        <StatusPill
                                                            status={lot.status}
                                                        />
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}

                            {lots.last_page > 1 ? (
                                <div className="flex flex-wrap items-center justify-center gap-1 border-t border-border px-4 py-3">
                                    {lots.links.map((link) => (
                                        <button
                                            key={link.label}
                                            type="button"
                                            disabled={link.url === null}
                                            onClick={() =>
                                                link.url &&
                                                router.get(
                                                    link.url,
                                                    {},
                                                    {
                                                        preserveState: true,
                                                        preserveScroll: true,
                                                    },
                                                )
                                            }
                                            className={`min-w-9 rounded-lg border px-2.5 py-1.5 text-[12px] font-semibold disabled:opacity-40 ${
                                                link.active
                                                    ? 'border-brand bg-brand text-brand-foreground'
                                                    : 'border-border text-foreground/85 hover:bg-muted'
                                            }`}
                                            dangerouslySetInnerHTML={{
                                                __html: link.label,
                                            }}
                                        />
                                    ))}
                                </div>
                            ) : null}
                        </Panel>
                    </>
                )}
            </div>
        </>
    );
}
