import { Form, Head, router } from '@inertiajs/react';
import { useMemo, useRef, useState } from 'react';

import HeadingSmall from '@/components/heading-small';
import { SortableHeader, useSort } from '@/components/sortable-header';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import AppLayout from '@/layouts/app-layout';
import { index, store, update, destroy, exportMethod, importMethod } from '@/routes/admin/supplier-utility-mappings';

type Supplier = {
    id: number;
    name: string;
    slug: string;
};

type State = {
    id: number;
    code: string;
    name: string;
};

type Utility = {
    id: number;
    name: string;
    code: string | null;
    state: State;
};

type Mapping = {
    id: number;
    supplier_id: number;
    utility_id: number;
    name: string | null;
    code: string | null;
    representative_zip_code: string | null;
    external_id: string | null;
    requires_credit_check: boolean;
    requires_fraud_check: boolean;
    hide_marketing_consent: boolean | null;
    hide_bill_delivery_preference: boolean | null;
    switch_on_meter_read_cycle: boolean | null;
    account_number_validation_regex: string | null;
    second_account_number_validation_regex: string | null;
    supplier: Supplier;
    utility: Utility;
};

type MissingUtility = {
    internal_territory_code: string | null;
    code: string | null;
    name: string | null;
    state_code: string | null;
    mapping_name: string | null;
    mapping_code: string | null;
};

type ImportResult = {
    error?: string;
    importedCount?: number;
    skippedCount?: number;
    missingUtilities?: MissingUtility[];
};

type Props = {
    mappings: Mapping[];
    suppliers: Supplier[];
    utilities: Utility[];
    isProduction: boolean;
    importResult?: ImportResult;
};

const breadcrumbs = [{ title: 'Supplier Utility Mappings', href: index.url() }];

const inputClasses = 'rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950';
const labelClasses = 'text-xs font-medium text-zinc-700 dark:text-zinc-300';

function TriStateBadge({ value }: { value: boolean | null }) {
    if (value === null) {
        return <span className="text-zinc-400">—</span>;
    }

    return value ? (
        <span className="rounded-full bg-sky-100 px-2 py-0.5 text-xs font-medium text-sky-800 dark:bg-sky-900/30 dark:text-sky-400">Yes</span>
    ) : (
        <span className="rounded-full bg-zinc-100 px-2 py-0.5 text-xs font-medium text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">No</span>
    );
}

function MappingForm({
    suppliers,
    utilities,
    defaults,
    onCancel,
    submitLabel,
}: {
    suppliers: Supplier[];
    utilities: Utility[];
    defaults?: Mapping;
    onCancel: () => void;
    submitLabel: string;
}) {
    return ({ processing, errors }: { processing: boolean; errors: Record<string, string> }) => (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Supplier</label>
                <select name="supplier_id" defaultValue={defaults?.supplier_id ?? ''} className={inputClasses}>
                    <option value="" disabled>Select…</option>
                    {suppliers.map((s) => (
                        <option key={s.id} value={s.id}>{s.name}</option>
                    ))}
                </select>
                {errors.supplier_id && <div className="text-xs text-red-600">{errors.supplier_id}</div>}
            </div>

            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Utility</label>
                <select name="utility_id" defaultValue={defaults?.utility_id ?? ''} className={inputClasses}>
                    <option value="" disabled>Select…</option>
                    {utilities.map((u) => (
                        <option key={u.id} value={u.id}>{u.name}{u.code ? ` (${u.code})` : ''}</option>
                    ))}
                </select>
                {errors.utility_id && <div className="text-xs text-red-600">{errors.utility_id}</div>}
            </div>

            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Name</label>
                <input name="name" defaultValue={defaults?.name ?? ''} className={inputClasses} placeholder="Supplier's name for this utility" />
                {errors.name && <div className="text-xs text-red-600">{errors.name}</div>}
            </div>

            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Code</label>
                <input name="code" defaultValue={defaults?.code ?? ''} className={inputClasses} placeholder="e.g. ONCOR" />
                {errors.code && <div className="text-xs text-red-600">{errors.code}</div>}
            </div>

            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Representative zip code</label>
                <input
                    name="representative_zip_code"
                    defaultValue={defaults?.representative_zip_code ?? ''}
                    className={inputClasses}
                    placeholder="e.g. 45122"
                />
                {errors.representative_zip_code && <div className="text-xs text-red-600">{errors.representative_zip_code}</div>}
            </div>

            <div className="flex flex-col gap-1 sm:col-span-2">
                <label className={labelClasses}>External ID</label>
                <input name="external_id" defaultValue={defaults?.external_id ?? ''} className={inputClasses} placeholder="Supplier's external identifier" />
                {errors.external_id && <div className="text-xs text-red-600">{errors.external_id}</div>}
            </div>

            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Account number validation regex</label>
                <input
                    name="account_number_validation_regex"
                    defaultValue={defaults?.account_number_validation_regex ?? ''}
                    className={inputClasses}
                    placeholder="e.g. 7200 ### ####"
                />
                {errors.account_number_validation_regex && (
                    <div className="text-xs text-red-600">{errors.account_number_validation_regex}</div>
                )}
            </div>

            <div className="flex flex-col gap-1">
                <label className={labelClasses}>Second account number validation regex</label>
                <input
                    name="second_account_number_validation_regex"
                    defaultValue={defaults?.second_account_number_validation_regex ?? ''}
                    className={inputClasses}
                    placeholder="e.g. #### ####"
                />
                {errors.second_account_number_validation_regex && (
                    <div className="text-xs text-red-600">{errors.second_account_number_validation_regex}</div>
                )}
            </div>

            <div className="flex items-center gap-2 sm:col-span-2">
                <input type="hidden" name="requires_credit_check" value="0" />
                <input
                    type="checkbox"
                    id="requires_credit_check"
                    name="requires_credit_check"
                    value="1"
                    defaultChecked={defaults?.requires_credit_check ?? false}
                    className="h-4 w-4 rounded border-zinc-300 text-zinc-900 focus:ring-zinc-500 dark:border-zinc-700"
                />
                <label htmlFor="requires_credit_check" className={labelClasses}>Requires credit check</label>
            </div>

            <div className="flex items-center gap-2 sm:col-span-2">
                <input type="hidden" name="requires_fraud_check" value="0" />
                <input
                    type="checkbox"
                    id="requires_fraud_check"
                    name="requires_fraud_check"
                    value="1"
                    defaultChecked={defaults?.requires_fraud_check ?? false}
                    className="h-4 w-4 rounded border-zinc-300 text-zinc-900 focus:ring-zinc-500 dark:border-zinc-700"
                />
                <label htmlFor="requires_fraud_check" className={labelClasses}>Requires fraud check</label>
            </div>

            <div className="flex items-end justify-end gap-3 sm:col-span-2">
                <button
                    type="button"
                    onClick={onCancel}
                    className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                >
                    Cancel
                </button>
                <button
                    type="submit"
                    disabled={processing}
                    className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                >
                    {submitLabel}
                </button>
            </div>
        </div>
    );
}

export default function SupplierUtilityMappings({ mappings, suppliers, utilities, isProduction, importResult }: Props) {
    const [editingId, setEditingId] = useState<number | null>(null);
    const [createOpen, setCreateOpen] = useState(false);
    const [filterSupplierId, setFilterSupplierId] = useState('');
    const [filterUtilityId, setFilterUtilityId] = useState('');
    const [pendingImportFile, setPendingImportFile] = useState<File | null>(null);
    const [confirmationText, setConfirmationText] = useState('');
    const [importing, setImporting] = useState(false);
    const [importResultOpen, setImportResultOpen] = useState(!!importResult);
    const importInputRef = useRef<HTMLInputElement>(null);
    const { sorted, sortColumn, sortDirection, toggleSort } = useSort(mappings, 'supplier_id', 'asc', {
        state_id: (m) => m.utility?.state?.code,
    });

    const exportSupplier = suppliers.find((s) => s.id === Number(filterSupplierId)) ?? null;

    function handleImportFileSelected(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!file) return;
        setConfirmationText('');
        setPendingImportFile(file);
    }

    function handleConfirmImport() {
        if (!pendingImportFile || !exportSupplier) return;

        setImporting(true);
        const data = new FormData();
        data.append('file', pendingImportFile);
        data.append('confirm', '1');

        router.post(importMethod.url(exportSupplier.id), data, {
            onFinish: () => {
                setImporting(false);
                setPendingImportFile(null);
                setConfirmationText('');
                if (importInputRef.current) {
                    importInputRef.current.value = '';
                }
            },
            onSuccess: () => setImportResultOpen(true),
        });
    }

    const requiredConfirmationText = exportSupplier ? exportSupplier.slug : '';
    const canConfirmImport = !isProduction || confirmationText.trim() === requiredConfirmationText;

    const filtered = useMemo(() => {
        return sorted.filter((m) => {
            if (filterSupplierId && m.supplier_id !== Number(filterSupplierId)) return false;
            if (filterUtilityId && m.utility_id !== Number(filterUtilityId)) return false;
            return true;
        });
    }, [sorted, filterSupplierId, filterUtilityId]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Supplier Utility Mappings" />

            <h1 className="sr-only">Supplier Utility Mappings</h1>

            <div className="space-y-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Supplier Utility Mappings"
                        description="Map suppliers to utilities with their internal codes and identifiers."
                    />

                    <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                        <DialogTrigger asChild>
                            <button
                                type="button"
                                className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
                            >
                                Add mapping
                            </button>
                        </DialogTrigger>

                        <DialogContent className="sm:max-w-lg">
                            <DialogHeader>
                                <DialogTitle>Add mapping</DialogTitle>
                                <DialogDescription>
                                    Create a new supplier–utility mapping.
                                </DialogDescription>
                            </DialogHeader>

                            <Form
                                method="post"
                                action={store.url()}
                                resetOnSuccess
                                onSuccess={() => setCreateOpen(false)}
                            >
                                {MappingForm({ suppliers, utilities, onCancel: () => setCreateOpen(false), submitLabel: 'Add mapping' })}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* Filters */}
                <div className="flex flex-wrap items-end gap-3">
                    <div className="flex flex-col gap-1">
                        <label className={labelClasses}>Supplier</label>
                        <select
                            value={filterSupplierId}
                            onChange={(e) => setFilterSupplierId(e.target.value)}
                            className={inputClasses}
                        >
                            <option value="">All suppliers</option>
                            {suppliers.map((s) => (
                                <option key={s.id} value={s.id}>{s.name}</option>
                            ))}
                        </select>
                    </div>

                    <div className="flex items-center gap-2">
                        <a
                            href={exportSupplier ? exportMethod.url(exportSupplier.id) : undefined}
                            aria-disabled={!exportSupplier}
                            className={`rounded-md border border-zinc-200 px-3 py-2 text-sm font-medium text-zinc-700 hover:bg-zinc-50 dark:border-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-900 ${!exportSupplier ? 'pointer-events-none opacity-50' : ''}`}
                        >
                            Export mappings
                        </a>

                        <input
                            ref={importInputRef}
                            type="file"
                            accept=".json,application/json"
                            className="hidden"
                            onChange={handleImportFileSelected}
                        />
                        <button
                            type="button"
                            disabled={!exportSupplier}
                            onClick={() => importInputRef.current?.click()}
                            className="rounded-md border border-zinc-200 px-3 py-2 text-sm font-medium text-zinc-700 hover:bg-zinc-50 disabled:opacity-50 dark:border-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-900"
                        >
                            Import mappings
                        </button>
                    </div>

                    {!exportSupplier && (
                        <p className="pb-2 text-xs text-zinc-500 dark:text-zinc-400">
                            Select a supplier above to export or import its mappings.
                        </p>
                    )}

                    <div className="flex flex-col gap-1">
                        <label className={labelClasses}>Utility</label>
                        <select
                            value={filterUtilityId}
                            onChange={(e) => setFilterUtilityId(e.target.value)}
                            className={inputClasses}
                        >
                            <option value="">All utilities</option>
                            {utilities.map((u) => (
                                <option key={u.id} value={u.id}>{u.name}{u.code ? ` (${u.code})` : ''}</option>
                            ))}
                        </select>
                    </div>

                    {(filterSupplierId || filterUtilityId) && (
                        <div className="flex flex-col justify-end">
                            <button
                                type="button"
                                onClick={() => { setFilterSupplierId(''); setFilterUtilityId(''); }}
                                className="rounded-md px-3 py-2 text-sm text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                            >
                                Clear filters
                            </button>
                        </div>
                    )}
                </div>

                {/* Mappings table */}
                <div className="overflow-hidden rounded-md border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm">
                            <thead className="border-b border-zinc-200 text-xs uppercase text-zinc-600 dark:border-zinc-800 dark:text-zinc-400">
                                <tr>
                                    <SortableHeader label="Supplier" column="supplier_id" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Utility" column="utility_id" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Name" column="name" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Code" column="code" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Rep. Zip" column="representative_zip_code" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="State" column="state_id" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="External ID" column="external_id" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Credit Check" column="requires_credit_check" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Fraud Check" column="requires_fraud_check" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader
                                        label="Hide Marketing Consent"
                                        column="hide_marketing_consent"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                        title="Atlantic Energy: TDSP.market.hide_marketing_consent, reconciled on each product import"
                                    />
                                    <SortableHeader
                                        label="Hide Bill Delivery Pref."
                                        column="hide_bill_delivery_preference"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                        title="Atlantic Energy: TDSP.hide_bill_delivery_preference, reconciled on each product import"
                                    />
                                    <SortableHeader
                                        label="Switch on Meter Read Cycle"
                                        column="switch_on_meter_read_cycle"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                        title="Atlantic Energy: TDSP.switch_on_meter_read_cycle, reconciled on each product import"
                                    />
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {filtered.map((m) => (
                                    <tr key={m.id}>
                                        <td className="px-4 py-3 font-medium">{m.supplier?.name ?? '—'}</td>
                                        <td className="px-4 py-3">
                                            {m.utility ? (
                                                <>
                                                    {m.utility.name}
                                                    {m.utility.code && (
                                                        <span className="ml-1 font-mono text-xs text-zinc-500">({m.utility.code})</span>
                                                    )}
                                                </>
                                            ) : '—'}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">{m.name ?? '—'}</td>
                                        <td className="px-4 py-3 font-mono text-xs">{m.code ?? '—'}</td>
                                        <td className="px-4 py-3 font-mono text-xs">{m.representative_zip_code ?? '—'}</td>
                                        <td className="px-4 py-3">
                                            {m.utility.state ? (
                                                <>
                                                    {m.utility.state.code}
                                                </>
                                            ) : '—'}
                                        </td>
                                        <td className="px-4 py-3 font-mono text-xs text-zinc-600 dark:text-zinc-400">{m.external_id ?? '—'}</td>
                                        <td className="px-4 py-3">
                                            {m.requires_credit_check ? (
                                                <span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800 dark:bg-amber-900/30 dark:text-amber-400">Required</span>
                                            ) : (
                                                <span className="text-zinc-400">—</span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3">
                                            {m.requires_fraud_check ? (
                                                <span className="rounded-full bg-purple-100 px-2 py-0.5 text-xs font-medium text-purple-800 dark:bg-purple-900/30 dark:text-purple-400">Required</span>
                                            ) : (
                                                <span className="text-zinc-400">—</span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3">
                                            <TriStateBadge value={m.hide_marketing_consent} />
                                        </td>
                                        <td className="px-4 py-3">
                                            <TriStateBadge value={m.hide_bill_delivery_preference} />
                                        </td>
                                        <td className="px-4 py-3">
                                            <TriStateBadge value={m.switch_on_meter_read_cycle} />
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex items-center justify-end gap-4">
                                                <Dialog
                                                    open={editingId === m.id}
                                                    onOpenChange={(open) => setEditingId(open ? m.id : null)}
                                                >
                                                    <DialogTrigger asChild>
                                                        <button
                                                            type="button"
                                                            className="text-sm text-zinc-700 hover:underline dark:text-zinc-300"
                                                        >
                                                            Edit
                                                        </button>
                                                    </DialogTrigger>

                                                    <DialogContent className="sm:max-w-lg">
                                                        <DialogHeader>
                                                            <DialogTitle>Edit mapping</DialogTitle>
                                                            <DialogDescription>
                                                                Update {m.supplier?.name} → {m.utility?.name} mapping.
                                                            </DialogDescription>
                                                        </DialogHeader>

                                                        <Form
                                                            method="put"
                                                            action={update.url(m.id)}
                                                            onSuccess={() => setEditingId(null)}
                                                        >
                                                            {MappingForm({ suppliers, utilities, defaults: m, onCancel: () => setEditingId(null), submitLabel: 'Save' })}
                                                        </Form>
                                                    </DialogContent>
                                                </Dialog>

                                                <Form method="delete" action={destroy.url(m.id)}>
                                                    {({ processing }) => (
                                                        <button
                                                            type="submit"
                                                            disabled={processing}
                                                            className="text-sm text-red-700 hover:underline disabled:opacity-60 dark:text-red-400"
                                                        >
                                                            Delete
                                                        </button>
                                                    )}
                                                </Form>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    {filtered.length === 0 && (
                        <div className="p-4 text-sm text-zinc-600 dark:text-zinc-400">
                            {mappings.length === 0 ? 'No mappings yet.' : 'No mappings match the selected filters.'}
                        </div>
                    )}
                </div>
            </div>

            <Dialog
                open={!!pendingImportFile}
                onOpenChange={(open) => {
                    if (!open) {
                        setPendingImportFile(null);
                        setConfirmationText('');
                        if (importInputRef.current) importInputRef.current.value = '';
                    }
                }}
            >
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Overwrite mappings for {exportSupplier?.name}?</DialogTitle>
                        <DialogDescription>
                            Importing <span className="font-mono">{pendingImportFile?.name}</span> will{' '}
                            <span className="font-semibold text-red-600 dark:text-red-400">
                                permanently delete all existing utility mappings
                            </span>{' '}
                            for {exportSupplier?.name} and replace them with the mappings in this file. This cannot be
                            undone.
                        </DialogDescription>
                    </DialogHeader>

                    {isProduction && (
                        <div className="space-y-2 rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-900 dark:bg-red-950/40">
                            <p className="text-sm font-medium text-red-800 dark:text-red-300">
                                This is production. Type the supplier slug (
                                <span className="font-mono">{requiredConfirmationText}</span>) to confirm.
                            </p>
                            <input
                                type="text"
                                value={confirmationText}
                                onChange={(e) => setConfirmationText(e.target.value)}
                                placeholder={requiredConfirmationText}
                                className="w-full rounded-md border border-red-300 bg-white px-3 py-2 font-mono text-sm dark:border-red-800 dark:bg-zinc-950"
                            />
                        </div>
                    )}

                    <DialogFooter>
                        <button
                            type="button"
                            onClick={() => setPendingImportFile(null)}
                            className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                        >
                            Cancel
                        </button>
                        <button
                            type="button"
                            disabled={!canConfirmImport || importing}
                            onClick={handleConfirmImport}
                            className="rounded-md bg-red-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
                        >
                            {importing ? 'Importing…' : 'Overwrite mappings'}
                        </button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={importResultOpen} onOpenChange={setImportResultOpen}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>
                            {importResult?.error ? 'Import failed' : 'Import complete'}
                        </DialogTitle>
                        <DialogDescription asChild>
                            <div className="space-y-3 text-left">
                                {importResult?.error && (
                                    <p className="text-sm text-red-600 dark:text-red-400">{importResult.error}</p>
                                )}

                                {!importResult?.error && (
                                    <p className="text-sm">
                                        Imported {importResult?.importedCount ?? 0} mapping
                                        {importResult?.importedCount === 1 ? '' : 's'}
                                        {!!importResult?.skippedCount &&
                                            `, skipped ${importResult.skippedCount} due to missing utilities.`}
                                    </p>
                                )}

                                {!!importResult?.missingUtilities?.length && (
                                    <div className="space-y-2">
                                        <p className="text-sm font-medium text-amber-700 dark:text-amber-400">
                                            The following utilities don&apos;t exist yet. Create them first (Admin →
                                            Utilities), then re-import to include these mappings.
                                        </p>
                                        <div className="max-h-64 overflow-y-auto rounded-md border border-amber-200 dark:border-amber-900">
                                            {importResult.missingUtilities.map((u, i) => (
                                                <div
                                                    key={i}
                                                    className="border-b border-amber-100 px-3 py-2 text-xs last:border-b-0 dark:border-amber-900/50"
                                                >
                                                    <div className="font-medium text-zinc-900 dark:text-zinc-100">
                                                        {u.name ?? 'Unnamed utility'}
                                                        {u.state_code && ` (${u.state_code})`}
                                                    </div>
                                                    <div className="text-zinc-500 dark:text-zinc-400">
                                                        {u.code && <>code: <span className="font-mono">{u.code}</span> </>}
                                                        {u.internal_territory_code && (
                                                            <>territory code: <span className="font-mono">{u.internal_territory_code}</span> </>
                                                        )}
                                                    </div>
                                                    {(u.mapping_name || u.mapping_code) && (
                                                        <div className="text-zinc-500 dark:text-zinc-400">
                                                            mapping: {u.mapping_name ?? '—'}
                                                            {u.mapping_code ? ` (${u.mapping_code})` : ''}
                                                        </div>
                                                    )}
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </div>
                        </DialogDescription>
                    </DialogHeader>

                    <DialogFooter>
                        <button
                            type="button"
                            onClick={() => setImportResultOpen(false)}
                            className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
                        >
                            Close
                        </button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}
