import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Check, MousePointer2, Ruler, Share2 } from 'lucide-react';
import { useMemo, useState } from 'react';
import { MasterplanViewer } from '@/components/plan/masterplan-viewer';
import { LeadForm } from '@/components/portal/lead-form';
import { PaymentSimulator } from '@/components/portal/payment-simulator';
import { formatMoney } from '@/data/portal';
import type { MasterplanFrame, MasterplanLot } from '@/types/masterplan';
import type { LotStatus } from '@/types/portal';

interface PublicLot extends MasterplanLot {
    price: number;
    orientation: string;
    financing: string;
}

interface ExplorerProps {
    project: {
        name: string;
        slug: string;
        location: string;
        headline: string | null;
        projectUrl: string;
        whatsapp: string | null;
        downPaymentPercent: number | null;
        financingMonths: number | null;
    } | null;
    frame: MasterplanFrame | null;
    basePlanUrl: string | null;
    lots: PublicLot[];
    projects: Array<{ name: string; slug: string }>;
}

const STATUS_LABEL: Record<LotStatus, string> = {
    available: 'Disponible',
    held: 'Apartado',
    sold: 'Vendido',
    blocked: 'No disponible',
};

export default function PortalExplorer({
    project,
    frame,
    basePlanUrl,
    lots,
    projects,
}: ExplorerProps) {
    const [selectedId, setSelectedId] = useState<string | null>(null);
    const [shared, setShared] = useState(false);

    const selected = useMemo(
        () => lots.find((lot) => lot.id === selectedId) ?? null,
        [lots, selectedId],
    );

    const counts = useMemo(
        () => ({
            available: lots.filter((lot) => lot.status === 'available').length,
            held: lots.filter((lot) => lot.status === 'held').length,
            sold: lots.filter((lot) => lot.status === 'sold').length,
        }),
        [lots],
    );

    const share = async () => {
        const url = window.location.href;

        if (navigator.share) {
            await navigator.share({
                title: project?.name ?? 'Lotea',
                text: `Consulta los lotes disponibles en ${project?.name ?? 'Lotea'}`,
                url,
            });

            return;
        }

        await navigator.clipboard.writeText(url);
        setShared(true);
        window.setTimeout(() => setShared(false), 1800);
    };

    return (
        <>
            <Head
                title={`${project?.name ?? 'Plano interactivo'} · Plano interactivo`}
            />

            <div className="flex h-screen flex-col bg-[#eef1f3] text-[#102b4a]">
                <header className="z-20 flex flex-wrap items-center justify-between gap-3 border-b border-[#e0e5e8] bg-white px-4 py-3 lg:px-6">
                    <div className="flex min-w-0 items-center gap-3">
                        <Link
                            href="/"
                            aria-label="Volver al portal"
                            className="flex size-9 shrink-0 items-center justify-center rounded-xl border border-[#e1e5e8] text-[#66778a] transition hover:text-[#102b4a]"
                        >
                            <ArrowLeft className="size-4" />
                        </Link>
                        <div className="min-w-0">
                            <p className="truncate text-[9px] font-bold tracking-[0.14em] text-[#788696] uppercase">
                                {project?.location ?? 'Portal Lotea'}
                            </p>
                            <h1 className="truncate text-base font-bold tracking-[-0.02em] sm:text-lg">
                                {project?.name ?? 'Sin proyecto publicado'}
                            </h1>
                        </div>
                    </div>

                    <div className="flex items-center gap-2">
                        {projects.length > 1 ? (
                            <select
                                value={project?.slug ?? ''}
                                onChange={(event) =>
                                    router.get('/explorador-3d', {
                                        project: event.target.value,
                                    })
                                }
                                aria-label="Cambiar de desarrollo"
                                className="rounded-xl border border-[#e2e6e9] bg-white px-3 py-2 text-xs font-semibold outline-none"
                            >
                                {projects.map((item) => (
                                    <option key={item.slug} value={item.slug}>
                                        {item.name}
                                    </option>
                                ))}
                            </select>
                        ) : null}
                        {project ? (
                            <Link
                                href={project.projectUrl}
                                className="hidden rounded-xl border border-[#e2e6e9] bg-white px-3 py-2 text-xs font-semibold sm:block"
                            >
                                Ficha del proyecto
                            </Link>
                        ) : null}
                        <button
                            type="button"
                            onClick={() => void share()}
                            className="flex items-center gap-2 rounded-xl border border-[#e2e6e9] bg-white px-3 py-2 text-xs font-semibold transition hover:border-[#cbd3da]"
                        >
                            {shared ? (
                                <Check className="size-4" />
                            ) : (
                                <Share2 className="size-4" />
                            )}
                            {shared ? 'Copiado' : 'Compartir'}
                        </button>
                    </div>
                </header>

                <main className="flex min-h-0 flex-1 flex-col lg:flex-row">
                    <section className="relative min-h-[420px] flex-1 bg-white">
                        {frame && lots.length > 0 ? (
                            <MasterplanViewer
                                frame={frame}
                                basePlanUrl={basePlanUrl}
                                lots={lots}
                                selectedId={selectedId}
                                onSelect={setSelectedId}
                                statuses={['available', 'held', 'sold']}
                            />
                        ) : (
                            <div className="flex h-full items-center justify-center p-8">
                                <div className="max-w-sm text-center">
                                    <p className="text-sm font-bold">
                                        Todavía no hay un plano publicado
                                    </p>
                                    <p className="mt-2 text-xs leading-5 text-[#66778a]">
                                        Cuando el desarrollador publique su
                                        proyecto, el plano interactivo aparecerá
                                        aquí con la disponibilidad al día.
                                    </p>
                                    <Link
                                        href="/"
                                        className="mt-5 inline-flex rounded-xl bg-[#102b4a] px-4 py-2.5 text-xs font-bold text-white"
                                    >
                                        Volver al portal
                                    </Link>
                                </div>
                            </div>
                        )}
                    </section>

                    <aside className="w-full shrink-0 overflow-y-auto border-t border-[#e0e5e8] bg-white p-4 lg:w-[340px] lg:border-t-0 lg:border-l">
                        <div className="grid grid-cols-3 gap-2">
                            <Count
                                value={counts.available}
                                label="Disponibles"
                                color="#2f9a69"
                            />
                            <Count
                                value={counts.held}
                                label="Apartados"
                                color="#138c98"
                            />
                            <Count
                                value={counts.sold}
                                label="Vendidos"
                                color="#ae315a"
                            />
                        </div>

                        {selected ? (
                            <div className="mt-4">
                                <p className="text-[9px] font-bold tracking-[0.12em] text-[#788696] uppercase">
                                    Lote seleccionado
                                </p>
                                <h2 className="mt-1 text-xl font-bold tracking-[-0.02em]">
                                    {selected.lot} ·{' '}
                                    {selected.blockLabel ?? 'sin manzana'}
                                </h2>

                                <dl className="mt-3 grid grid-cols-2 gap-2">
                                    <Detail
                                        label="Superficie"
                                        value={
                                            selected.area
                                                ? `${selected.area.toFixed(2)} m²`
                                                : '—'
                                        }
                                    />
                                    <Detail
                                        label="Estatus"
                                        value={STATUS_LABEL[selected.status]}
                                    />
                                    <Detail
                                        label="Precio"
                                        value={
                                            selected.price > 0
                                                ? formatMoney(selected.price)
                                                : 'Consultar'
                                        }
                                    />
                                    <Detail
                                        label="Orientación"
                                        value={selected.orientation}
                                    />
                                    <Detail
                                        label="Medidas del plano"
                                        value={
                                            selected.dimensions.length > 0
                                                ? selected.dimensions.join(
                                                      ' × ',
                                                  )
                                                : '—'
                                        }
                                        wide
                                    />
                                </dl>

                                <p className="mt-3 flex items-start gap-2 rounded-xl bg-[#f4f7f9] px-3 py-2.5 text-[10px] leading-4 text-[#4a5c70]">
                                    <Ruler className="mt-px size-3 shrink-0" />
                                    Superficie y medidas leídas directamente del
                                    plano oficial del desarrollo.
                                </p>

                                {project && selected.status === 'available' ? (
                                    <>
                                        {selected.price > 0 ? (
                                            <div className="mt-3">
                                                <PaymentSimulator
                                                    price={selected.price}
                                                    downPaymentPercent={
                                                        project.downPaymentPercent
                                                    }
                                                    financingMonths={
                                                        project.financingMonths
                                                    }
                                                />
                                            </div>
                                        ) : null}

                                        <div className="mt-3">
                                            <LeadForm
                                                target={{
                                                    projectSlug: project.slug,
                                                    projectName: project.name,
                                                    whatsapp: project.whatsapp,
                                                    lot: {
                                                        id: Number(
                                                            selected.databaseId ??
                                                                0,
                                                        ),
                                                        label: `${selected.blockLabel ?? ''} ${selected.lot}`.trim(),
                                                        area:
                                                            selected.area ?? 0,
                                                        price: selected.price,
                                                    },
                                                }}
                                                compact
                                            />
                                        </div>
                                    </>
                                ) : null}
                            </div>
                        ) : (
                            <div className="mt-4 rounded-xl border border-dashed border-[#d5dde3] px-4 py-8 text-center">
                                <MousePointer2 className="mx-auto size-6 text-[#25a9bc]" />
                                <p className="mt-3 text-xs font-bold">
                                    Haz clic en un lote
                                </p>
                                <p className="mt-1.5 text-[10px] leading-4 text-[#66778a]">
                                    Consulta su superficie, medidas, precio y
                                    disponibilidad.
                                </p>
                            </div>
                        )}
                    </aside>
                </main>
            </div>
        </>
    );
}

function Count({
    value,
    label,
    color,
}: {
    value: number;
    label: string;
    color: string;
}) {
    return (
        <div className="rounded-xl border border-[#e6eaec] px-2.5 py-2">
            <span
                className="block size-2 rounded-full"
                style={{ backgroundColor: color }}
            />
            <strong className="mt-1.5 block text-lg leading-none font-bold">
                {value}
            </strong>
            <span className="mt-1 block text-[9px] font-bold tracking-[0.06em] text-[#788696] uppercase">
                {label}
            </span>
        </div>
    );
}

function Detail({
    label,
    value,
    wide,
}: {
    label: string;
    value: string;
    wide?: boolean;
}) {
    return (
        <div
            className={`rounded-lg border border-[#e6eaec] px-2.5 py-2 ${wide ? 'col-span-2' : ''}`}
        >
            <dt className="text-[9px] font-bold tracking-[0.06em] text-[#788696] uppercase">
                {label}
            </dt>
            <dd className="mt-0.5 text-xs font-bold">{value}</dd>
        </div>
    );
}
