import { Deferred, Link, router, usePage } from '@inertiajs/react';
import { CarFront, ChevronLeft, GitMerge, Plus } from 'lucide-react';
import { useState } from 'react';
import { CatalogStatusBadge } from '@/components/shared/badges';
import { ChromeTabs } from '@/components/shared/chrome-tabs';
import { EmptyState } from '@/components/shared/empty-state';
import { EntityEditingActions } from '@/components/shared/entity-editing-actions';
import {
    LocaleCoverageChips,
    LocaleFallbackChip,
} from '@/components/shared/locale-chips';
import { LocaleSwitch } from '@/components/shared/locale-switch';
import { Skeleton } from '@/components/ui/skeleton';
import { FeatureAddPanel } from '@/components/views/feature-add-panel';
import { useCatalogLocale } from '@/hooks/use-catalog-locale';
import {
    formatCount,
    formatPrice,
    isPriceSentinel,
    pickLocalizedName,
} from '@/lib/catalog';
import { cn } from '@/lib/utils';
import { show as engineShow } from '@/routes/catalog/engines';
import { index as modelsIndex } from '@/routes/catalog/models';
import { show as trimShow } from '@/routes/catalog/trims';
import { show as variantShow } from '@/routes/catalog/variants';
import type {
    CatalogBodyTypeDetail,
    CatalogBodyTypeSection,
    CatalogBodyTypeShowProps,
    CatalogFeatureIncludeGroup,
} from '@/types/catalog';

const TABS = [
    { id: 'sections', label: 'Sections' },
    { id: 'engines', label: 'Engines' },
    { id: 'trims', label: 'Trims' },
    { id: 'variants', label: 'Variants' },
    { id: 'includes', label: 'Feature includes' },
];

export function BodyTypeDetailView({
    model,
    bodyType,
    sections,
    feature_includes,
}: CatalogBodyTypeShowProps) {
    const [tab, setTab] = useState('variants');
    const [featureTrimId, setFeatureTrimId] = useState<number | null>(null);
    const locale = useCatalogLocale();
    const { props } = usePage();
    const canEdit = props.auth.can.edit_catalog;

    const modelName = pickLocalizedName(model, locale, model.name);
    const bodyTypeName = pickLocalizedName(bodyType, locale, bodyType.name);
    const enginesCount = bodyType.engines_count;
    const trimsCount = bodyType.trims_count;
    const variantsCount = bodyType.variants_count;

    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>
                        <Link
                            href={`/models/${model.id}`}
                            className="cursor-pointer text-[10px] font-bold tracking-widest text-gray-400 uppercase transition-colors hover:text-astara-orange"
                        >
                            {modelName.text}
                        </Link>
                    </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={locale}
                                used={bodyTypeName.locale}
                            />
                        )}
                        <span className="font-mono text-[11px] text-gray-400">
                            {bodyType.body_key}
                        </span>
                    </div>
                    <p className="mt-1 text-[11px] font-bold tracking-widest text-gray-500 uppercase">
                        Body type detail
                    </p>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                    <LocaleCoverageChips names={bodyType} />
                    <CatalogStatusBadge status={bodyType.status} />
                    {bodyType.flag === 'New' && (
                        <span className="inline-flex h-[18px] items-center rounded bg-yellow-50 px-2 text-[9px] font-bold tracking-wider text-amber-700 uppercase">
                            New
                        </span>
                    )}
                    {bodyType.test_drive && (
                        <span
                            title="Test drive available"
                            className="flex h-[18px] w-[18px] items-center justify-center rounded bg-green-50 text-green-700"
                        >
                            <CarFront size={11} />
                        </span>
                    )}
                    {bodyType.range_json.map((range) => (
                        <span
                            key={range}
                            className="inline-flex h-[18px] items-center rounded border border-slate-200 bg-white px-2 text-[9px] font-semibold text-slate-600"
                        >
                            {range}
                        </span>
                    ))}
                    <LocaleSwitch />
                </div>
            </header>

            <div className="p-6">
                <div className="mb-4 flex flex-wrap items-center gap-2">
                    <CountChip label="Engines" value={enginesCount} />
                    <CountChip label="Trims" value={trimsCount} />
                    <CountChip label="Variants" value={variantsCount} />
                </div>

                <ChromeTabs tabs={TABS} active={tab} onChange={setTab} />

                <div className="rounded-tr-xl rounded-b-xl border border-t-0 border-[rgba(30,25,50,0.06)] bg-white p-4 shadow-[0_2px_8px_rgba(30,25,50,0.04)]">
                    {tab === 'sections' && (
                        <Deferred
                            data={['sections']}
                            fallback={<SectionsSkeleton />}
                        >
                            {sections !== undefined && (
                                <SectionCatalog sections={sections} />
                            )}
                        </Deferred>
                    )}

                    {tab === 'engines' && (
                        <div className="divide-y divide-gray-50">
                            {bodyType.engines.map((engine, index) => {
                                const engineName = pickLocalizedName(
                                    engine,
                                    locale,
                                    engine.name,
                                );

                                return (
                                    <div
                                        key={engine.id}
                                        className="flex items-center gap-2 px-2 py-1.5"
                                    >
                                        <button
                                            type="button"
                                            onClick={() =>
                                                router.visit(
                                                    engineShow({
                                                        model: model.id,
                                                        bodyType: bodyType.id,
                                                        engine: engine.id,
                                                    }),
                                                )
                                            }
                                            className="flex flex-1 cursor-pointer items-center gap-3 py-1 text-left transition-colors hover:bg-gray-50"
                                        >
                                            <span className="font-mono text-[11px] text-gray-400">
                                                {engine.engine_key}
                                            </span>
                                            <span className="flex-1 truncate text-xs font-bold text-astara-purple">
                                                {engineName.text}
                                            </span>
                                            {engineName.fellBack && (
                                                <LocaleFallbackChip
                                                    requested={locale}
                                                    used={engineName.locale}
                                                />
                                            )}
                                            <CatalogStatusBadge
                                                status={engine.status}
                                            />
                                        </button>
                                        {canEdit && (
                                            <EntityEditingActions
                                                modelId={model.id}
                                                bodyTypeId={bodyType.id}
                                                entityType="engine"
                                                entity={engine}
                                                isFirst={index === 0}
                                                isLast={
                                                    index ===
                                                    bodyType.engines.length - 1
                                                }
                                                defaultName={engineName.text}
                                            />
                                        )}
                                    </div>
                                );
                            })}
                            {bodyType.engines.length === 0 && (
                                <p className="px-2 py-4 text-[11px] text-gray-400">
                                    No engines for this body type.
                                </p>
                            )}
                        </div>
                    )}

                    {tab === 'trims' && (
                        <div className="divide-y divide-gray-50">
                            {bodyType.trims.map((trim, index) => (
                                <div key={trim.id} className="px-2 py-1.5">
                                    <div className="flex items-center gap-2">
                                        <button
                                            type="button"
                                            onClick={() =>
                                                router.visit(
                                                    trimShow({
                                                        model: model.id,
                                                        bodyType: bodyType.id,
                                                        trim: trim.id,
                                                    }),
                                                )
                                            }
                                            className="flex flex-1 cursor-pointer items-center gap-3 py-1 text-left transition-colors hover:bg-gray-50"
                                        >
                                            <span className="font-mono text-[11px] text-gray-400">
                                                {trim.trim_key}
                                            </span>
                                            <span className="flex-1 truncate text-xs font-bold text-astara-purple">
                                                {trim.name}
                                            </span>
                                            <CatalogStatusBadge
                                                status={trim.status}
                                            />
                                        </button>
                                        {canEdit && (
                                            <EntityEditingActions
                                                modelId={model.id}
                                                bodyTypeId={bodyType.id}
                                                entityType="trim"
                                                entity={trim}
                                                isFirst={index === 0}
                                                isLast={
                                                    index ===
                                                    bodyType.trims.length - 1
                                                }
                                                defaultName={trim.name}
                                            />
                                        )}
                                        {canEdit && (
                                            <button
                                                type="button"
                                                title="Add feature"
                                                onClick={() =>
                                                    setFeatureTrimId(
                                                        featureTrimId ===
                                                            trim.id
                                                            ? null
                                                            : trim.id,
                                                    )
                                                }
                                                className="flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-slate-100 hover:text-astara-purple"
                                            >
                                                <Plus size={13} />
                                            </button>
                                        )}
                                    </div>
                                    {featureTrimId === trim.id && (
                                        <FeatureAddPanel
                                            modelId={model.id}
                                            bodyTypeId={bodyType.id}
                                            trimId={trim.id}
                                            brandCode={model.brand.code}
                                        />
                                    )}
                                </div>
                            ))}
                            {bodyType.trims.length === 0 && (
                                <p className="px-2 py-4 text-[11px] text-gray-400">
                                    No trims for this body type.
                                </p>
                            )}
                        </div>
                    )}

                    {tab === 'variants' && (
                        <VariantMatrix bodyType={bodyType} />
                    )}

                    {tab === 'includes' &&
                        (feature_includes.length === 0 ? (
                            <EmptyState
                                icon={GitMerge}
                                title="No feature-inclusion rules for this body type"
                                description="body_type_feature_includes has no rows for this body type in the vendor feed."
                            />
                        ) : (
                            <FeatureIncludes groups={feature_includes} />
                        ))}
                </div>
            </div>
        </div>
    );
}

function CountChip({ label, value }: { label: string; value: number }) {
    return (
        <span className="inline-flex items-center gap-1.5 rounded bg-slate-100 px-2.5 py-1 text-[10px] font-bold tracking-widest text-slate-600 uppercase">
            {formatCount(value)} {label}
        </span>
    );
}

/*
 * Trim × engine matrix (IA §4.4): rows = trims, columns = engines, cells =
 * the variants row when one exists, else an honest empty cell.
 */
function VariantMatrix({ bodyType }: { bodyType: CatalogBodyTypeDetail }) {
    const locale = useCatalogLocale();
    const variantByPair = new Map(
        bodyType.variants.map((variant) => [
            `${variant.trim?.id}:${variant.engine?.id}`,
            variant,
        ]),
    );

    return (
        <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>
                        {bodyType.engines.map((engine) => {
                            const engineName = pickLocalizedName(
                                engine,
                                locale,
                                engine.name,
                            );

                            return (
                                <th
                                    key={engine.id}
                                    className="min-w-[140px] border-b border-border bg-neutral-50 px-3 py-2 text-left font-mono text-[10px] font-semibold text-slate-600"
                                    title={
                                        engineName.fellBack
                                            ? `${engineName.text} (${locale.toUpperCase()}: not available)`
                                            : engineName.text
                                    }
                                >
                                    {engine.engine_key}
                                </th>
                            );
                        })}
                    </tr>
                </thead>
                <tbody>
                    {bodyType.trims.length === 0 && (
                        <tr>
                            <td
                                colSpan={Math.max(
                                    1,
                                    bodyType.engines.length + 1,
                                )}
                                className="px-3 py-4 text-[11px] text-gray-400"
                            >
                                No trims for this body type — the matrix has no
                                rows.
                            </td>
                        </tr>
                    )}
                    {bodyType.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="font-mono text-[10px] text-gray-400">
                                    {trim.trim_key}
                                </span>
                                <span className="ml-2 text-[11px] font-bold text-astara-purple">
                                    {trim.name}
                                </span>
                            </td>
                            {bodyType.engines.map((engine) => {
                                const variant = variantByPair.get(
                                    `${trim.id}:${engine.id}`,
                                );

                                return (
                                    <td
                                        key={engine.id}
                                        className="border-b border-gray-100 px-3 py-1.5"
                                    >
                                        {variant ? (
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    router.visit(
                                                        variantShow({
                                                            variant: variant.id,
                                                        }),
                                                    )
                                                }
                                                className={cn(
                                                    'flex w-full cursor-pointer flex-col rounded border px-2 py-1.5 text-left transition-all hover:shadow-md',
                                                    isPriceSentinel(
                                                        variant.price,
                                                    )
                                                        ? 'border-amber-200 bg-amber-50'
                                                        : 'border-border bg-white hover:border-astara-orange',
                                                )}
                                            >
                                                <span className="truncate text-[10px] font-bold text-astara-purple">
                                                    {variant.name}
                                                </span>
                                                <span
                                                    className={cn(
                                                        'text-[9px] font-semibold',
                                                        isPriceSentinel(
                                                            variant.price,
                                                        )
                                                            ? 'text-amber-600'
                                                            : 'text-gray-400',
                                                    )}
                                                >
                                                    {formatPrice(variant.price)}
                                                </span>
                                            </button>
                                        ) : (
                                            <div className="flex h-full min-h-[34px] items-center justify-center text-[10px] text-gray-300">
                                                —
                                            </div>
                                        )}
                                    </td>
                                );
                            })}
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

/*
 * Section catalog (IA §4.4 tab 1): the shared 14 section definitions, each
 * listing this body type's section elements. Sections without elements are
 * honest — "no elements in vendor feed" (624 of 2576 across the catalog).
 */
function SectionCatalog({ sections }: { sections: CatalogBodyTypeSection[] }) {
    return (
        <div className="divide-y divide-gray-50">
            {sections.map((section) => (
                <div key={section.section_key}>
                    <div className="flex items-center gap-3 px-4 py-3">
                        <span className="font-mono text-[11px] font-bold text-astara-purple">
                            {section.section_key}
                        </span>
                        <span className="inline-flex h-[16px] items-center rounded bg-slate-100 px-1.5 text-[8px] font-bold tracking-wider text-slate-600 uppercase">
                            {section.flag}
                        </span>
                        <span className="flex-1 truncate text-[11px] font-bold text-gray-600">
                            {section.display_name}
                        </span>
                        <span className="text-[10px] font-bold text-gray-400">
                            {formatCount(section.elements_count)} elements
                        </span>
                    </div>
                    {section.elements.length === 0 ? (
                        <div className="px-4 pb-3 text-[10px] text-gray-400 italic">
                            No elements for this section in the vendor feed.
                        </div>
                    ) : (
                        <div className="divide-y divide-gray-50 bg-gray-50/50">
                            {section.elements.map((element) => (
                                <div
                                    key={element.id}
                                    className="flex items-center gap-3 px-4 py-2"
                                >
                                    <span className="w-44 shrink-0 truncate font-mono text-[10px] text-gray-500">
                                        {element.code}
                                    </span>
                                    <span
                                        className={cn(
                                            'inline-flex h-[16px] shrink-0 items-center rounded px-1.5 text-[8px] font-bold tracking-wider uppercase',
                                            element.element_type === 'feature'
                                                ? 'bg-green-50 text-green-700'
                                                : 'bg-orange-50 text-amber-700',
                                        )}
                                    >
                                        {element.element_type}
                                    </span>
                                    {element.unit_code && (
                                        <span className="inline-flex items-center rounded border border-slate-200 bg-white px-1.5 py-0.5 text-[9px] font-semibold text-slate-600">
                                            {element.unit_code}
                                        </span>
                                    )}
                                    {element.sap_code && (
                                        <span className="rounded bg-purple-50 px-1.5 py-0.5 font-mono text-[9px] text-purple-700">
                                            {element.sap_code}
                                        </span>
                                    )}
                                    <span className="flex-1 truncate text-[10px] text-gray-500">
                                        {element.description}
                                    </span>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            ))}
        </div>
    );
}

/*
 * Feature-inclusion rules (IA §4.4 tab 5): parent code → included codes.
 * Parent codes that are rule labels (e.g. STYLE) get the honest chip.
 */
function FeatureIncludes({ groups }: { groups: CatalogFeatureIncludeGroup[] }) {
    return (
        <div className="divide-y divide-gray-50">
            {groups.map((group) => (
                <div key={group.parent_feature_code} className="px-4 py-3">
                    <div className="flex items-center gap-2">
                        <span className="font-mono text-[11px] font-bold text-astara-purple">
                            {group.parent_feature_code}
                        </span>
                        {!group.parent_in_section_catalog && (
                            <span className="inline-flex h-[16px] items-center rounded bg-orange-50 px-1.5 text-[8px] font-bold tracking-wider text-amber-700 uppercase">
                                rule label, no section element
                            </span>
                        )}
                        <span className="text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                            includes
                        </span>
                    </div>
                    <div className="mt-1.5 flex flex-wrap items-center gap-1.5 pl-1">
                        {group.included.map((include) => (
                            <span
                                key={include.code}
                                className="inline-flex items-center gap-1 rounded bg-slate-100 px-2 py-0.5 font-mono text-[10px] text-slate-600"
                            >
                                {include.code}
                                {!include.in_section_catalog && (
                                    <span className="text-[8px] font-bold tracking-wider text-amber-700 uppercase">
                                        not in catalog
                                    </span>
                                )}
                            </span>
                        ))}
                    </div>
                </div>
            ))}
        </div>
    );
}

function SectionsSkeleton() {
    return (
        <div className="flex flex-col gap-2 p-4">
            <Skeleton className="h-9 w-full" />
            <Skeleton className="h-9 w-full" />
            <Skeleton className="h-9 w-full" />
        </div>
    );
}
