import { Link } from '@inertiajs/react';
import { ChevronLeft, Download, FileSpreadsheet } from 'lucide-react';
import { CatalogStatusBadge } from '@/components/shared/badges';
import { LocaleFallbackChip } from '@/components/shared/locale-chips';
import { SectionCard } from '@/components/shared/section-card';
import { useCatalogLocale } from '@/hooks/use-catalog-locale';
import { pickLocalizedName } from '@/lib/catalog';
import { cn } from '@/lib/utils';
import { index as modelsIndex } from '@/routes/catalog/models';
import type {
    CatalogPricelistShowProps,
    CatalogPriceList,
} from '@/types/catalog';

const SYMBOL_STYLES: Record<string, string> = {
    '●': 'text-green-600',
    '○': 'text-astara-orange',
    '–': 'text-gray-300',
    '?': 'text-gray-400',
};

export function PricelistView({
    pricelist,
    locale,
}: CatalogPricelistShowProps) {
    const catalogLocale = useCatalogLocale();
    const meta = pricelist.body_type;
    const trims = pricelist.trims;
    const engines = trims[0]?.engines ?? [];
    const categories = pricelist.categories;

    const modelName = pickLocalizedName(
        meta.model,
        catalogLocale,
        meta.model.name,
    );
    const bodyTypeName = pickLocalizedName(meta, catalogLocale, meta.name);

    const variantFor = (trimId: number, engineId: number) => {
        const trim = trims.find((t) => t.trim_id === trimId);

        return trim?.variants.find((v) => v.engine_id === engineId);
    };

    return (
        <div className="custom-scroll flex-1 overflow-y-auto">
            <header className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-gray-100 bg-white p-5">
                <div>
                    <div className="mb-1 flex items-center gap-2">
                        <Link
                            href={modelsIndex()}
                            prefetch="hover"
                            className="flex cursor-pointer items-center gap-1 text-[10px] font-bold tracking-widest text-gray-400 uppercase transition-colors hover:text-astara-orange"
                        >
                            <ChevronLeft size={12} /> Models
                        </Link>
                        <span className="text-[10px] text-gray-300">/</span>
                        <span className="text-[10px] font-bold tracking-widest text-gray-400 uppercase">
                            {modelName.text}
                        </span>
                    </div>
                    <div className="flex items-center gap-2.5">
                        <h2 className="text-2xl font-bold text-astara-purple">
                            {bodyTypeName.text}
                        </h2>
                        {bodyTypeName.fellBack && (
                            <LocaleFallbackChip
                                requested={catalogLocale}
                                used={bodyTypeName.locale}
                            />
                        )}
                        <span className="font-mono text-[11px] text-gray-400">
                            {meta.body_key}
                        </span>
                    </div>
                    <p className="mt-1 text-[11px] font-bold tracking-widest text-gray-500 uppercase">
                        Price list — {meta.brand.name ?? meta.brand.code}
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <CatalogStatusBadge status={meta.status} />
                    <span className="rounded bg-gray-100 px-2 py-0.5 text-[10px] font-bold text-gray-500">
                        MY {meta.model.year}
                    </span>
                    <a
                        href={`/body-types/${meta.id}/pricelist.xlsx?locale=${locale}`}
                        className="inline-flex items-center gap-1.5 rounded-lg bg-astara-purple px-3 py-2 text-[11px] font-bold text-white transition-colors hover:bg-astara-purple/90"
                    >
                        <FileSpreadsheet size={14} />
                        Excel
                    </a>
                    <a
                        href={`/body-types/${meta.id}/pricelist.pdf?locale=${locale}`}
                        className="inline-flex items-center gap-1.5 rounded-lg border border-astara-purple px-3 py-2 text-[11px] font-bold text-astara-purple transition-colors hover:bg-astara-purple/5"
                    >
                        <Download size={14} />
                        PDF
                    </a>
                </div>
            </header>

            <div className="space-y-3 p-5">
                <SectionCard
                    title="Prices"
                    titleRight={
                        <span className="text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                            {trims.length} trims · {engines.length} engines
                        </span>
                    }
                >
                    <div className="custom-scroll overflow-x-auto">
                        <table className="w-full border-collapse">
                            <thead>
                                <tr>
                                    <th className="sticky left-0 z-10 border-r border-b border-border bg-neutral-50 px-3 py-2 text-left text-[9px] font-bold tracking-widest text-slate-500 uppercase">
                                        Trim \ Engine
                                    </th>
                                    {engines.map((engine) => (
                                        <th
                                            key={engine.id}
                                            className="min-w-[160px] border-b border-border bg-neutral-50 px-3 py-2 text-left font-mono text-[10px] font-semibold text-slate-600"
                                            title={engine.name}
                                        >
                                            {engine.name}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {trims.map((trim) => (
                                    <tr key={trim.id}>
                                        <td className="sticky left-0 z-10 border-r border-b border-gray-100 bg-white px-3 py-2">
                                            <span className="text-[11px] font-bold text-astara-purple">
                                                {trim.name}
                                            </span>
                                        </td>
                                        {engines.map((engine) => {
                                            const variant = variantFor(
                                                trim.trim_id,
                                                engine.engine_id,
                                            );

                                            return (
                                                <td
                                                    key={engine.id}
                                                    className="border-b border-gray-100 px-3 py-2"
                                                >
                                                    {variant?.price !== null &&
                                                    variant?.price !==
                                                        undefined ? (
                                                        <span className="text-[11px] font-bold text-gray-700 tabular-nums">
                                                            {formatPrice(
                                                                variant.price,
                                                            )}
                                                        </span>
                                                    ) : (
                                                        <span className="text-[10px] text-gray-300">
                                                            —
                                                        </span>
                                                    )}
                                                </td>
                                            );
                                        })}
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </SectionCard>

                <SectionCard
                    title="Equipment"
                    titleRight={
                        <span className="text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                            ● Standard · ○ Optional · – N/A
                        </span>
                    }
                >
                    <div className="custom-scroll overflow-x-auto">
                        <table className="w-full border-collapse">
                            <thead>
                                <tr>
                                    <th className="sticky left-0 z-10 border-r border-b border-border bg-neutral-50 px-3 py-2 text-left text-[9px] font-bold tracking-widest text-slate-500 uppercase">
                                        Category
                                    </th>
                                    {trims.map((trim) => (
                                        <th
                                            key={trim.id}
                                            className="min-w-[110px] border-b border-border bg-neutral-50 px-3 py-2 text-left text-[9px] font-bold tracking-widest text-slate-600 uppercase"
                                        >
                                            {trim.name}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {categories.map((category) => (
                                    <CategoryRows
                                        key={category.code}
                                        category={category}
                                        trims={trims}
                                    />
                                ))}
                            </tbody>
                        </table>
                    </div>
                </SectionCard>
            </div>
        </div>
    );
}

function CategoryRows({
    category,
    trims,
}: {
    category: CatalogPriceList['categories'][number];
    trims: CatalogPriceList['trims'];
}) {
    return (
        <>
            {category.items.map((item, index) => (
                <tr key={`${category.code}:${item.code ?? index}`}>
                    <td className="sticky left-0 z-10 border-r border-b border-gray-100 bg-white px-3 py-1.5">
                        {index === 0 ? (
                            <span className="text-[10px] font-bold tracking-widest text-astara-purple uppercase">
                                {category.name}
                            </span>
                        ) : null}
                        <span
                            className={cn(
                                'block text-[11px]',
                                index === 0
                                    ? 'mt-1 text-gray-600'
                                    : 'text-gray-600',
                            )}
                        >
                            {item.name ?? item.code}
                        </span>
                    </td>
                    {trims.map((trim) => {
                        const feature = trim.features.find(
                            (f) => f.code === item.code,
                        );

                        return (
                            <td
                                key={`${trim.id}:${item.code}`}
                                className="border-b border-gray-100 px-3 py-1.5 text-center"
                            >
                                <span
                                    className={cn(
                                        'text-sm font-bold',
                                        SYMBOL_STYLES[feature?.symbol ?? '?'] ??
                                            'text-gray-400',
                                    )}
                                >
                                    {feature?.symbol ?? '?'}
                                </span>
                            </td>
                        );
                    })}
                </tr>
            ))}
        </>
    );
}

function formatPrice(price: number): string {
    return new Intl.NumberFormat('de-CH', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(price);
}
