import { Head, router, useForm } from '@inertiajs/react';
import {
    CalendarClock,
    FileText,
    MessageSquarePlus,
    Plus,
    Search,
    Trash2,
    UserRound,
    X,
} from 'lucide-react';
import { useState } from 'react';
import {
    EmptyState,
    PageHeader,
    Panel,
    Stat,
    count,
    money,
    shortDate,
} from '@/components/admin/primitives';

interface Interaction {
    id: number;
    channel: string;
    summary: string;
    stageTo: string | null;
    at: string | null;
}

interface Reservation {
    id: number;
    amount: number;
    status: string;
    expiresAt: string;
    daysLeft: number;
    active: boolean;
}

interface QuoteRow {
    id: number;
    folio: string;
    status: string;
    price: number;
    downPayment: number;
    monthly: number;
    months: number;
    validUntil: string;
    url: string;
}

interface Prospect {
    id: number;
    name: string;
    email: string | null;
    phone: string | null;
    source: string;
    stage: string;
    budget: number | null;
    notes: string | null;
    developmentId: number | null;
    project: string | null;
    lotId: number | null;
    lot: {
        id: number;
        label: string;
        area: number;
        price: number;
        status: string;
    } | null;
    reservations: Reservation[];
    quotes: QuoteRow[];
    lastContactedAt: string | null;
    nextFollowUpAt: string | null;
    createdAt: string | null;
    interactions: Interaction[];
}

interface ProjectOption {
    id: number;
    name: string;
    lots: Array<{
        id: number;
        label: string;
        status: string;
        price: number;
        area: number;
    }>;
}

interface CrmProps {
    prospects: Prospect[];
    filters: { stage: string; q: string };
    stages: string[];
    sources: string[];
    channels: string[];
    stageCounts: Record<string, number>;
    totals: { prospects: number; open: number; won: number; budget: number };
    projects: ProjectOption[];
}

const STAGE_LABEL: Record<string, string> = {
    nuevo: 'Nuevo',
    contactado: 'Contactado',
    visita: 'Visita',
    negociacion: 'Negociación',
    apartado: 'Apartado',
    cerrado: 'Cerrado',
    perdido: 'Perdido',
};

const STAGE_TONE: Record<string, string> = {
    nuevo: 'bg-muted text-muted-foreground',
    contactado: 'bg-muted text-foreground/80',
    visita: 'bg-status-held-soft text-status-held',
    negociacion: 'bg-status-held-soft text-status-held',
    apartado: 'bg-status-held-soft text-status-held',
    cerrado: 'bg-status-available-soft text-status-available',
    perdido: 'bg-status-blocked-soft text-status-blocked',
};

const emptyProspect = {
    name: '',
    email: '',
    phone: '',
    source: 'portal',
    stage: 'nuevo',
    development_id: '',
    lot_id: '',
    budget: '',
    notes: '',
    next_follow_up_at: '',
};

export default function CrmIndex({
    prospects,
    filters,
    stages,
    sources,
    channels,
    stageCounts,
    totals,
    projects,
}: CrmProps) {
    const [search, setSearch] = useState(filters.q);
    const [creating, setCreating] = useState(false);
    const [openId, setOpenId] = useState<number | null>(null);

    const applyFilters = (next: { stage?: string; q?: string }) => {
        router.get(
            '/admin/crm',
            {
                stage: next.stage ?? filters.stage,
                q: next.q ?? search,
            },
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    return (
        <>
            <Head title="CRM y prospectos" />

            <div className="space-y-6 p-5">
                <PageHeader
                    eyebrow="Comercial"
                    title="CRM y prospectos"
                    description="Cada prospecto vive ligado a un proyecto y al lote que le interesa. El historial guarda cada llamada, visita y cotización."
                    actions={
                        <button
                            type="button"
                            onClick={() => setCreating(true)}
                            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"
                        >
                            <Plus className="size-4.5" />
                            Nuevo prospecto
                        </button>
                    }
                />

                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <Stat value={count(totals.prospects)} label="Prospectos" />
                    <Stat value={count(totals.open)} label="En seguimiento" />
                    <Stat
                        value={count(totals.won)}
                        label="Cerrados"
                        hint={
                            totals.prospects > 0
                                ? `${Math.round((totals.won / totals.prospects) * 100)}% del total`
                                : undefined
                        }
                    />
                    <Stat
                        value={money(totals.budget)}
                        label="Presupuesto en pipeline"
                        tone="accent"
                    />
                </div>

                <div className="flex flex-wrap items-center gap-2">
                    <form
                        className="relative"
                        onSubmit={(event) => {
                            event.preventDefault();
                            applyFilters({ 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="Nombre, correo o teléfono"
                            aria-label="Buscar prospecto"
                            className="w-56 rounded-lg border border-border bg-card py-2 pr-2 pl-8 text-[13px] outline-none focus:border-ring"
                        />
                    </form>

                    <StageChip
                        active={filters.stage === 'all'}
                        label="Todas"
                        badge={totals.prospects}
                        onClick={() => applyFilters({ stage: 'all' })}
                    />
                    {stages.map((stage) => (
                        <StageChip
                            key={stage}
                            active={filters.stage === stage}
                            label={STAGE_LABEL[stage] ?? stage}
                            badge={stageCounts[stage] ?? 0}
                            onClick={() => applyFilters({ stage })}
                        />
                    ))}
                </div>

                {prospects.length === 0 ? (
                    <EmptyState
                        title="Sin prospectos que mostrar"
                        description="Registra el primer prospecto o cambia el filtro de etapa. Los prospectos que llegan del portal aparecen aquí automáticamente."
                        action={
                            <button
                                type="button"
                                onClick={() => setCreating(true)}
                                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"
                            >
                                <Plus className="size-4.5" />
                                Registrar prospecto
                            </button>
                        }
                    />
                ) : (
                    <Panel
                        title="Prospectos"
                        action={
                            <span className="text-[12px] text-muted-foreground">
                                {count(prospects.length)} en la vista
                            </span>
                        }
                    >
                        <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 py-2">Prospecto</th>
                                        <th className="px-3 py-2">Contacto</th>
                                        <th className="px-3 py-2">Proyecto</th>
                                        <th className="px-3 py-2">Lote</th>
                                        <th className="px-3 py-2">
                                            Presupuesto
                                        </th>
                                        <th className="px-3 py-2">Etapa</th>
                                        <th className="px-3 py-2">
                                            Próximo contacto
                                        </th>
                                        <th className="px-3 py-2" />
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border">
                                    {prospects.map((prospect) => (
                                        <tr
                                            key={prospect.id}
                                            className="hover:bg-muted/40"
                                        >
                                            <td className="px-3.5 py-3">
                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        setOpenId(prospect.id)
                                                    }
                                                    className="text-left font-bold text-foreground hover:underline"
                                                >
                                                    {prospect.name}
                                                </button>
                                                <p className="mt-0.5 text-[12px] text-muted-foreground">
                                                    {prospect.source} ·{' '}
                                                    {shortDate(
                                                        prospect.createdAt,
                                                    )}
                                                </p>
                                            </td>
                                            <td className="px-3.5 py-3 text-foreground/75">
                                                {prospect.phone ?? '—'}
                                                <p className="text-[12px] text-muted-foreground">
                                                    {prospect.email ?? ''}
                                                </p>
                                            </td>
                                            <td className="px-3.5 py-3 text-foreground/75">
                                                {prospect.project ?? '—'}
                                            </td>
                                            <td className="px-3.5 py-3 text-foreground/75">
                                                {prospect.lot?.label ?? '—'}
                                            </td>
                                            <td className="px-3.5 py-3 text-foreground/75">
                                                {prospect.budget
                                                    ? money(prospect.budget)
                                                    : '—'}
                                            </td>
                                            <td className="px-3.5 py-3">
                                                <span
                                                    className={`inline-flex rounded-md px-2.5 py-1.5 text-[12px] font-bold ${STAGE_TONE[prospect.stage] ?? ''}`}
                                                >
                                                    {STAGE_LABEL[
                                                        prospect.stage
                                                    ] ?? prospect.stage}
                                                </span>
                                            </td>
                                            <td className="px-3.5 py-3 text-foreground/75">
                                                {prospect.nextFollowUpAt ? (
                                                    <span
                                                        className={
                                                            new Date(
                                                                prospect.nextFollowUpAt,
                                                            ) < new Date()
                                                                ? 'font-bold text-destructive'
                                                                : ''
                                                        }
                                                    >
                                                        {shortDate(
                                                            prospect.nextFollowUpAt,
                                                        )}
                                                    </span>
                                                ) : (
                                                    '—'
                                                )}
                                            </td>
                                            <td className="px-3.5 py-3 text-right">
                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        setOpenId(prospect.id)
                                                    }
                                                    className="rounded-lg border border-border px-2.5 py-1.5 text-[12px] font-semibold text-foreground/85 hover:bg-muted"
                                                >
                                                    Abrir
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </Panel>
                )}
            </div>

            {creating ? (
                <ProspectDialog
                    title="Nuevo prospecto"
                    projects={projects}
                    stages={stages}
                    sources={sources}
                    initial={emptyProspect}
                    action="/admin/crm"
                    method="post"
                    onClose={() => setCreating(false)}
                />
            ) : null}

            {openId !== null ? (
                <ProspectDrawer
                    prospect={
                        prospects.find(
                            (prospect) => prospect.id === openId,
                        ) as Prospect
                    }
                    projects={projects}
                    stages={stages}
                    sources={sources}
                    channels={channels}
                    onClose={() => setOpenId(null)}
                />
            ) : null}
        </>
    );
}

function StageChip({
    active,
    label,
    badge,
    onClick,
}: {
    active: boolean;
    label: string;
    badge: number;
    onClick: () => void;
}) {
    return (
        <button
            type="button"
            onClick={onClick}
            className={`flex items-center gap-1.5 rounded-lg border px-3.5 py-3 text-[13px] font-semibold ${
                active
                    ? 'border-brand bg-brand text-brand-foreground'
                    : 'border-border bg-card text-foreground/85 hover:bg-muted'
            }`}
        >
            {label}
            <span
                className={`rounded px-1 text-[11px] ${active ? 'bg-card/20' : 'bg-muted'}`}
            >
                {badge}
            </span>
        </button>
    );
}

function ProspectDialog({
    title,
    projects,
    stages,
    sources,
    initial,
    action,
    method,
    onClose,
}: {
    title: string;
    projects: ProjectOption[];
    stages: string[];
    sources: string[];
    initial: typeof emptyProspect;
    action: string;
    method: 'post' | 'put';
    onClose: () => void;
}) {
    const form = useForm(initial);
    const project = projects.find(
        (item) => String(item.id) === form.data.development_id,
    );

    return (
        <Modal title={title} onClose={onClose}>
            <form
                onSubmit={(event) => {
                    event.preventDefault();
                    form[method](action, {
                        preserveScroll: true,
                        onSuccess: onClose,
                    });
                }}
                className="space-y-3"
            >
                <div className="grid gap-3 sm:grid-cols-2">
                    <Labeled label="Nombre" error={form.errors.name}>
                        <input
                            value={form.data.name}
                            onChange={(event) =>
                                form.setData('name', event.target.value)
                            }
                            required
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        />
                    </Labeled>
                    <Labeled label="Teléfono">
                        <input
                            value={form.data.phone}
                            onChange={(event) =>
                                form.setData('phone', event.target.value)
                            }
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        />
                    </Labeled>
                    <Labeled label="Correo" error={form.errors.email}>
                        <input
                            type="email"
                            value={form.data.email}
                            onChange={(event) =>
                                form.setData('email', event.target.value)
                            }
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        />
                    </Labeled>
                    <Labeled label="Origen">
                        <select
                            value={form.data.source}
                            onChange={(event) =>
                                form.setData('source', event.target.value)
                            }
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        >
                            {sources.map((source) => (
                                <option key={source} value={source}>
                                    {source}
                                </option>
                            ))}
                        </select>
                    </Labeled>
                    <Labeled label="Proyecto">
                        <select
                            value={form.data.development_id}
                            onChange={(event) => {
                                form.setData(
                                    'development_id',
                                    event.target.value,
                                );
                                form.setData('lot_id', '');
                            }}
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        >
                            <option value="">Sin proyecto</option>
                            {projects.map((item) => (
                                <option key={item.id} value={item.id}>
                                    {item.name}
                                </option>
                            ))}
                        </select>
                    </Labeled>
                    <Labeled label="Lote de interés">
                        <select
                            value={form.data.lot_id}
                            onChange={(event) =>
                                form.setData('lot_id', event.target.value)
                            }
                            disabled={!project}
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring disabled:bg-background"
                        >
                            <option value="">Sin lote</option>
                            {(project?.lots ?? []).map((lot) => (
                                <option key={lot.id} value={lot.id}>
                                    {lot.label} · {lot.status}
                                </option>
                            ))}
                        </select>
                    </Labeled>
                    <Labeled label="Presupuesto">
                        <input
                            type="number"
                            min={0}
                            step="0.01"
                            value={form.data.budget}
                            onChange={(event) =>
                                form.setData('budget', event.target.value)
                            }
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        />
                    </Labeled>
                    <Labeled label="Etapa">
                        <select
                            value={form.data.stage}
                            onChange={(event) =>
                                form.setData('stage', event.target.value)
                            }
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        >
                            {stages.map((stage) => (
                                <option key={stage} value={stage}>
                                    {STAGE_LABEL[stage] ?? stage}
                                </option>
                            ))}
                        </select>
                    </Labeled>
                    <Labeled label="Próximo contacto">
                        <input
                            type="date"
                            value={form.data.next_follow_up_at}
                            onChange={(event) =>
                                form.setData(
                                    'next_follow_up_at',
                                    event.target.value,
                                )
                            }
                            className="w-full rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                        />
                    </Labeled>
                </div>

                <Labeled label="Notas">
                    <textarea
                        value={form.data.notes}
                        onChange={(event) =>
                            form.setData('notes', event.target.value)
                        }
                        className="min-h-20 w-full resize-y rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                    />
                </Labeled>

                <div className="flex justify-end gap-2 pt-1">
                    <button
                        type="button"
                        onClick={onClose}
                        className="rounded-xl border border-border px-3.5 py-2.5 text-[13px] font-semibold text-foreground/85 hover:bg-muted"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        disabled={form.processing}
                        className="rounded-xl bg-brand px-4 py-2.5 text-[13px] font-bold text-brand-foreground hover:bg-brand/90 disabled:bg-muted-foreground/40"
                    >
                        Guardar
                    </button>
                </div>
            </form>
        </Modal>
    );
}

function ProspectDrawer({
    prospect,
    projects,
    stages,
    sources,
    channels,
    onClose,
}: {
    prospect: Prospect;
    projects: ProjectOption[];
    stages: string[];
    sources: string[];
    channels: string[];
    onClose: () => void;
}) {
    const [editing, setEditing] = useState(false);
    const log = useForm({
        channel: 'llamada',
        summary: '',
        stage: prospect.stage,
        next_follow_up_at: '',
    });

    if (editing) {
        return (
            <ProspectDialog
                title={`Editar ${prospect.name}`}
                projects={projects}
                stages={stages}
                sources={sources}
                initial={{
                    name: prospect.name,
                    email: prospect.email ?? '',
                    phone: prospect.phone ?? '',
                    source: prospect.source,
                    stage: prospect.stage,
                    development_id: prospect.developmentId
                        ? String(prospect.developmentId)
                        : '',
                    lot_id: prospect.lotId ? String(prospect.lotId) : '',
                    budget: prospect.budget ? String(prospect.budget) : '',
                    notes: prospect.notes ?? '',
                    next_follow_up_at: prospect.nextFollowUpAt
                        ? prospect.nextFollowUpAt.slice(0, 10)
                        : '',
                }}
                action={`/admin/crm/${prospect.id}`}
                method="put"
                onClose={() => setEditing(false)}
            />
        );
    }

    return (
        <Modal title={prospect.name} onClose={onClose}>
            <div className="space-y-4">
                <div className="grid grid-cols-2 gap-2 text-[13px]">
                    <Info label="Teléfono" value={prospect.phone ?? '—'} />
                    <Info label="Correo" value={prospect.email ?? '—'} />
                    <Info label="Proyecto" value={prospect.project ?? '—'} />
                    <Info label="Lote" value={prospect.lot?.label ?? '—'} />
                    <Info
                        label="Presupuesto"
                        value={prospect.budget ? money(prospect.budget) : '—'}
                    />
                    <Info
                        label="Etapa"
                        value={STAGE_LABEL[prospect.stage] ?? prospect.stage}
                    />
                    <Info
                        label="Último contacto"
                        value={shortDate(prospect.lastContactedAt)}
                    />
                    <Info
                        label="Próximo contacto"
                        value={shortDate(prospect.nextFollowUpAt)}
                    />
                </div>

                {prospect.notes ? (
                    <p className="rounded-xl bg-muted/50 px-3.5 py-3 text-[13px] leading-5 text-foreground/75">
                        {prospect.notes}
                    </p>
                ) : null}

                <CommercialActions prospect={prospect} />

                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        log.post(`/admin/crm/${prospect.id}/interacciones`, {
                            preserveScroll: true,
                            onSuccess: () => log.reset('summary'),
                        });
                    }}
                    className="rounded-xl border border-border p-3"
                >
                    <p className="flex items-center gap-1.5 text-[12px] font-bold tracking-[0.08em] text-foreground/75 uppercase">
                        <MessageSquarePlus className="size-3.5" />
                        Registrar interacción
                    </p>
                    <div className="mt-2.5 grid gap-2 sm:grid-cols-3">
                        <select
                            value={log.data.channel}
                            onChange={(event) =>
                                log.setData('channel', event.target.value)
                            }
                            aria-label="Canal"
                            className="rounded-lg border border-border px-2 py-2 text-[13px] outline-none focus:border-ring"
                        >
                            {channels.map((channel) => (
                                <option key={channel} value={channel}>
                                    {channel}
                                </option>
                            ))}
                        </select>
                        <select
                            value={log.data.stage}
                            onChange={(event) =>
                                log.setData('stage', event.target.value)
                            }
                            aria-label="Etapa resultante"
                            className="rounded-lg border border-border px-2 py-2 text-[13px] outline-none focus:border-ring"
                        >
                            {stages.map((stage) => (
                                <option key={stage} value={stage}>
                                    {STAGE_LABEL[stage] ?? stage}
                                </option>
                            ))}
                        </select>
                        <input
                            type="date"
                            value={log.data.next_follow_up_at}
                            onChange={(event) =>
                                log.setData(
                                    'next_follow_up_at',
                                    event.target.value,
                                )
                            }
                            aria-label="Próximo contacto"
                            className="rounded-lg border border-border px-2 py-2 text-[13px] outline-none focus:border-ring"
                        />
                    </div>
                    <textarea
                        value={log.data.summary}
                        onChange={(event) =>
                            log.setData('summary', event.target.value)
                        }
                        required
                        placeholder="Qué se habló, qué quedó pendiente…"
                        className="mt-2 min-h-16 w-full resize-y rounded-lg border border-border px-3.5 py-3 text-[13px] outline-none focus:border-ring"
                    />
                    <button
                        type="submit"
                        disabled={log.processing || log.data.summary === ''}
                        className="mt-2 w-full rounded-lg bg-brand py-2 text-[13px] font-bold text-brand-foreground hover:bg-brand/90 disabled:bg-muted-foreground/40"
                    >
                        Guardar interacción
                    </button>
                </form>

                <div>
                    <p className="flex items-center gap-1.5 text-[12px] font-bold tracking-[0.08em] text-foreground/75 uppercase">
                        <CalendarClock className="size-3.5" />
                        Historial
                    </p>
                    {prospect.interactions.length === 0 ? (
                        <p className="mt-2 text-[13px] text-muted-foreground">
                            Sin interacciones registradas.
                        </p>
                    ) : (
                        <ul className="mt-2 space-y-2">
                            {prospect.interactions.map((interaction) => (
                                <li
                                    key={interaction.id}
                                    className="rounded-xl border border-border px-3 py-2"
                                >
                                    <p className="flex items-center justify-between text-[12px] font-bold text-foreground/75">
                                        <span className="uppercase">
                                            {interaction.channel}
                                        </span>
                                        <span className="font-normal text-muted-foreground">
                                            {shortDate(interaction.at)}
                                        </span>
                                    </p>
                                    <p className="mt-1 text-[13px] leading-5 text-foreground/85">
                                        {interaction.summary}
                                    </p>
                                </li>
                            ))}
                        </ul>
                    )}
                </div>

                <div className="flex justify-between gap-2 border-t border-border pt-3">
                    <button
                        type="button"
                        onClick={() => {
                            if (
                                window.confirm(
                                    `¿Eliminar el prospecto ${prospect.name}?`,
                                )
                            ) {
                                router.delete(`/admin/crm/${prospect.id}`, {
                                    onSuccess: onClose,
                                });
                            }
                        }}
                        className="inline-flex items-center gap-1.5 rounded-xl border border-destructive/40 px-3 py-2 text-[13px] font-semibold text-destructive hover:bg-destructive/10"
                    >
                        <Trash2 className="size-4" />
                        Eliminar
                    </button>
                    <button
                        type="button"
                        onClick={() => setEditing(true)}
                        className="inline-flex items-center gap-1.5 rounded-xl bg-brand px-4 py-2 text-[13px] font-bold text-brand-foreground hover:bg-brand/90"
                    >
                        <UserRound className="size-4" />
                        Editar ficha
                    </button>
                </div>
            </div>
        </Modal>
    );
}

function CommercialActions({ prospect }: { prospect: Prospect }) {
    const [panel, setPanel] = useState<'none' | 'reserve' | 'quote'>('none');
    const hold = prospect.reservations.find((item) => item.active) ?? null;

    const reserve = useForm({
        lot_id: prospect.lot?.id ?? '',
        prospect_id: prospect.id,
        amount: '',
        days: '15',
        notes: '',
    });

    const quote = useForm({
        lot_id: prospect.lot?.id ?? '',
        prospect_id: prospect.id,
        down_payment: '',
        months: '60',
        valid_days: '15',
        notes: '',
    });

    if (prospect.lot === null) {
        return (
            <p className="rounded-xl border border-dashed border-border px-3 py-3 text-[12px] text-muted-foreground">
                Asigna un lote de interés a este prospecto para poder apartarlo
                o cotizarlo.
            </p>
        );
    }

    return (
        <section className="rounded-xl border border-border p-3">
            <p className="flex items-center gap-1.5 text-[11px] font-bold tracking-[0.08em] text-foreground/75 uppercase">
                <FileText className="size-3.5" />
                Lote {prospect.lot.label}
            </p>

            {hold ? (
                <div className="mt-2.5 rounded-lg border border-status-held/40 bg-status-held-soft px-3 py-2.5">
                    <p className="text-[12px] font-bold text-status-held">
                        Apartado vigente · {money(hold.amount)}
                    </p>
                    <p className="mt-0.5 text-[12px] text-status-held">
                        Vence el {shortDate(hold.expiresAt)} ·{' '}
                        {hold.daysLeft === 0
                            ? 'vence hoy'
                            : `${hold.daysLeft} días restantes`}
                    </p>
                    <div className="mt-2.5 flex flex-wrap gap-1.5">
                        <HoldAction id={hold.id} action="convert">
                            Convertir en venta
                        </HoldAction>
                        <HoldAction id={hold.id} action="extend" days={15}>
                            +15 días
                        </HoldAction>
                        <HoldAction id={hold.id} action="cancel" danger>
                            Cancelar
                        </HoldAction>
                    </div>
                </div>
            ) : null}

            <div className="mt-2.5 flex gap-2">
                {hold === null && prospect.lot.status !== 'sold' ? (
                    <button
                        type="button"
                        onClick={() =>
                            setPanel(panel === 'reserve' ? 'none' : 'reserve')
                        }
                        className="flex-1 rounded-lg border border-border px-3 py-2 text-[12px] font-bold text-foreground/85 hover:bg-muted"
                    >
                        Apartar lote
                    </button>
                ) : null}
                <button
                    type="button"
                    onClick={() =>
                        setPanel(panel === 'quote' ? 'none' : 'quote')
                    }
                    className="flex-1 rounded-lg border border-border px-3 py-2 text-[12px] font-bold text-foreground/85 hover:bg-muted"
                >
                    Cotizar
                </button>
            </div>

            {panel === 'reserve' ? (
                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        reserve.post('/admin/apartados', {
                            preserveScroll: true,
                            onSuccess: () => setPanel('none'),
                        });
                    }}
                    className="mt-2.5 space-y-2 rounded-lg bg-muted/50 p-3"
                >
                    <div className="grid grid-cols-2 gap-2">
                        <SmallField label="Monto del apartado">
                            <input
                                value={reserve.data.amount}
                                onChange={(event) =>
                                    reserve.setData(
                                        'amount',
                                        event.target.value,
                                    )
                                }
                                inputMode="decimal"
                                placeholder="10000"
                                required
                                className="w-full rounded-lg border border-border bg-card px-2.5 py-2 text-[12px] outline-none focus:border-ring"
                            />
                        </SmallField>
                        <SmallField label="Vigencia (días)">
                            <input
                                value={reserve.data.days}
                                onChange={(event) =>
                                    reserve.setData('days', event.target.value)
                                }
                                inputMode="numeric"
                                required
                                className="w-full rounded-lg border border-border bg-card px-2.5 py-2 text-[12px] outline-none focus:border-ring"
                            />
                        </SmallField>
                    </div>
                    {reserve.errors.lot_id ? (
                        <p className="text-[12px] text-destructive">
                            {reserve.errors.lot_id}
                        </p>
                    ) : null}
                    <button
                        type="submit"
                        disabled={reserve.processing}
                        className="w-full rounded-lg bg-brand py-2 text-[12px] font-bold text-brand-foreground hover:bg-brand/90 disabled:bg-muted-foreground/40"
                    >
                        Apartar
                    </button>
                </form>
            ) : null}

            {panel === 'quote' ? (
                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        quote.post('/admin/cotizaciones', {
                            preserveScroll: true,
                            onSuccess: () => setPanel('none'),
                        });
                    }}
                    className="mt-2.5 space-y-2 rounded-lg bg-muted/50 p-3"
                >
                    <div className="grid grid-cols-3 gap-2">
                        <SmallField label="Enganche">
                            <input
                                value={quote.data.down_payment}
                                onChange={(event) =>
                                    quote.setData(
                                        'down_payment',
                                        event.target.value,
                                    )
                                }
                                inputMode="decimal"
                                placeholder="178500"
                                required
                                className="w-full rounded-lg border border-border bg-card px-2.5 py-2 text-[12px] outline-none focus:border-ring"
                            />
                        </SmallField>
                        <SmallField label="Meses">
                            <input
                                value={quote.data.months}
                                onChange={(event) =>
                                    quote.setData('months', event.target.value)
                                }
                                inputMode="numeric"
                                required
                                className="w-full rounded-lg border border-border bg-card px-2.5 py-2 text-[12px] outline-none focus:border-ring"
                            />
                        </SmallField>
                        <SmallField label="Vigencia">
                            <input
                                value={quote.data.valid_days}
                                onChange={(event) =>
                                    quote.setData(
                                        'valid_days',
                                        event.target.value,
                                    )
                                }
                                inputMode="numeric"
                                required
                                className="w-full rounded-lg border border-border bg-card px-2.5 py-2 text-[12px] outline-none focus:border-ring"
                            />
                        </SmallField>
                    </div>
                    {quote.errors.lot_id || quote.errors.down_payment ? (
                        <p className="text-[12px] text-destructive">
                            {quote.errors.lot_id ?? quote.errors.down_payment}
                        </p>
                    ) : null}
                    <button
                        type="submit"
                        disabled={quote.processing}
                        className="w-full rounded-lg bg-brand py-2 text-[12px] font-bold text-brand-foreground hover:bg-brand/90 disabled:bg-muted-foreground/40"
                    >
                        Generar cotización
                    </button>
                </form>
            ) : null}

            {prospect.quotes.length > 0 ? (
                <ul className="mt-2.5 space-y-1.5">
                    {prospect.quotes.map((item) => (
                        <li
                            key={item.id}
                            className="flex items-center justify-between gap-2 rounded-lg border border-border px-2.5 py-2"
                        >
                            <span className="min-w-0">
                                <span className="block truncate text-[12px] font-bold text-foreground">
                                    {item.folio}
                                </span>
                                <span className="block text-[12px] text-muted-foreground">
                                    {money(item.monthly)} × {item.months} ·
                                    vence {shortDate(item.validUntil)}
                                </span>
                            </span>
                            <a
                                href={item.url}
                                target="_blank"
                                rel="noreferrer"
                                className="shrink-0 rounded-lg border border-border px-2.5 py-1.5 text-[12px] font-bold text-foreground/85 hover:bg-muted"
                            >
                                Abrir
                            </a>
                        </li>
                    ))}
                </ul>
            ) : null}
        </section>
    );
}

function HoldAction({
    id,
    action,
    days,
    danger,
    children,
}: {
    id: number;
    action: 'convert' | 'cancel' | 'extend';
    days?: number;
    danger?: boolean;
    children: React.ReactNode;
}) {
    return (
        <button
            type="button"
            onClick={() =>
                router.put(
                    `/admin/apartados/${id}`,
                    { action, ...(days ? { days } : {}) },
                    { preserveScroll: true },
                )
            }
            className={`rounded-lg border px-2.5 py-1.5 text-[12px] font-bold ${
                danger
                    ? 'border-destructive/40 text-destructive hover:bg-destructive/10'
                    : 'border-border bg-card text-foreground/85 hover:bg-muted'
            }`}
        >
            {children}
        </button>
    );
}

function SmallField({
    label,
    children,
}: {
    label: string;
    children: React.ReactNode;
}) {
    return (
        <label className="block">
            <span className="mb-1 block text-[11px] font-bold tracking-[0.06em] text-muted-foreground uppercase">
                {label}
            </span>
            {children}
        </label>
    );
}

function Modal({
    title,
    onClose,
    children,
}: {
    title: string;
    onClose: () => void;
    children: React.ReactNode;
}) {
    return (
        <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/55 p-4 backdrop-blur-sm">
            <div className="my-8 w-full max-w-2xl rounded-2xl border border-border bg-card shadow-xl">
                <div className="flex items-center justify-between border-b border-border px-4 py-3">
                    <h2 className="text-sm font-bold text-foreground">
                        {title}
                    </h2>
                    <button
                        type="button"
                        onClick={onClose}
                        aria-label="Cerrar"
                        className="rounded-lg p-1 text-muted-foreground hover:bg-muted"
                    >
                        <X className="size-4.5" />
                    </button>
                </div>
                <div className="p-4">{children}</div>
            </div>
        </div>
    );
}

function Labeled({
    label,
    error,
    children,
}: {
    label: string;
    error?: string;
    children: React.ReactNode;
}) {
    return (
        <label className="block">
            <span className="mb-1 block text-[11px] font-bold tracking-[0.08em] text-muted-foreground uppercase">
                {label}
            </span>
            {children}
            {error ? (
                <span className="mt-1 block text-[12px] text-destructive">
                    {error}
                </span>
            ) : null}
        </label>
    );
}

function Info({ label, value }: { label: string; value: string }) {
    return (
        <div className="rounded-lg border border-border px-3.5 py-3">
            <span className="text-[11px] font-bold tracking-[0.08em] text-muted-foreground uppercase">
                {label}
            </span>
            <b className="mt-0.5 block text-[13px] font-semibold text-foreground">
                {value}
            </b>
        </div>
    );
}
