import { Deferred, Link } from '@inertiajs/react';
import type { ColDef } from 'ag-grid-community';
import { AgGridReact } from 'ag-grid-react';
import type { CustomCellRendererProps } from 'ag-grid-react';
import { ChevronLeft, FileText } from 'lucide-react';
import { useState } from 'react';
import {
    AvailabilityBadge,
    CatalogStatusBadge,
} from '@/components/shared/badges';
import { EmptyState } from '@/components/shared/empty-state';
import {
    LocaleCoverageChips,
    LocaleFallbackChip,
} from '@/components/shared/locale-chips';
import { LocaleSwitch } from '@/components/shared/locale-switch';
import { SectionCard } from '@/components/shared/section-card';
import { Skeleton } from '@/components/ui/skeleton';
import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { useCatalogLocale } from '@/hooks/use-catalog-locale';
import { astaraGridTheme } from '@/lib/ag-grid-theme';
import {
    CATALOG_LOCALES,
    formatUnitValue,
    formatPrice,
    isPriceSentinel,
    isSurchargeSentinel,
    pickName,
} from '@/lib/catalog';
import { cn } from '@/lib/utils';
import { index as variantsIndex } from '@/routes/catalog/variants';
import type {
    CatalogDataValue,
    CatalogFeature,
    CatalogFeatureDisclaimer,
    CatalogStatus,
    LocalizedNameFields,
} from '@/types/catalog';

export interface EntityIdentity {
    name: string;
    key: string;
    status: CatalogStatus;
    description?: string | null;
    price?: number;
    /** Raw name_* fields of the entity itself (IA §6 coverage chips). */
    localizedNames?: LocalizedNameFields;
    links?: {
        model?: {
            id: number;
            model_key: string;
            name: string;
            names?: LocalizedNameFields;
        };
        bodyType?: {
            id: number;
            body_key: string;
            name: string;
            names?: LocalizedNameFields;
        };
        trim?: { id: number; trim_key: string; name: string };
        engine?: { id: number; engine_key: string; name: string };
    };
}

export interface EntityDetailViewProps {
    entityType: 'engine' | 'trim' | 'variant';
    identity: EntityIdentity;
    payloadSupported: boolean;
    features: CatalogFeature[];
    dataValues: CatalogDataValue[];
    featureDisclaimers: CatalogFeatureDisclaimer[];
}

const EntityTypeChip = ({
    type,
}: {
    type: EntityDetailViewProps['entityType'];
}) => (
    <span className="inline-flex h-[18px] items-center rounded bg-astara-purple px-2 text-[9px] font-bold tracking-widest text-white uppercase">
        {type}
    </span>
);

const FeatureCodeCell = ({ data }: CustomCellRendererProps<CatalogFeature>) => (
    <div className="flex h-full items-center font-mono text-[11px] text-astara-purple">
        {data?.feature_code}
    </div>
);

const AvailabilityCell = ({
    data,
}: CustomCellRendererProps<CatalogFeature>) => (
    <div className="flex h-full items-center">
        <AvailabilityBadge availability={data?.availability ?? null} />
    </div>
);

const SurchargeCell = ({ data }: CustomCellRendererProps<CatalogFeature>) => {
    const surcharge = data?.surcharge;

    if (surcharge === null || surcharge === undefined) {
        return <div className="flex h-full items-center text-gray-300">—</div>;
    }

    const sentinel = isSurchargeSentinel(surcharge);

    return (
        <div className="flex h-full items-center">
            <span
                className={cn(
                    'inline-flex h-[18px] items-center rounded px-1.5 text-[10px] leading-none font-semibold',
                    sentinel ? 'bg-amber-50 text-amber-600' : 'text-gray-500',
                )}
            >
                {formatUnitValue(Number(surcharge))}
            </span>
            {sentinel && (
                <span className="ml-1 text-[8px] font-bold tracking-wider text-amber-600 uppercase">
                    sentinel
                </span>
            )}
        </div>
    );
};

export function EntityDetailView({
    entityType,
    identity,
    payloadSupported,
    features,
    dataValues,
    featureDisclaimers,
}: EntityDetailViewProps) {
    const isVariant = entityType === 'variant';
    const locale = useCatalogLocale();

    const resolvedName =
        identity.localizedNames !== undefined
            ? pickName(
                  identity.localizedNames.name_de,
                  identity.localizedNames.name_fr,
                  identity.localizedNames.name_it,
                  locale,
                  identity.name,
              )
            : { text: identity.name, locale: null, fellBack: false };

    const [featureColumnDefs] = useState<ColDef<CatalogFeature>[]>([
        {
            colId: 'feature_code',
            headerName: 'Feature code',
            field: 'feature_code',
            flex: 2,
            minWidth: 220,
            cellRenderer: FeatureCodeCell,
        },
        {
            colId: 'availability',
            headerName: 'Availability',
            field: 'availability',
            width: 130,
            cellRenderer: AvailabilityCell,
        },
        {
            colId: 'surcharge',
            headerName: 'Surcharge',
            field: 'surcharge',
            width: 140,
            cellRenderer: SurchargeCell,
        },
    ]);

    const [dataColumnDefs] = useState<ColDef<CatalogDataValue>[]>([
        {
            colId: 'data_code',
            headerName: 'Data code',
            field: 'data_code',
            flex: 2,
            minWidth: 200,
            cellRenderer: (
                params: CustomCellRendererProps<CatalogDataValue>,
            ) => (
                <div className="flex h-full items-center font-mono text-[11px] text-astara-purple">
                    {params.data?.data_code}
                </div>
            ),
        },
        {
            colId: 'value',
            headerName: 'Value',
            field: 'value',
            flex: 1,
            minWidth: 160,
            cellRenderer: (
                params: CustomCellRendererProps<CatalogDataValue>,
            ) => (
                <div className="flex h-full items-center text-[11px] font-semibold text-gray-600">
                    {params.data?.value}
                </div>
            ),
        },
        {
            colId: 'unit_code',
            headerName: 'Unit',
            field: 'unit_code',
            width: 140,
            cellRenderer: (
                params: CustomCellRendererProps<CatalogDataValue>,
            ) => (
                <div className="flex h-full items-center">
                    <span className="inline-flex h-[18px] items-center rounded border border-slate-200 bg-slate-100 px-1.5 text-[9px] leading-none font-bold text-slate-600">
                        {params.data?.unit_code}
                    </span>
                </div>
            ),
        },
    ]);

    const crumbTo = isVariant
        ? variantsIndex()
        : identity.links?.model
          ? `/models/${identity.links.model.id}`
          : '/models';
    const crumbLabel = isVariant
        ? 'Variants'
        : (identity.links?.model?.name ?? 'Models');

    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={crumbTo}
                            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} /> {crumbLabel}
                        </Link>
                        {!isVariant && identity.links?.bodyType && (
                            <>
                                <span className="text-[10px] text-gray-300">
                                    /
                                </span>
                                <Link
                                    href={`/models/${identity.links.model?.id}/body-types/${identity.links.bodyType.id}`}
                                    className="cursor-pointer text-[10px] font-bold tracking-widest text-gray-400 uppercase transition-colors hover:text-astara-orange"
                                >
                                    {identity.links.bodyType.name}
                                </Link>
                            </>
                        )}
                    </div>
                    <div className="flex items-center gap-2.5">
                        <EntityTypeChip type={entityType} />
                        <h2 className="text-2xl font-bold text-astara-purple">
                            {resolvedName.text}
                        </h2>
                        {resolvedName.fellBack && (
                            <LocaleFallbackChip
                                requested={locale}
                                used={resolvedName.locale}
                            />
                        )}
                        <span className="font-mono text-[11px] text-gray-400">
                            {identity.key}
                        </span>
                        {identity.description && (
                            <span className="hidden text-[11px] text-gray-400 italic lg:inline">
                                {identity.description}
                            </span>
                        )}
                    </div>
                    <p className="mt-1 text-[11px] font-bold tracking-widest text-gray-500 uppercase">
                        {entityType} detail
                    </p>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                    {identity.localizedNames !== undefined && (
                        <LocaleCoverageChips names={identity.localizedNames} />
                    )}
                    {isVariant && identity.price !== undefined && (
                        <PriceCell price={identity.price} />
                    )}
                    <CatalogStatusBadge status={identity.status} />
                    <LocaleSwitch />
                </div>
            </header>

            {isVariant && identity.links && (
                <div className="flex flex-wrap items-center gap-1.5 border-b border-gray-100 bg-white px-5 pb-3">
                    <span className="mr-1 text-[9px] font-bold tracking-widest text-gray-400 uppercase">
                        Linked
                    </span>
                    {identity.links.model && (
                        <Link
                            href={`/models/${identity.links.model.id}`}
                            className="inline-flex h-[20px] cursor-pointer items-center rounded bg-slate-100 px-2 text-[9px] font-bold tracking-wider text-slate-600 uppercase transition-colors hover:bg-slate-200"
                        >
                            {identity.links.model.names !== undefined
                                ? pickName(
                                      identity.links.model.names.name_de,
                                      identity.links.model.names.name_fr,
                                      identity.links.model.names.name_it,
                                      locale,
                                      identity.links.model.name,
                                  ).text
                                : identity.links.model.name}
                        </Link>
                    )}
                    {identity.links.bodyType && identity.links.model && (
                        <Link
                            href={`/models/${identity.links.model.id}/body-types/${identity.links.bodyType.id}`}
                            className="inline-flex h-[20px] cursor-pointer items-center rounded bg-slate-100 px-2 text-[9px] font-bold tracking-wider text-slate-600 uppercase transition-colors hover:bg-slate-200"
                        >
                            {identity.links.bodyType.body_key}
                        </Link>
                    )}
                    {identity.links.trim &&
                        identity.links.model &&
                        identity.links.bodyType && (
                            <Link
                                href={`/models/${identity.links.model.id}/body-types/${identity.links.bodyType.id}/trims/${identity.links.trim.id}`}
                                className="inline-flex h-[20px] cursor-pointer items-center rounded bg-slate-100 px-2 text-[9px] font-bold tracking-wider text-slate-600 uppercase transition-colors hover:bg-slate-200"
                            >
                                {identity.links.trim.trim_key}
                            </Link>
                        )}
                    {identity.links.engine &&
                        identity.links.model &&
                        identity.links.bodyType && (
                            <Link
                                href={`/models/${identity.links.model.id}/body-types/${identity.links.bodyType.id}/engines/${identity.links.engine.id}`}
                                className="inline-flex h-[20px] cursor-pointer items-center rounded bg-slate-100 px-2 text-[9px] font-bold tracking-wider text-slate-600 uppercase transition-colors hover:bg-slate-200"
                            >
                                {identity.links.engine.engine_key}
                            </Link>
                        )}
                </div>
            )}

            <div className="space-y-6 p-6">
                <SectionCard
                    title={`Features — ${formatCount(features.length)}`}
                >
                    {features.length === 0 ? (
                        <EmptyState
                            icon={FileText}
                            title={
                                payloadSupported
                                    ? 'No feature rows for this variant in the vendor feed'
                                    : 'Feature payload not served yet'
                            }
                            description={
                                payloadSupported
                                    ? 'Feature data may live on the trim or engine instead — the availability rules are not interpreted here.'
                                    : 'The catalog API does not serve features/data values for engines and trims yet; variant detail pages carry the full feature payload.'
                            }
                        />
                    ) : (
                        <div className="h-[420px]">
                            <Deferred
                                data={['features']}
                                fallback={<GridSkeleton rows={6} />}
                            >
                                <AgGridReact<CatalogFeature>
                                    theme={astaraGridTheme}
                                    rowData={features}
                                    columnDefs={featureColumnDefs}
                                    getRowId={(params) =>
                                        String(params.data.id)
                                    }
                                    rowHeight={38}
                                    headerHeight={36}
                                    suppressCellFocus
                                    defaultColDef={{ resizable: true }}
                                />
                            </Deferred>
                        </div>
                    )}
                </SectionCard>

                <SectionCard
                    title={`Data values — ${formatCount(dataValues.length)}`}
                >
                    {dataValues.length === 0 ? (
                        <EmptyState
                            icon={FileText}
                            title={
                                payloadSupported
                                    ? 'No data values for this variant in the vendor feed'
                                    : 'Data-value payload not served yet'
                            }
                        />
                    ) : (
                        <div className="h-[300px]">
                            <Deferred
                                data={['data_values']}
                                fallback={<GridSkeleton rows={5} />}
                            >
                                <AgGridReact<CatalogDataValue>
                                    theme={astaraGridTheme}
                                    rowData={dataValues}
                                    columnDefs={dataColumnDefs}
                                    getRowId={(params) =>
                                        String(params.data.id)
                                    }
                                    rowHeight={38}
                                    headerHeight={36}
                                    suppressCellFocus
                                    defaultColDef={{ resizable: true }}
                                />
                            </Deferred>
                        </div>
                    )}
                </SectionCard>

                <SectionCard
                    title={`Disclaimers — ${formatCount(featureDisclaimers.length)}`}
                >
                    {featureDisclaimers.length === 0 ? (
                        <div className="px-4 py-6 text-[11px] text-gray-400">
                            No disclaimers for this {entityType}.
                        </div>
                    ) : (
                        <div className="divide-y divide-gray-50">
                            {featureDisclaimers.map((disclaimer) => (
                                <DisclaimerRow
                                    key={disclaimer.id}
                                    disclaimer={disclaimer}
                                />
                            ))}
                        </div>
                    )}
                </SectionCard>
            </div>
        </div>
    );
}

function PriceCell({ price }: { price: number }) {
    const sentinel = isPriceSentinel(price);

    return (
        <div className="flex items-center gap-1.5">
            <span
                className={cn(
                    'text-sm font-bold',
                    sentinel ? 'text-amber-600' : 'text-astara-purple',
                )}
            >
                {formatPrice(price)}
            </span>
            {sentinel && (
                <Tooltip>
                    <TooltipTrigger asChild>
                        <span className="inline-flex h-[18px] cursor-help items-center rounded bg-amber-50 px-1.5 text-[8px] font-bold tracking-wider text-amber-600 uppercase">
                            sentinel
                        </span>
                    </TooltipTrigger>
                    <TooltipContent>
                        Price kept verbatim from the vendor feed — not
                        interpreted.
                    </TooltipContent>
                </Tooltip>
            )}
        </div>
    );
}

function DisclaimerRow({
    disclaimer,
}: {
    disclaimer: CatalogFeatureDisclaimer;
}) {
    const locale = useCatalogLocale();
    const resolved = pickName(
        disclaimer.disclaimer_de,
        disclaimer.disclaimer_fr,
        disclaimer.disclaimer_it,
        locale,
    );
    const others = CATALOG_LOCALES.filter((code) => code !== resolved.locale)
        .map((code) => disclaimer[`disclaimer_${code}`])
        .filter(
            (text): text is string =>
                text !== null && text !== undefined && text !== '',
        );

    return (
        <div className="flex items-start gap-3 px-4 py-2.5">
            <span className="mt-0.5 shrink-0 font-mono text-[10px] text-gray-400">
                {disclaimer.feature_code}
            </span>
            <p className="flex-1 text-[11px] leading-relaxed text-gray-600">
                {resolved.text || '—'}
            </p>
            {resolved.fellBack && (
                <LocaleFallbackChip requested={locale} used={resolved.locale} />
            )}
            {others.length > 0 && (
                <Tooltip>
                    <TooltipTrigger asChild>
                        <span className="shrink-0 cursor-help rounded bg-gray-100 px-1.5 py-0.5 text-[8px] font-bold tracking-wider text-gray-400 uppercase">
                            FR/IT
                        </span>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-sm space-y-1">
                        {others.map((text, index) => (
                            <p key={index} className="text-[10px]">
                                {text}
                            </p>
                        ))}
                    </TooltipContent>
                </Tooltip>
            )}
        </div>
    );
}

function GridSkeleton({ rows }: { rows: number }) {
    return (
        <div className="flex flex-col gap-2 p-4">
            <Skeleton className="h-8 w-full" />
            {Array.from({ length: rows }).map((_, index) => (
                <Skeleton key={index} className="h-8 w-full" />
            ))}
        </div>
    );
}

function formatCount(value: number): string {
    return new Intl.NumberFormat('de-CH').format(value);
}
