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

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

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

type Utility = {
    id: number;
    name: string;
    code: string | null;
    state_id: number;
    state: State;
    external_id: string | null;
    electric_usage_uom: string | null;
    gas_usage_uom: string | null;
    rate_decimal_places: number | null;
    primary_account_identifier_name: string | null;
    primary_account_identifier_example: string | null;
    primary_account_identifier_regex: string | null;
    primary_account_identifier_help_text: string | null;
    has_secondary_account_identifier: boolean;
    secondary_account_identifier_name: string | null;
    secondary_account_identifier_example: string | null;
    secondary_account_identifier_regex: string | null;
    secondary_account_identifier_help_text: string | null;
    has_tertiary_account_identifier: boolean;
    tertiary_account_identifier_name: string | null;
    tertiary_account_identifier_example: string | null;
    tertiary_account_identifier_regex: string | null;
    tertiary_account_identifier_help_text: string | null;
    bill_sample_image_url: string | null;
    internal_territory_code: string | null;
    zip_codes_count: number;
};

type Props = {
    utilities: Utility[];
    states: State[];
    canImport: boolean;
};

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

const uoms = ['kWh', 'therm', 'CCF', 'MCF', 'DTH'];

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 AccountIdentifierFields({
    prefix,
    label,
    defaults,
    errors,
}: {
    prefix: string;
    label: string;
    defaults?: { name?: string | null; example?: string | null; regex?: string | null; help_text?: string | null };
    errors: Record<string, string>;
}) {
    return (
        <fieldset className="space-y-3 rounded-md border border-zinc-200 p-3 dark:border-zinc-800">
            <legend className="px-1 text-xs font-semibold text-zinc-600 dark:text-zinc-400">{label}</legend>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <div className="flex flex-col gap-1">
                    <label className={labelClasses}>Name</label>
                    <input name={`${prefix}_name`} defaultValue={defaults?.name ?? ''} className={inputClasses} placeholder="e.g. ESIID" />
                    {errors[`${prefix}_name`] && <div className="text-xs text-red-600">{errors[`${prefix}_name`]}</div>}
                </div>
                <div className="flex flex-col gap-1">
                    <label className={labelClasses}>Example</label>
                    <input name={`${prefix}_example`} defaultValue={defaults?.example ?? ''} className={inputClasses} placeholder="e.g. 1234567890" />
                    {errors[`${prefix}_example`] && <div className="text-xs text-red-600">{errors[`${prefix}_example`]}</div>}
                </div>
                <div className="flex flex-col gap-1">
                    <label className={labelClasses}>Regex pattern</label>
                    <input name={`${prefix}_regex`} defaultValue={defaults?.regex ?? ''} className={inputClasses} placeholder="^[0-9]{10}$" />
                    {errors[`${prefix}_regex`] && <div className="text-xs text-red-600">{errors[`${prefix}_regex`]}</div>}
                </div>
                <div className="flex flex-col gap-1">
                    <label className={labelClasses}>Help text</label>
                    <input name={`${prefix}_help_text`} defaultValue={defaults?.help_text ?? ''} className={inputClasses} placeholder="Enter your 10-digit ID" />
                    {errors[`${prefix}_help_text`] && <div className="text-xs text-red-600">{errors[`${prefix}_help_text`]}</div>}
                </div>
            </div>
        </fieldset>
    );
}

export default function Utilities({ utilities, states, canImport }: Props) {
    const { props: { flash } } = usePage<{ flash: { success?: string } }>();
    const [editingId, setEditingId] = useState<number | null>(null);
    const [createOpen, setCreateOpen] = useState(false);
    const [zipCodesUtilityId, setZipCodesUtilityId] = useState<number | null>(null);
    const [importing, setImporting] = useState(false);
    const [importError, setImportError] = useState<string | null>(null);
    const importInputRef = useRef<HTMLInputElement>(null);
    const zipCodesUtility = utilities.find((u) => u.id === zipCodesUtilityId) ?? null;
    const { sorted, sortColumn, sortDirection, toggleSort } = useSort(utilities, 'name');

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

        setImporting(true);
        setImportError(null);
        const data = new FormData();
        data.append('file', file);

        router.post(importMethod.url(), data, {
            onError: (errors) => setImportError(errors.file ?? 'Failed to import utilities file.'),
            onFinish: () => {
                setImporting(false);
                if (importInputRef.current) {
                    importInputRef.current.value = '';
                }
            },
        });
    }

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Utilities" />

            <h1 className="sr-only">Utilities</h1>

            <div className="space-y-6">
                {flash?.success && (
                    <div className="rounded-md bg-green-50 px-4 py-3 text-sm text-green-800 dark:bg-green-950 dark:text-green-200">
                        {flash.success}
                    </div>
                )}

                {importError && (
                    <div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800 dark:border-red-900 dark:bg-red-950 dark:text-red-300">
                        {importError}
                    </div>
                )}

                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Utilities"
                        description="Manage utility companies and their configurations."
                    />

                    <div className="flex flex-wrap items-center gap-2">
                        <a
                            href={exportMethod.url()}
                            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"
                        >
                            Download JSON
                        </a>

                        {canImport && (
                            <>
                                <input
                                    ref={importInputRef}
                                    type="file"
                                    accept=".json,application/json"
                                    className="hidden"
                                    onChange={handleImportFile}
                                />
                                <button
                                    type="button"
                                    disabled={importing}
                                    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-60 dark:border-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-900"
                                >
                                    {importing ? 'Importing…' : 'Import from Production'}
                                </button>
                            </>
                        )}

                    <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 utility
                            </button>
                        </DialogTrigger>

                        <DialogContent className="sm:max-w-2xl max-h-[80vh] overflow-y-auto">
                            <DialogHeader>
                                <DialogTitle>Add utility</DialogTitle>
                                <DialogDescription>
                                    Create a new utility company and configure its settings.
                                </DialogDescription>
                            </DialogHeader>

                            <Form
                                method="post"
                                action={store.url()}
                                resetOnSuccess
                                onSuccess={() => setCreateOpen(false)}
                            >
                                {({ processing, errors }) => (
                                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Name
                                            </label>
                                            <input
                                                name="name"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="Eversource Energy"
                                            />
                                            {errors.name && (
                                                <div className="text-xs text-red-600">{errors.name}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Code
                                            </label>
                                            <input
                                                name="code"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="EVER"
                                            />
                                            {errors.code && (
                                                <div className="text-xs text-red-600">{errors.code}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                State
                                            </label>
                                            <select
                                                name="state_id"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                defaultValue=""
                                            >
                                                <option value="" disabled>
                                                    Select…
                                                </option>
                                                {states.map((s) => (
                                                    <option key={s.id} value={s.id}>
                                                        {s.code} — {s.name}
                                                    </option>
                                                ))}
                                            </select>
                                            {errors.state_id && (
                                                <div className="text-xs text-red-600">{errors.state_id}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Electric UOM
                                            </label>
                                            <select
                                                name="electric_usage_uom"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                defaultValue=""
                                            >
                                                <option value="">None</option>
                                                {uoms.map((u) => (
                                                    <option key={u} value={u}>
                                                        {u}
                                                    </option>
                                                ))}
                                            </select>
                                            {errors.electric_usage_uom && (
                                                <div className="text-xs text-red-600">{errors.electric_usage_uom}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Gas UOM
                                            </label>
                                            <select
                                                name="gas_usage_uom"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                defaultValue=""
                                            >
                                                <option value="">None</option>
                                                {uoms.map((u) => (
                                                    <option key={u} value={u}>
                                                        {u}
                                                    </option>
                                                ))}
                                            </select>
                                            {errors.gas_usage_uom && (
                                                <div className="text-xs text-red-600">{errors.gas_usage_uom}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                External ID
                                            </label>
                                            <input
                                                name="external_id"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="12345"
                                            />
                                            {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}>Rate decimals</label>
                                            <input
                                                name="rate_decimal_places"
                                                type="number"
                                                min={0}
                                                max={10}
                                                className={inputClasses}
                                                placeholder="4"
                                            />
                                            {errors.rate_decimal_places && (
                                                <div className="text-xs text-red-600">
                                                    {errors.rate_decimal_places}
                                                </div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className={labelClasses}>Int Territory Code</label>
                                            <input
                                                name="internal_territory_code"
                                                type="string"
                                                className={inputClasses}
                                                placeholder=""
                                            />
                                            {errors.internal_territory_code && (
                                                <div className="text-xs text-red-600">
                                                    {errors.internal_territory_code}
                                                </div>
                                            )}
                                        </div>


                                        <div className="sm:col-span-2">
                                            <AccountIdentifierFields prefix="primary_account_identifier" label="Primary Account Identifier" errors={errors} />
                                        </div>

                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                            <label className="inline-flex items-center gap-2 text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                <input type="hidden" name="has_secondary_account_identifier" value="0" />
                                                <input type="checkbox" name="has_secondary_account_identifier" value="1" className="rounded" />
                                                Has secondary account identifier
                                            </label>
                                        </div>

                                        <div className="sm:col-span-2">
                                            <AccountIdentifierFields prefix="secondary_account_identifier" label="Secondary Account Identifier" errors={errors} />
                                        </div>

                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                            <label className="inline-flex items-center gap-2 text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                <input type="hidden" name="has_tertiary_account_identifier" value="0" />
                                                <input type="checkbox" name="has_tertiary_account_identifier" value="1" className="rounded" />
                                                Has tertiary account identifier
                                            </label>
                                        </div>

                                        <div className="sm:col-span-2">
                                            <AccountIdentifierFields prefix="tertiary_account_identifier" label="Tertiary Account Identifier" errors={errors} />
                                        </div>

                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                            <label className={labelClasses}>Bill Sample Image URL</label>
                                            <input name="bill_sample_image_url" className={inputClasses} placeholder="https://example.com/bill-sample.png" />
                                            {errors.bill_sample_image_url && (
                                                <div className="text-xs text-red-600">{errors.bill_sample_image_url}</div>
                                            )}
                                        </div>

                                        <div className="flex items-end justify-end gap-3 sm:col-span-2">
                                            <button
                                                type="button"
                                                onClick={() => setCreateOpen(false)}
                                                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"
                                            >
                                                Add utility
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                    </div>
                </div>

                {/* Utilities 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="Name" column="name" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Code" column="code" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="State" column="state_id" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Electric UOM" column="electric_usage_uom" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Gas UOM" column="gas_usage_uom" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Decimals" column="rate_decimal_places" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <th className="px-4 py-3">Zip Codes</th>
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {sorted.map((u) => (
                                        <tr key={u.id}>
                                            <td className="px-4 py-3 font-medium">{u.name}</td>
                                            <td className="px-4 py-3 font-mono text-xs">
                                                {u.code ?? '—'}
                                            </td>
                                            <td className="px-4 py-3">
                                                {u.state ? `${u.state.code} — ${u.state.name}` : '—'}
                                            </td>
                                            <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                                {u.electric_usage_uom ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                                {u.gas_usage_uom ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                                {u.rate_decimal_places ?? '—'}
                                            </td>
                                            <td className="px-4 py-3">
                                                <button
                                                    type="button"
                                                    onClick={() => setZipCodesUtilityId(u.id)}
                                                    className="inline-flex items-center rounded-md bg-zinc-100 px-2 py-1 text-xs font-medium text-zinc-700 hover:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700"
                                                >
                                                    {u.zip_codes_count} zip codes
                                                </button>
                                            </td>
                                            <td className="px-4 py-3 text-right">
                                                <div className="flex items-center justify-end gap-4">
                                                    <Dialog
                                                        open={editingId === u.id}
                                                        onOpenChange={(open) => setEditingId(open ? u.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-2xl max-h-[80vh] overflow-y-auto">
                                                            <DialogHeader>
                                                                <DialogTitle>Edit utility</DialogTitle>
                                                                <DialogDescription>
                                                                    Update {u.name} settings.
                                                                </DialogDescription>
                                                            </DialogHeader>

                                                            <Form
                                                                method="put"
                                                                action={update.url(u.id)}
                                                                onSuccess={() => setEditingId(null)}
                                                            >
                                                                {({ processing, errors }) => (
                                                                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                Name
                                                                            </label>
                                                                            <input
                                                                                name="name"
                                                                                defaultValue={u.name}
                                                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            />
                                                                            {errors.name && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.name}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex flex-col gap-1">
                                                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                Code
                                                                            </label>
                                                                            <input
                                                                                name="code"
                                                                                defaultValue={u.code ?? ''}
                                                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            />
                                                                            {errors.code && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.code}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex flex-col gap-1">
                                                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                State
                                                                            </label>
                                                                            <select
                                                                                name="state_id"
                                                                                defaultValue={u.state_id}
                                                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            >
                                                                                {states.map((s) => (
                                                                                    <option key={s.id} value={s.id}>
                                                                                        {s.code} — {s.name}
                                                                                    </option>
                                                                                ))}
                                                                            </select>
                                                                            {errors.state_id && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.state_id}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex flex-col gap-1">
                                                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                Electric UOM
                                                                            </label>
                                                                            <select
                                                                                name="electric_usage_uom"
                                                                                defaultValue={u.electric_usage_uom ?? ''}
                                                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            >
                                                                                <option value="">None</option>
                                                                                {uoms.map((uom) => (
                                                                                    <option key={uom} value={uom}>
                                                                                        {uom}
                                                                                    </option>
                                                                                ))}
                                                                            </select>
                                                                            {errors.electric_usage_uom && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.electric_usage_uom}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex flex-col gap-1">
                                                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                Gas UOM
                                                                            </label>
                                                                            <select
                                                                                name="gas_usage_uom"
                                                                                defaultValue={u.gas_usage_uom ?? ''}
                                                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            >
                                                                                <option value="">None</option>
                                                                                {uoms.map((uom) => (
                                                                                    <option key={uom} value={uom}>
                                                                                        {uom}
                                                                                    </option>
                                                                                ))}
                                                                            </select>
                                                                            {errors.gas_usage_uom && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.gas_usage_uom}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex flex-col gap-1">
                                                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                External ID
                                                                            </label>
                                                                            <input
                                                                                name="external_id"
                                                                                defaultValue={u.external_id ?? ''}
                                                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            />
                                                                            {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}>Rate decimals</label>
                                                                            <input
                                                                                name="rate_decimal_places"
                                                                                type="number"
                                                                                min={0}
                                                                                max={10}
                                                                                defaultValue={u.rate_decimal_places ?? ''}
                                                                                className={inputClasses}
                                                                            />
                                                                            {errors.rate_decimal_places && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.rate_decimal_places}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex flex-col gap-1">
                                                                            <label className={labelClasses}>Int Territory Code</label>
                                                                            <input
                                                                                name="internal_territory_code"
                                                                                type="string"
                                                                                className={inputClasses}
                                                                                placeholder=""
                                                                                defaultValue={u.internal_territory_code ?? ''}
                                                                            />
                                                                            {errors.internal_territory_code && (
                                                                                <div className="text-xs text-red-600">
                                                                                    {errors.internal_territory_code}
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <div className="sm:col-span-2">
                                                                            <AccountIdentifierFields
                                                                                prefix="primary_account_identifier"
                                                                                label="Primary Account Identifier"
                                                                                defaults={{
                                                                                    name: u.primary_account_identifier_name,
                                                                                    example: u.primary_account_identifier_example,
                                                                                    regex: u.primary_account_identifier_regex,
                                                                                    help_text: u.primary_account_identifier_help_text,
                                                                                }}
                                                                                errors={errors}
                                                                            />
                                                                        </div>

                                                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                                                            <label className="inline-flex items-center gap-2 text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                <input type="hidden" name="has_secondary_account_identifier" value="0" />
                                                                                <input type="checkbox" name="has_secondary_account_identifier" value="1" defaultChecked={u.has_secondary_account_identifier} className="rounded" />
                                                                                Has secondary account identifier
                                                                            </label>
                                                                        </div>

                                                                        <div className="sm:col-span-2">
                                                                            <AccountIdentifierFields
                                                                                prefix="secondary_account_identifier"
                                                                                label="Secondary Account Identifier"
                                                                                defaults={{
                                                                                    name: u.secondary_account_identifier_name,
                                                                                    example: u.secondary_account_identifier_example,
                                                                                    regex: u.secondary_account_identifier_regex,
                                                                                    help_text: u.secondary_account_identifier_help_text,
                                                                                }}
                                                                                errors={errors}
                                                                            />
                                                                        </div>

                                                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                                                            <label className="inline-flex items-center gap-2 text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                                <input type="hidden" name="has_tertiary_account_identifier" value="0" />
                                                                                <input type="checkbox" name="has_tertiary_account_identifier" value="1" defaultChecked={u.has_tertiary_account_identifier} className="rounded" />
                                                                                Has tertiary account identifier
                                                                            </label>
                                                                        </div>

                                                                        <div className="sm:col-span-2">
                                                                            <AccountIdentifierFields
                                                                                prefix="tertiary_account_identifier"
                                                                                label="Tertiary Account Identifier"
                                                                                defaults={{
                                                                                    name: u.tertiary_account_identifier_name,
                                                                                    example: u.tertiary_account_identifier_example,
                                                                                    regex: u.tertiary_account_identifier_regex,
                                                                                    help_text: u.tertiary_account_identifier_help_text,
                                                                                }}
                                                                                errors={errors}
                                                                            />
                                                                        </div>

                                                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                                                            <label className={labelClasses}>Bill Sample Image URL</label>
                                                                            <input name="bill_sample_image_url" defaultValue={u.bill_sample_image_url ?? ''} className={inputClasses} />
                                                                            {errors.bill_sample_image_url && (
                                                                                <div className="text-xs text-red-600">{errors.bill_sample_image_url}</div>
                                                                            )}
                                                                        </div>

                                                                        <div className="flex items-end justify-end gap-3 sm:col-span-2">
                                                                            <button
                                                                                type="button"
                                                                                onClick={() => setEditingId(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="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"
                                                                            >
                                                                                Save
                                                                            </button>
                                                                        </div>
                                                                    </div>
                                                                )}
                                                            </Form>
                                                        </DialogContent>
                                                    </Dialog>

                                                    <Form method="delete" action={destroy.url(u.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>

                    {utilities.length === 0 && (
                        <div className="p-4 text-sm text-zinc-600 dark:text-zinc-400">
                            No utilities yet.
                        </div>
                    )}
                </div>
            </div>

            <ZipCodeModal
                utility={zipCodesUtility}
                open={zipCodesUtilityId !== null}
                onOpenChange={(open) => {
                    if (!open) setZipCodesUtilityId(null);
                }}
            />
        </AppLayout>
    );
}

