import { Head, Link } from '@inertiajs/react';
import { ArrowUpRight, Globe, Layers, ScanLine } from 'lucide-react';
import {
    EmptyState,
    PageHeader,
    STATUS_BAR,
    Stat,
    area,
    count,
    money,
    shortDate,
} from '@/components/admin/primitives';

interface ProjectSummary {
    id: number;
    name: string;
    slug: string;
    location: string;
    published: boolean;
    publishedAt: string | null;
    updatedAt: string | null;
    totalLots: number;
    blockCount: number;
    statusCounts: {
        available: number;
        held: number;
        sold: number;
        blocked: number;
    };
    totalArea: number;
    pricedLots: number;
    inventoryValue: number;
    soldValue: number;
    coverUrl: string | null;
}

export default function ProjectsIndex({
    projects,
    digitizerUrl,
}: {
    projects: ProjectSummary[];
    digitizerUrl: string;
}) {
    const totalLots = projects.reduce(
        (sum, project) => sum + project.totalLots,
        0,
    );
    const available = projects.reduce(
        (sum, project) => sum + project.statusCounts.available,
        0,
    );
    const inventoryValue = projects.reduce(
        (sum, project) => sum + project.inventoryValue,
        0,
    );

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

            <div className="space-y-6 p-5">
                <PageHeader
                    eyebrow="Cartera"
                    title="Proyectos"
                    description="Cada plano digitalizado es un proyecto. Dentro de cada uno viven sus manzanas, lotes, medidas, superficies, precios y estatus comercial."
                    actions={
                        <Link
                            href={digitizerUrl}
                            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"
                        >
                            <ScanLine className="size-4.5" />
                            Digitalizar un plano
                        </Link>
                    }
                />

                {projects.length === 0 ? (
                    <EmptyState
                        title="Todavía no hay proyectos"
                        description="Un proyecto nace de un plano. Sube el PDF de lotificación en el digitalizador y Lotea creará el proyecto con sus manzanas y lotes."
                        action={
                            <Link
                                href={digitizerUrl}
                                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"
                            >
                                <ScanLine className="size-4.5" />
                                Subir el primer plano
                            </Link>
                        }
                    />
                ) : (
                    <>
                        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                            <Stat
                                value={count(projects.length)}
                                label="Proyectos"
                                hint={`${count(projects.filter((project) => project.published).length)} publicados`}
                            />
                            <Stat
                                value={count(totalLots)}
                                label="Lotes totales"
                            />
                            <Stat
                                value={count(available)}
                                label="Disponibles"
                                hint={
                                    totalLots > 0
                                        ? `${Math.round((available / totalLots) * 100)}% del inventario`
                                        : undefined
                                }
                            />
                            <Stat
                                value={money(inventoryValue)}
                                label="Valor disponible"
                                tone="accent"
                            />
                        </div>

                        <div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
                            {projects.map((project) => (
                                <ProjectCard
                                    key={project.id}
                                    project={project}
                                />
                            ))}
                        </div>
                    </>
                )}
            </div>
        </>
    );
}

function ProjectCard({ project }: { project: ProjectSummary }) {
    const sold = project.statusCounts.sold;
    const soldShare =
        project.totalLots > 0
            ? Math.round((sold / project.totalLots) * 100)
            : 0;

    return (
        <Link
            href={`/admin/proyectos/${project.slug}`}
            className="group flex flex-col overflow-hidden rounded-2xl border border-border bg-card transition hover:border-brand"
        >
            <div className="relative h-36 overflow-hidden bg-muted">
                {project.coverUrl ? (
                    <img
                        src={project.coverUrl}
                        alt={`Plano de ${project.name}`}
                        className="size-full object-cover object-center"
                    />
                ) : (
                    <div className="flex size-full items-center justify-center text-muted-foreground">
                        <Layers className="size-8" />
                    </div>
                )}
                <span
                    className={`absolute top-3 right-3 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-bold ${
                        project.published
                            ? 'bg-brand text-brand-foreground'
                            : 'bg-card/90 text-muted-foreground'
                    }`}
                >
                    <Globe className="size-3.5" />
                    {project.published ? 'Publicado' : 'Borrador'}
                </span>
            </div>

            <div className="flex flex-1 flex-col p-4">
                <div className="flex items-start justify-between gap-2">
                    <div>
                        <h2 className="text-sm font-bold text-foreground">
                            {project.name}
                        </h2>
                        <p className="mt-0.5 text-[13px] text-muted-foreground">
                            {project.location}
                        </p>
                    </div>
                    <ArrowUpRight className="size-4.5 shrink-0 text-muted-foreground transition group-hover:text-foreground" />
                </div>

                <dl className="mt-4 grid grid-cols-2 gap-x-3 gap-y-2 text-[13px]">
                    <Detail
                        label="Manzanas"
                        value={count(project.blockCount)}
                    />
                    <Detail label="Lotes" value={count(project.totalLots)} />
                    <Detail
                        label="Disponibles"
                        value={count(project.statusCounts.available)}
                    />
                    <Detail
                        label="Superficie"
                        value={area(project.totalArea)}
                    />
                </dl>

                <div className="mt-4">
                    <div className="flex h-1.5 overflow-hidden rounded-full bg-muted">
                        <Segment
                            value={project.statusCounts.sold}
                            total={project.totalLots}
                            color={STATUS_BAR.sold}
                        />
                        <Segment
                            value={project.statusCounts.held}
                            total={project.totalLots}
                            color={STATUS_BAR.held}
                        />
                        <Segment
                            value={project.statusCounts.available}
                            total={project.totalLots}
                            color={STATUS_BAR.available}
                        />
                    </div>
                    <p className="mt-2 text-[12px] text-muted-foreground">
                        {soldShare}% vendido · {count(project.pricedLots)} de{' '}
                        {count(project.totalLots)} con precio
                    </p>
                </div>

                <div className="mt-4 flex items-end justify-between border-t border-border pt-3">
                    <div>
                        <p className="text-[11px] font-bold tracking-[0.1em] text-muted-foreground uppercase">
                            Valor disponible
                        </p>
                        <p className="mt-0.5 text-sm font-semibold text-foreground">
                            {money(project.inventoryValue)}
                        </p>
                    </div>
                    <p className="text-[12px] text-muted-foreground">
                        {shortDate(project.updatedAt)}
                    </p>
                </div>
            </div>
        </Link>
    );
}

function Segment({
    value,
    total,
    color,
}: {
    value: number;
    total: number;
    color: string;
}) {
    if (total === 0 || value === 0) {
        return null;
    }

    return (
        <span
            style={{
                width: `${(value / total) * 100}%`,
                backgroundColor: color,
            }}
        />
    );
}

function Detail({ label, value }: { label: string; value: string }) {
    return (
        <div>
            <dt className="text-[11px] font-bold tracking-[0.08em] text-muted-foreground uppercase">
                {label}
            </dt>
            <dd className="mt-0.5 font-semibold text-foreground">{value}</dd>
        </div>
    );
}
