import { Head, Link } from '@inertiajs/react';
import {
    ArrowLeft,
    ArrowRight,
    BadgeCheck,
    ChevronLeft,
    ChevronRight,
    MapPin,
    Play,
} from 'lucide-react';
import { useMemo, useState } from 'react';
import { LeadForm, WhatsappButton } from '@/components/portal/lead-form';
import { PaymentSimulator } from '@/components/portal/payment-simulator';
import { PortalHeader } from '@/components/portal/portal-header';
import { formatMoney } from '@/data/portal';

const numberFormat = new Intl.NumberFormat('es-MX', {
    maximumFractionDigits: 0,
});

interface Medium {
    id: number;
    kind: 'image' | 'video';
    isCover: boolean;
    playsInline: boolean;
    title: string | null;
    url: string | null;
    embedUrl: string | null;
    uploaded: boolean;
    position: number;
}

interface ProjectProps {
    project: {
        name: string;
        slug: string;
        location: string;
        address: string | null;
        latitude: number | null;
        longitude: number | null;
        mapUrl: string | null;
        headline: string;
        totalLots: number;
        availableLots: number;
        soldLots: number;
        heldLots: number;
        blockCount: number;
        startingPrice: number;
        smallestArea: number;
        largestArea: number;
        planUrl: string | null;
        explorerUrl: string;
        whatsapp: string | null;
        downPaymentPercent: number | null;
        financingMonths: number | null;
        averagePricePerMeter: number | null;
        soldShare: number;
    };
    media: Medium[];
    blocks: Array<{ name: string; lots: number; available: number }>;
    lots: Array<{
        id: number;
        block: string | null;
        lotNumber: string | null;
        area: number;
        price: number;
        dimensions: string[];
    }>;
}

export default function PortalProject({
    project,
    media,
    blocks,
    lots,
}: ProjectProps) {
    const [picked, setPicked] = useState<ProjectProps['lots'][number] | null>(
        null,
    );

    return (
        <>
            <Head title={`${project.name} · ${project.location}`}>
                <meta name="description" content={project.headline} />
            </Head>

            <div className="min-h-screen bg-[#f3f0e8] text-[#19352d]">
                <PortalHeader />

                <main>
                    <section className="mx-auto max-w-7xl px-5 pt-10 lg:px-8">
                        <Link
                            href="/#desarrollos"
                            className="inline-flex items-center gap-2 text-[11px] font-bold text-[#69776f] hover:text-[#19352d]"
                        >
                            <ArrowLeft className="size-3.5" />
                            Todos los desarrollos
                        </Link>

                        <div className="mt-5 grid gap-7 lg:grid-cols-[1.25fr_0.75fr] lg:items-end">
                            <div>
                                <p className="flex items-center gap-2 text-[11px] font-bold tracking-[0.16em] text-[#a45d3d] uppercase">
                                    <MapPin className="size-3.5" />
                                    {project.location}
                                </p>
                                <h1 className="font-editorial mt-4 text-5xl leading-[1] font-medium tracking-[-0.04em] text-balance sm:text-6xl">
                                    {project.name}
                                </h1>
                                <p className="mt-5 max-w-2xl text-sm leading-7 text-[#69776f]">
                                    {project.headline}
                                </p>
                                {project.address ? (
                                    <p className="mt-3 text-sm text-[#69776f]">
                                        {project.address}
                                    </p>
                                ) : null}
                                {project.mapUrl ? (
                                    <a
                                        href={project.mapUrl}
                                        target="_blank"
                                        rel="noreferrer"
                                        className="mt-3 inline-flex items-center gap-2 text-xs font-bold text-[#315f4e] hover:underline"
                                    >
                                        <MapPin className="size-4" />
                                        Ver ubicación en el mapa
                                    </a>
                                ) : null}
                            </div>

                            <div className="rounded-2xl border border-[#d8d9d1] bg-[#f8f6f0] p-5 lg:justify-self-end">
                                <p className="text-[9px] font-bold tracking-[0.12em] text-[#8d9891] uppercase">
                                    Precio desde
                                </p>
                                <p className="font-editorial mt-1 text-3xl font-medium tracking-[-0.03em]">
                                    {project.startingPrice > 0
                                        ? formatMoney(project.startingPrice)
                                        : 'Consultar'}
                                </p>
                                <a
                                    href="#me-interesa"
                                    className="mt-4 flex w-full items-center justify-center gap-2 rounded-xl bg-[#19352d] px-4 py-3 text-sm font-bold text-white"
                                >
                                    Quiero información
                                    <ArrowRight className="size-4" />
                                </a>
                                <WhatsappButton
                                    target={{
                                        projectSlug: project.slug,
                                        projectName: project.name,
                                        whatsapp: project.whatsapp,
                                    }}
                                    className="mt-2"
                                />
                                <Link
                                    href={project.explorerUrl}
                                    className="mt-2 flex w-full items-center justify-center gap-2 rounded-xl border border-[#d3d6cc] px-4 py-3 text-xs font-bold text-[#19352d]"
                                >
                                    Abrir el plano interactivo
                                </Link>
                            </div>
                        </div>
                    </section>

                    <Gallery
                        media={media}
                        planUrl={project.planUrl}
                        name={project.name}
                    />

                    <section className="border-y border-[#d8d8cf] bg-[#e7e2d7]">
                        <div className="mx-auto grid max-w-7xl grid-cols-2 divide-x divide-[#ccccc2] px-5 lg:grid-cols-6 lg:px-8">
                            <Metric
                                value={numberFormat.format(project.blockCount)}
                                label="manzanas"
                            />
                            <Metric
                                value={numberFormat.format(project.totalLots)}
                                label="lotes en el plano"
                            />
                            <Metric
                                value={numberFormat.format(
                                    project.availableLots,
                                )}
                                label="disponibles"
                            />
                            <Metric
                                value={
                                    project.smallestArea > 0
                                        ? `${numberFormat.format(project.smallestArea)} m²`
                                        : '—'
                                }
                                label="desde"
                            />
                            <Metric
                                value={
                                    project.averagePricePerMeter
                                        ? formatMoney(
                                              project.averagePricePerMeter,
                                          )
                                        : '—'
                                }
                                label="precio por m²"
                            />
                            <Metric
                                value={`${project.soldShare}%`}
                                label="vendido"
                            />
                        </div>
                    </section>

                    <section className="mx-auto max-w-7xl px-5 py-16 lg:px-8 lg:py-20">
                        <div className="grid gap-10 lg:grid-cols-[1.15fr_0.85fr]">
                            <div>
                                <h2 className="font-editorial text-3xl font-medium tracking-[-0.035em]">
                                    Lotes disponibles
                                </h2>
                                <p className="mt-3 max-w-xl text-sm leading-6 text-[#69776f]">
                                    Superficies y medidas leídas del plano
                                    oficial del desarrollo.
                                </p>

                                {lots.length === 0 ? (
                                    <p className="mt-8 rounded-2xl border border-dashed border-[#cdd2c8] px-5 py-10 text-center text-sm text-[#69776f]">
                                        En este momento no hay lotes
                                        disponibles.
                                    </p>
                                ) : (
                                    <LotBrowser
                                        lots={lots}
                                        project={project}
                                        onPick={setPicked}
                                        picked={picked}
                                    />
                                )}
                            </div>

                            <div className="space-y-4 lg:sticky lg:top-6 lg:self-start">
                                <div id="me-interesa">
                                    <LeadForm
                                        target={{
                                            projectSlug: project.slug,
                                            projectName: project.name,
                                            whatsapp: project.whatsapp,
                                            lot: picked
                                                ? {
                                                      id: picked.id,
                                                      label: `${picked.block ?? ''} L-${picked.lotNumber}`.trim(),
                                                      area: picked.area,
                                                      price: picked.price,
                                                  }
                                                : null,
                                        }}
                                        compact
                                    />
                                </div>

                                {picked && picked.price > 0 ? (
                                    <PaymentSimulator
                                        price={picked.price}
                                        downPaymentPercent={
                                            project.downPaymentPercent
                                        }
                                        financingMonths={
                                            project.financingMonths
                                        }
                                    />
                                ) : null}

                                {project.planUrl ? (
                                    <Link
                                        href={project.explorerUrl}
                                        className="block overflow-hidden rounded-2xl border border-[#d8d9d1] bg-white"
                                    >
                                        <img
                                            src={project.planUrl}
                                            alt={`Plano de ${project.name}`}
                                            className="h-40 w-full object-cover object-center"
                                        />
                                        <p className="flex items-center justify-between px-4 py-3 text-xs font-semibold">
                                            Elegir sobre el plano
                                            <ArrowRight className="size-4 text-[#315f4e]" />
                                        </p>
                                    </Link>
                                ) : null}

                                <div className="rounded-2xl border border-[#d8d9d1] bg-[#f8f6f0] p-5">
                                    <h3 className="text-[10px] font-bold tracking-[0.1em] text-[#8d9891] uppercase">
                                        Disponibilidad por manzana
                                    </h3>
                                    <ul className="mt-3 space-y-1.5">
                                        {blocks.map((block) => (
                                            <li
                                                key={block.name}
                                                className="flex items-center justify-between text-xs"
                                            >
                                                <span className="font-semibold">
                                                    {block.name}
                                                </span>
                                                <span className="text-[#69776f]">
                                                    {block.available} de{' '}
                                                    {block.lots} disponibles
                                                </span>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </section>

                    <section className="border-t border-[#d8d9d1] bg-[#18352d] text-white">
                        <div className="mx-auto flex max-w-7xl flex-col justify-between gap-6 px-5 py-14 lg:flex-row lg:items-center lg:px-8">
                            <div>
                                <p className="flex items-center gap-2 text-[10px] font-bold tracking-[0.16em] text-[#e5b08b] uppercase">
                                    <BadgeCheck className="size-3.5" />
                                    Inventario verificado
                                </p>
                                <h2 className="font-editorial mt-3 max-w-2xl text-3xl leading-tight font-medium tracking-[-0.035em]">
                                    Elige tu lote sobre el plano y agenda tu
                                    visita.
                                </h2>
                            </div>
                            <Link
                                href={project.explorerUrl}
                                className="inline-flex shrink-0 items-center justify-center gap-2 rounded-xl bg-[#e6b18c] px-5 py-3.5 text-sm font-bold text-[#17332b]"
                            >
                                Ver los {project.availableLots} lotes
                                <ArrowRight className="size-4" />
                            </Link>
                        </div>
                    </section>
                </main>

                <footer className="bg-[#112820] text-white/60">
                    <div className="mx-auto flex max-w-7xl flex-col justify-between gap-5 px-5 py-8 text-[10px] lg:flex-row lg:items-center lg:px-8">
                        <p className="font-editorial text-xl font-medium text-white">
                            Lotea
                        </p>
                        <div className="flex flex-wrap gap-6 font-semibold">
                            <span>Privacidad</span>
                            <span>Términos</span>
                            <span>Contacto</span>
                            <span>© 2026 Lotea</span>
                        </div>
                    </div>
                </footer>
            </div>
        </>
    );
}

type SortKey = 'price' | 'area' | 'block';

function LotBrowser({
    lots,
    project,
    picked,
    onPick,
}: {
    lots: ProjectProps['lots'];
    project: ProjectProps['project'];
    picked: ProjectProps['lots'][number] | null;
    onPick: (lot: ProjectProps['lots'][number]) => void;
}) {
    const [sort, setSort] = useState<SortKey>('block');
    const [limit, setLimit] = useState(12);

    const sorted = useMemo(() => {
        const copy = [...lots];

        if (sort === 'price') {
            copy.sort((a, b) => (a.price || Infinity) - (b.price || Infinity));
        } else if (sort === 'area') {
            copy.sort((a, b) => b.area - a.area);
        }

        return copy;
    }, [lots, sort]);

    return (
        <>
            <div className="mt-6 flex flex-wrap items-center gap-2">
                <span className="text-[11px] font-bold tracking-[0.08em] text-[#8d9891] uppercase">
                    Ordenar por
                </span>
                {(
                    [
                        ['block', 'Manzana'],
                        ['price', 'Precio'],
                        ['area', 'Superficie'],
                    ] as Array<[SortKey, string]>
                ).map(([key, label]) => (
                    <button
                        key={key}
                        type="button"
                        onClick={() => setSort(key)}
                        className={`rounded-lg px-3 py-1.5 text-xs font-bold transition ${
                            sort === key
                                ? 'bg-[#19352d] text-white'
                                : 'border border-[#d3d6cc] bg-white text-[#3c4a43] hover:border-[#adb5a9]'
                        }`}
                    >
                        {label}
                    </button>
                ))}
            </div>

            <ul className="mt-4 grid gap-3 sm:grid-cols-2">
                {sorted.slice(0, limit).map((lot) => {
                    const active = picked?.id === lot.id;

                    return (
                        <li key={lot.id}>
                            <button
                                type="button"
                                onClick={() => onPick(lot)}
                                className={`w-full rounded-2xl border p-4 text-left transition ${
                                    active
                                        ? 'border-[#19352d] bg-[#f2f5ef]'
                                        : 'border-[#d8d9d1] bg-[#f8f6f0] hover:border-[#adb5a9]'
                                }`}
                            >
                                <div className="flex items-start justify-between gap-3">
                                    <div>
                                        <p className="text-[10px] font-bold tracking-[0.1em] text-[#8d9891] uppercase">
                                            {lot.block ?? 'Sin manzana'}
                                        </p>
                                        <p className="font-editorial text-2xl font-medium tracking-[-0.02em]">
                                            L-{lot.lotNumber}
                                        </p>
                                    </div>
                                    <p className="text-right">
                                        <span className="block text-lg font-semibold text-[#19352d]">
                                            {lot.price > 0
                                                ? formatMoney(lot.price)
                                                : 'Consultar'}
                                        </span>
                                        {lot.price > 0 && lot.area > 0 ? (
                                            <span className="text-[10px] text-[#8d9891]">
                                                {formatMoney(
                                                    Math.round(
                                                        lot.price / lot.area,
                                                    ),
                                                )}{' '}
                                                / m²
                                            </span>
                                        ) : null}
                                    </p>
                                </div>

                                <div className="mt-3 flex flex-wrap gap-1.5 border-t border-[#e2e4de] pt-3">
                                    <Chip>
                                        {numberFormat.format(lot.area)} m²
                                    </Chip>
                                    {lot.dimensions.length > 0 ? (
                                        <Chip>
                                            {lot.dimensions
                                                .slice(0, 2)
                                                .join(' × ')}
                                        </Chip>
                                    ) : null}
                                </div>

                                <p className="mt-3 text-xs font-bold text-[#315f4e]">
                                    {active
                                        ? 'Seleccionado · completa tus datos'
                                        : 'Me interesa este lote'}
                                </p>
                            </button>
                        </li>
                    );
                })}
            </ul>

            {limit < sorted.length ? (
                <button
                    type="button"
                    onClick={() => setLimit(limit + 24)}
                    className="mt-4 w-full rounded-xl border border-[#d3d6cc] bg-white px-4 py-3 text-xs font-bold text-[#19352d] hover:border-[#adb5a9]"
                >
                    Ver más lotes ({sorted.length - limit} restantes)
                </button>
            ) : null}

            <p className="mt-3 text-[11px] text-[#8d9891]">
                {lots.length} lotes disponibles en {project.name}.
            </p>
        </>
    );
}

function Chip({ children }: { children: React.ReactNode }) {
    return (
        <span className="rounded-md bg-[#ebece6] px-2 py-1 text-[10px] font-semibold text-[#607168]">
            {children}
        </span>
    );
}

function Gallery({
    media,
    planUrl,
    name,
}: {
    media: Medium[];
    planUrl: string | null;
    name: string;
}) {
    const items: Medium[] =
        media.length > 0
            ? media
            : planUrl
              ? [
                    {
                        id: 0,
                        kind: 'image',
                        isCover: true,
                        playsInline: false,
                        title: 'Plano del desarrollo',
                        url: planUrl,
                        embedUrl: null,
                        uploaded: true,
                        position: 0,
                    },
                ]
              : [];
    const [index, setIndex] = useState(0);

    if (items.length === 0) {
        return null;
    }

    const current = items[Math.min(index, items.length - 1)];

    return (
        <section className="mx-auto max-w-7xl px-5 pt-10 lg:px-8">
            <div className="relative overflow-hidden rounded-[1.4rem] border border-[#d8d9d1] bg-[#e7e2d7]">
                <div className="aspect-[16/9] w-full">
                    {current.kind === 'video' && current.embedUrl ? (
                        <iframe
                            key={current.id}
                            src={current.embedUrl}
                            title={current.title ?? `Video de ${name}`}
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                            allowFullScreen
                            className="size-full"
                        />
                    ) : current.kind === 'video' ? (
                        <video
                            key={current.id}
                            src={current.url ?? undefined}
                            controls
                            playsInline
                            className="size-full bg-black object-contain"
                        />
                    ) : (
                        <img
                            src={current.url ?? undefined}
                            alt={current.title ?? name}
                            className="size-full object-cover object-center"
                        />
                    )}
                </div>

                {items.length > 1 ? (
                    <>
                        <GalleryArrow
                            side="left"
                            onClick={() =>
                                setIndex(
                                    (index - 1 + items.length) % items.length,
                                )
                            }
                        />
                        <GalleryArrow
                            side="right"
                            onClick={() => setIndex((index + 1) % items.length)}
                        />
                    </>
                ) : null}
            </div>

            {items.length > 1 ? (
                <div className="mt-3 flex gap-2 overflow-x-auto pb-1">
                    {items.map((item, position) => (
                        <button
                            key={item.id}
                            type="button"
                            onClick={() => setIndex(position)}
                            aria-label={
                                item.title ?? `Elemento ${position + 1}`
                            }
                            className={`relative h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${
                                position === index
                                    ? 'border-[#19352d]'
                                    : 'border-transparent opacity-70 hover:opacity-100'
                            }`}
                        >
                            {item.kind === 'image' && item.url ? (
                                <img
                                    src={item.url}
                                    alt=""
                                    className="size-full object-cover"
                                />
                            ) : (
                                <span className="flex size-full items-center justify-center bg-[#19352d] text-white">
                                    <Play className="size-4" />
                                </span>
                            )}
                        </button>
                    ))}
                </div>
            ) : null}
        </section>
    );
}

function GalleryArrow({
    side,
    onClick,
}: {
    side: 'left' | 'right';
    onClick: () => void;
}) {
    return (
        <button
            type="button"
            onClick={onClick}
            aria-label={side === 'left' ? 'Anterior' : 'Siguiente'}
            className={`absolute top-1/2 flex size-10 -translate-y-1/2 items-center justify-center rounded-full bg-[#f5f1e7]/92 text-[#19352d] shadow-lg backdrop-blur transition hover:bg-white ${
                side === 'left' ? 'left-4' : 'right-4'
            }`}
        >
            {side === 'left' ? (
                <ChevronLeft className="size-5" />
            ) : (
                <ChevronRight className="size-5" />
            )}
        </button>
    );
}

function Metric({ value, label }: { value: string; label: string }) {
    return (
        <div className="px-4 py-7 text-center lg:py-8">
            <p className="font-editorial text-3xl font-medium tracking-[-0.04em] sm:text-4xl">
                {value}
            </p>
            <p className="mt-1 text-[9px] font-bold tracking-[0.11em] text-[#718078] uppercase">
                {label}
            </p>
        </div>
    );
}
