import { Form, Head, Link } from '@inertiajs/react';
import { useState } from 'react';
import {
    BadgeCheck,
    ClipboardList,
    DollarSign,
    Info,
    Leaf,
    MapPin,
    PanelTop,
    PlugZap,
    ShieldCheck,
    StickyNote,
    Users,
} from 'lucide-react';
import JobController from '@/actions/App/Http/Controllers/JobController';
import {
    CustomerSiteFields,
    type CustomerOption,
} from '@/components/crm/customer-site-fields';
import { EquipmentFields } from '@/components/crm/equipment-fields';
import { JobPartsPanel } from '@/components/crm/job-parts-panel';
import { Callout, PageHeader, SectionCard } from '@/components/crm/page-header';
import { FormField, NativeSelect } from '@/components/crm/native-select';
import { RuleFlag } from '@/components/crm/status-badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    formatDate,
    toDateInputValue,
    toDateTimeInputValue,
} from '@/lib/format';
import { show as customerShow } from '@/routes/customers';
import { index as jobsIndex, show as jobShow } from '@/routes/jobs';
import type { JobDetail, OptionsBundle } from '@/types';

type Props = {
    job: JobDetail;
    options: OptionsBundle;
    customers: CustomerOption[];
    can: {
        viewFinancials: boolean;
        manageCompliance: boolean;
    };
};

const textareaClassName =
    'border-input dark:bg-input/30 min-h-24 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';

/**
 * A boolean field that always submits a value. Inertia's Form reads plain form
 * values, and Laravel's `boolean` rule rejects a bare "on", so the hidden input
 * supplies "0" when the box is unchecked.
 */
function CheckboxField({
    label,
    name,
    defaultChecked,
    hint,
    error,
}: {
    label: string;
    name: string;
    defaultChecked: boolean;
    hint?: string | null;
    error?: string;
}) {
    return (
        <div className="grid gap-1">
            <label className="flex items-start gap-2 text-sm">
                <input type="hidden" name={name} value="0" />
                <input
                    type="checkbox"
                    name={name}
                    value="1"
                    defaultChecked={defaultChecked}
                    className="border-input mt-0.5 size-4 shrink-0 rounded border"
                />
                <span>
                    {label}
                    {hint ? (
                        <span className="text-muted-foreground block text-xs">
                            {hint}
                        </span>
                    ) : null}
                </span>
            </label>
            {error ? (
                <p className="text-destructive text-xs">{error}</p>
            ) : null}
        </div>
    );
}

export default function JobsEdit({ job, options, customers, can }: Props) {
    // The job's own customer and site are already chosen; their sites arrive
    // with the pinned customer, and any other customer is found by searching.
    const [customerId, setCustomerId] = useState<number | null>(
        () => job.customer?.id ?? null,
    );
    const [siteId, setSiteId] = useState<number | null>(
        () => job.site?.id ?? null,
    );

    return (
        <>
            <Head title={`Edit ${job.job_number}`} />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <span className="font-mono">{job.job_number}</span>
                            <span aria-hidden className="text-muted-foreground/50">
                                ·
                            </span>
                            <span>{job.customer?.name ?? 'No customer'}</span>
                        </>
                    }
                    title={`Edit ${job.job_number}`}
                    description={job.customer?.name ?? null}
                    actions={
                        <>
                            <Button variant="outline" size="sm" asChild>
                                <Link href={jobShow(job.id)}>
                                    Back to job
                                </Link>
                            </Button>
                            <Button variant="ghost" size="sm" asChild>
                                <Link href={jobsIndex()}>All jobs</Link>
                            </Button>
                        </>
                    }
                />

                <Callout
                    tone="info"
                    icon={Info}
                    title="Installation status is not edited here"
                >
                    This form only changes the job's details. To move the job
                    through the pipeline — installing it, inspection, grid
                    connection and closeout — use the workflow controls on the{' '}
                    <Link
                        href={jobShow(job.id)}
                        className="font-medium underline"
                    >
                        job page
                    </Link>
                    . Current stage: <strong>{job.status.label}</strong>.
                </Callout>

                <Form
                    {...JobController.update.form({ job: job.id })}
                    className="flex flex-col gap-5"
                >
                    {({ processing, errors }) => (
                        <>
                            <SectionCard
                                title="Customer and site"
                                icon={MapPin}
                                tone="solar"
                                description="Changing the site changes which distribution network rules apply."
                            >
                                <CustomerSiteFields
                                    customers={customers}
                                    customerId={customerId}
                                    siteId={siteId}
                                    onChange={(nextCustomer, nextSite) => {
                                        setCustomerId(nextCustomer);
                                        setSiteId(nextSite);
                                    }}
                                    errors={{
                                        customer_id: errors.customer_id,
                                        site_id: errors.site_id,
                                    }}
                                    customerFooter={
                                        job.customer ? (
                                            <Link
                                                href={customerShow(
                                                    job.customer.id,
                                                )}
                                                className="text-muted-foreground text-xs underline"
                                            >
                                                Open the customer record
                                            </Link>
                                        ) : null
                                    }
                                />
                            </SectionCard>

                            <SectionCard
                                title="Job details"
                                icon={ClipboardList}
                                tone="slate"
                            >
                                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                    <FormField
                                        label="Job type"
                                        htmlFor="type"
                                        error={errors.type}
                                        required
                                    >
                                        <NativeSelect
                                            id="type"
                                            name="type"
                                            defaultValue={job.type.value}
                                        >
                                            {options.jobTypes.map((type) => (
                                                <option
                                                    key={type.value}
                                                    value={type.value}
                                                >
                                                    {type.label}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="Priority"
                                        htmlFor="priority"
                                        error={errors.priority}
                                        required
                                    >
                                        <NativeSelect
                                            id="priority"
                                            name="priority"
                                            defaultValue={job.priority.value}
                                        >
                                            {options.priorities.map(
                                                (priority) => (
                                                    <option
                                                        key={priority.value}
                                                        value={priority.value}
                                                    >
                                                        {priority.label}
                                                    </option>
                                                ),
                                            )}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="Sold on"
                                        htmlFor="sold_on"
                                        error={errors.sold_on}
                                    >
                                        <Input
                                            id="sold_on"
                                            name="sold_on"
                                            type="date"
                                            defaultValue={toDateInputValue(
                                                job.dates.sold_on,
                                            )}
                                        />
                                    </FormField>

                                    <FormField
                                        label="Title"
                                        htmlFor="title"
                                        error={errors.title}
                                        className="md:col-span-2"
                                    >
                                        <Input
                                            id="title"
                                            name="title"
                                            defaultValue={job.title ?? ''}
                                        />
                                    </FormField>

                                    <FormField
                                        label="Install date booked for"
                                        htmlFor="install_scheduled_for"
                                        error={errors.install_scheduled_for}
                                    >
                                        <Input
                                            id="install_scheduled_for"
                                            name="install_scheduled_for"
                                            type="date"
                                            defaultValue={toDateInputValue(
                                                job.dates
                                                    .install_scheduled_for,
                                            )}
                                        />
                                    </FormField>

                                    <FormField
                                        label="Description / scope"
                                        htmlFor="description"
                                        error={errors.description}
                                        className="md:col-span-2 lg:col-span-3"
                                    >
                                        <textarea
                                            id="description"
                                            name="description"
                                            className={textareaClassName}
                                            defaultValue={
                                                job.description ?? ''
                                            }
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Team"
                                icon={Users}
                                tone="indigo"
                            >
                                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                    <FormField
                                        label="Account owner"
                                        htmlFor="owner_id"
                                        error={errors.owner_id}
                                    >
                                        <NativeSelect
                                            id="owner_id"
                                            name="owner_id"
                                            defaultValue={
                                                job.owner
                                                    ? String(job.owner.id)
                                                    : ''
                                            }
                                        >
                                            <option value="">
                                                Unassigned
                                            </option>
                                            {options.staff.map((member) => (
                                                <option
                                                    key={member.value}
                                                    value={String(member.value)}
                                                >
                                                    {member.label}
                                                    {member.role
                                                        ? ` — ${member.role}`
                                                        : ''}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="Sales representative"
                                        htmlFor="sales_rep_id"
                                        error={errors.sales_rep_id}
                                    >
                                        <NativeSelect
                                            id="sales_rep_id"
                                            name="sales_rep_id"
                                            defaultValue={
                                                job.sales_rep
                                                    ? String(job.sales_rep.id)
                                                    : ''
                                            }
                                        >
                                            <option value="">
                                                Unassigned
                                            </option>
                                            {options.staff.map((member) => (
                                                <option
                                                    key={member.value}
                                                    value={String(member.value)}
                                                >
                                                    {member.label}
                                                    {member.role
                                                        ? ` — ${member.role}`
                                                        : ''}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="Operations manager"
                                        htmlFor="operations_manager_id"
                                        error={errors.operations_manager_id}
                                    >
                                        <NativeSelect
                                            id="operations_manager_id"
                                            name="operations_manager_id"
                                            defaultValue={
                                                job.operations_manager
                                                    ? String(
                                                          job
                                                              .operations_manager
                                                              .id,
                                                      )
                                                    : ''
                                            }
                                        >
                                            <option value="">
                                                Unassigned
                                            </option>
                                            {options.staff.map((member) => (
                                                <option
                                                    key={member.value}
                                                    value={String(member.value)}
                                                >
                                                    {member.label}
                                                    {member.role
                                                        ? ` — ${member.role}`
                                                        : ''}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="Installer"
                                        htmlFor="installer_id"
                                        error={errors.installer_id}
                                    >
                                        <NativeSelect
                                            id="installer_id"
                                            name="installer_id"
                                            defaultValue={
                                                job.installer
                                                    ? String(job.installer.id)
                                                    : ''
                                            }
                                        >
                                            <option value="">
                                                Unassigned
                                            </option>
                                            {options.staff.map((member) => (
                                                <option
                                                    key={member.value}
                                                    value={String(member.value)}
                                                >
                                                    {member.label}
                                                    {member.role
                                                        ? ` — ${member.role}`
                                                        : ''}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>
                                </div>
                            </SectionCard>

                            {can.viewFinancials ? (
                                <SectionCard
                                    title="Commercials"
                                    icon={DollarSign}
                                    tone="success"
                                    description="Visible only to staff with financial access."
                                >
                                    <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                        <FormField
                                            label="Contract value (AUD)"
                                            htmlFor="contract_value"
                                            error={errors.contract_value}
                                        >
                                            <Input
                                                id="contract_value"
                                                name="contract_value"
                                                type="number"
                                                step="0.01"
                                                min="0"
                                                defaultValue={
                                                    job.financials
                                                        ?.contract_value ?? ''
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Deposit (AUD)"
                                            htmlFor="deposit_amount"
                                            error={errors.deposit_amount}
                                        >
                                            <Input
                                                id="deposit_amount"
                                                name="deposit_amount"
                                                type="number"
                                                step="0.01"
                                                min="0"
                                                defaultValue={
                                                    job.financials
                                                        ?.deposit_amount ?? ''
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Finance provider"
                                            htmlFor="finance_provider"
                                            error={errors.finance_provider}
                                        >
                                            <Input
                                                id="finance_provider"
                                                name="finance_provider"
                                                defaultValue={
                                                    job.financials
                                                        ?.finance_provider ??
                                                    ''
                                                }
                                            />
                                        </FormField>

                                        <FormField
                                            label="Finance term (months)"
                                            htmlFor="finance_term_months"
                                            error={errors.finance_term_months}
                                        >
                                            <Input
                                                id="finance_term_months"
                                                name="finance_term_months"
                                                type="number"
                                                min="1"
                                                max="240"
                                                defaultValue={
                                                    job.financials
                                                        ?.finance_term_months ??
                                                    ''
                                                }
                                            />
                                        </FormField>
                                    </div>
                                </SectionCard>
                            ) : null}

                            <SectionCard
                                title="System"
                                icon={PanelTop}
                                tone="solar"
                            >
                                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                    <FormField
                                        label="Installation type"
                                        htmlFor="installation_config"
                                        error={errors.installation_config}
                                        hint="Decides whether battery isolation and a battery inverter belong on the parts list."
                                    >
                                        <NativeSelect
                                            id="installation_config"
                                            name="installation_config"
                                            defaultValue={
                                                job.system.installation_config
                                                    .value
                                            }
                                        >
                                            {options.installationConfigs.map(
                                                (config) => (
                                                    <option
                                                        key={config.value}
                                                        value={config.value}
                                                    >
                                                        {config.label}
                                                    </option>
                                                ),
                                            )}
                                        </NativeSelect>
                                    </FormField>

                                    <FormField
                                        label="System size (kW)"
                                        htmlFor="system_size_kw"
                                        error={errors.system_size_kw}
                                    >
                                        <Input
                                            id="system_size_kw"
                                            name="system_size_kw"
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            defaultValue={
                                                job.system.system_size_kw ?? ''
                                            }
                                        />
                                    </FormField>

                                    <FormField
                                        label="Panel count"
                                        htmlFor="panel_count"
                                        error={errors.panel_count}
                                    >
                                        <Input
                                            id="panel_count"
                                            name="panel_count"
                                            type="number"
                                            min="0"
                                            defaultValue={
                                                job.system.panel_count ?? ''
                                            }
                                        />
                                    </FormField>

                                    <EquipmentFields
                                        kind="panel"
                                        label="Panel"
                                        makeName="panel_make"
                                        modelName="panel_model"
                                        defaultMake={job.system.panel_make ?? ''}
                                        defaultModel={job.system.panel_model ?? ''}
                                        makeError={errors.panel_make}
                                        modelError={errors.panel_model}
                                    />

                                    <FormField
                                        label="Panel wattage (W)"
                                        htmlFor="panel_wattage"
                                        error={errors.panel_wattage}
                                        hint="Used with the system size to work out the panel count."
                                    >
                                        <Input
                                            id="panel_wattage"
                                            name="panel_wattage"
                                            type="number"
                                            min="50"
                                            max="1500"
                                            step="5"
                                            defaultValue={
                                                job.system.panel_wattage ?? ''
                                            }
                                        />
                                    </FormField>

                                    <FormField
                                        label="Strings"
                                        htmlFor="string_count"
                                        error={errors.string_count}
                                        hint="Optional. The number of DC strings, for connectors and isolation."
                                    >
                                        <Input
                                            id="string_count"
                                            name="string_count"
                                            type="number"
                                            min="1"
                                            max="100"
                                            defaultValue={
                                                job.system.string_count ?? ''
                                            }
                                        />
                                    </FormField>

                                    <EquipmentFields
                                        kind="inverter"
                                        label="Inverter"
                                        makeName="inverter_make"
                                        modelName="inverter_model"
                                        defaultMake={
                                            job.system.inverter_make ?? ''
                                        }
                                        defaultModel={
                                            job.system.inverter_model ?? ''
                                        }
                                        makeError={errors.inverter_make}
                                        modelError={errors.inverter_model}
                                    />

                                    <FormField
                                        label="Inverter serial"
                                        htmlFor="inverter_serial"
                                        error={errors.inverter_serial}
                                        hint="Required as STC evidence after installation."
                                    >
                                        <Input
                                            id="inverter_serial"
                                            name="inverter_serial"
                                            defaultValue={
                                                job.system.inverter_serial ?? ''
                                            }
                                        />
                                    </FormField>

                                    <FormField
                                        label="Inverter capacity (kW)"
                                        htmlFor="inverter_capacity_kw"
                                        error={errors.inverter_capacity_kw}
                                    >
                                        <Input
                                            id="inverter_capacity_kw"
                                            name="inverter_capacity_kw"
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            defaultValue={
                                                job.system
                                                    .inverter_capacity_kw ?? ''
                                            }
                                        />
                                    </FormField>

                                    <EquipmentFields
                                        kind="battery"
                                        label="Battery"
                                        makeName="battery_make"
                                        modelName="battery_model"
                                        defaultMake={job.system.battery_make ?? ''}
                                        defaultModel={
                                            job.system.battery_model ?? ''
                                        }
                                        makeError={errors.battery_make}
                                        modelError={errors.battery_model}
                                    />

                                    <FormField
                                        label="Battery capacity (kWh)"
                                        htmlFor="battery_capacity_kwh"
                                        error={errors.battery_capacity_kwh}
                                    >
                                        <Input
                                            id="battery_capacity_kwh"
                                            name="battery_capacity_kwh"
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            defaultValue={
                                                job.system
                                                    .battery_capacity_kwh ?? ''
                                            }
                                        />
                                    </FormField>

                                    <FormField
                                        label="Export limit (kW)"
                                        htmlFor="export_limit_kw"
                                        error={errors.export_limit_kw}
                                    >
                                        <Input
                                            id="export_limit_kw"
                                            name="export_limit_kw"
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            defaultValue={
                                                job.system.export_limit_kw ?? ''
                                            }
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Installation parts"
                                description="Draft the list from this design, then edit it before saving."
                                icon={ClipboardList}
                                tone="slate"
                            >
                                <JobPartsPanel initial={job.parts} />
                            </SectionCard>

                            {can.manageCompliance ? (
                                <>
                                    <SectionCard
                                        title="Grid connection"
                                        icon={PlugZap}
                                        tone="info"
                                        description="Pre-approval and final closeout are separate steps. Pre-approval is required before the system may be installed."
                                    >
                                        <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                            <FormField
                                                label="Connection status"
                                                htmlFor="grid_connection_status"
                                                error={
                                                    errors.grid_connection_status
                                                }
                                            >
                                                <NativeSelect
                                                    id="grid_connection_status"
                                                    name="grid_connection_status"
                                                    defaultValue={
                                                        job.grid?.status.value ??
                                                        'not_started'
                                                    }
                                                >
                                                    {options.gridConnectionStatuses.map(
                                                        (status) => (
                                                            <option
                                                                key={
                                                                    status.value
                                                                }
                                                                value={
                                                                    status.value
                                                                }
                                                            >
                                                                {status.label}
                                                            </option>
                                                        ),
                                                    )}
                                                </NativeSelect>
                                            </FormField>

                                            <FormField
                                                label="Application reference"
                                                htmlFor="grid_application_reference"
                                                error={
                                                    errors.grid_application_reference
                                                }
                                            >
                                                <Input
                                                    id="grid_application_reference"
                                                    name="grid_application_reference"
                                                    defaultValue={
                                                        job.grid
                                                            ?.application_reference ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Lodged with network"
                                                htmlFor="grid_application_submitted_at"
                                                error={
                                                    errors.grid_application_submitted_at
                                                }
                                            >
                                                <Input
                                                    id="grid_application_submitted_at"
                                                    name="grid_application_submitted_at"
                                                    type="datetime-local"
                                                    defaultValue={toDateTimeInputValue(
                                                        job.grid
                                                            ?.application_submitted_at ??
                                                            null,
                                                    )}
                                                />
                                            </FormField>

                                            <FormField
                                                label="Approved at"
                                                htmlFor="grid_approved_at"
                                                error={errors.grid_approved_at}
                                            >
                                                <Input
                                                    id="grid_approved_at"
                                                    name="grid_approved_at"
                                                    type="datetime-local"
                                                    defaultValue={toDateTimeInputValue(
                                                        job.grid?.approved_at ??
                                                            null,
                                                    )}
                                                />
                                            </FormField>

                                            <FormField
                                                label="Approval expires on"
                                                htmlFor="grid_approval_expires_on"
                                                error={
                                                    errors.grid_approval_expires_on
                                                }
                                            >
                                                <Input
                                                    id="grid_approval_expires_on"
                                                    name="grid_approval_expires_on"
                                                    type="date"
                                                    defaultValue={toDateInputValue(
                                                        job.grid
                                                            ?.approval_expires_on ??
                                                            null,
                                                    )}
                                                />
                                            </FormField>

                                            <FormField
                                                label="Approved export limit (kW)"
                                                htmlFor="approved_export_limit_kw"
                                                error={
                                                    errors.approved_export_limit_kw
                                                }
                                            >
                                                <Input
                                                    id="approved_export_limit_kw"
                                                    name="approved_export_limit_kw"
                                                    type="number"
                                                    step="0.01"
                                                    min="0"
                                                    defaultValue={
                                                        job.grid
                                                            ?.approved_export_limit_kw ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Meter type"
                                                htmlFor="meter_type"
                                                error={errors.meter_type}
                                            >
                                                <Input
                                                    id="meter_type"
                                                    name="meter_type"
                                                    defaultValue={
                                                        job.grid?.meter_type ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Meter serial"
                                                htmlFor="meter_serial"
                                                error={errors.meter_serial}
                                            >
                                                <Input
                                                    id="meter_serial"
                                                    name="meter_serial"
                                                    defaultValue={
                                                        job.grid?.meter_serial ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Meter installed at"
                                                htmlFor="meter_installed_at"
                                                error={
                                                    errors.meter_installed_at
                                                }
                                            >
                                                <Input
                                                    id="meter_installed_at"
                                                    name="meter_installed_at"
                                                    type="datetime-local"
                                                    defaultValue={toDateTimeInputValue(
                                                        job.grid
                                                            ?.meter_installed_at ??
                                                            null,
                                                    )}
                                                />
                                            </FormField>

                                            <FormField
                                                label="Network conditions"
                                                htmlFor="grid_conditions"
                                                error={errors.grid_conditions}
                                                className="md:col-span-2 lg:col-span-3"
                                            >
                                                <textarea
                                                    id="grid_conditions"
                                                    name="grid_conditions"
                                                    className={
                                                        textareaClassName
                                                    }
                                                    defaultValue={
                                                        job.grid?.conditions ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <div className="md:col-span-2 lg:col-span-3">
                                                <CheckboxField
                                                    label="Export enabled through the meter"
                                                    name="export_enabled"
                                                    defaultChecked={
                                                        job.grid
                                                            ?.export_enabled ??
                                                        false
                                                    }
                                                    error={
                                                        errors.export_enabled
                                                    }
                                                />
                                            </div>
                                        </div>
                                    </SectionCard>

                                    <SectionCard
                                        title="Electrical inspection and certificate"
                                        icon={ShieldCheck}
                                        tone="warning"
                                        description={
                                            job.inspection?.required_by_state
                                                ? `${job.inspection.authority ?? 'An independent inspector'} must pass this installation before it can be energised.`
                                                : 'Record the inspection outcome and the electrical certificate for this installation.'
                                        }
                                    >
                                        {job.inspection?.required_by_state ? (
                                            <div className="mb-4">
                                                <RuleFlag tone="warning">
                                                    Inspection mandatory in this
                                                    state
                                                </RuleFlag>
                                            </div>
                                        ) : null}
                                        <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                            <div className="md:col-span-2 lg:col-span-3">
                                                <CheckboxField
                                                    label="Requires an independent electrical inspection"
                                                    name="requires_electrical_inspection"
                                                    hint={
                                                        job.inspection
                                                            ?.required_by_state
                                                            ? 'Automatically required because of the state this system is installed in.'
                                                            : 'Turn this on if the network or the work type requires an independent inspection.'
                                                    }
                                                    defaultChecked={
                                                        job.inspection
                                                            ?.required ??
                                                        false
                                                    }
                                                    error={
                                                        errors.requires_electrical_inspection
                                                    }
                                                />
                                            </div>

                                            <FormField
                                                label="Inspection status"
                                                htmlFor="inspection_status"
                                                error={errors.inspection_status}
                                            >
                                                <NativeSelect
                                                    id="inspection_status"
                                                    name="inspection_status"
                                                    defaultValue={
                                                        job.inspection?.status
                                                            .value ??
                                                        'not_required'
                                                    }
                                                >
                                                    {options.inspectionStatuses.map(
                                                        (status) => (
                                                            <option
                                                                key={
                                                                    status.value
                                                                }
                                                                value={
                                                                    status.value
                                                                }
                                                            >
                                                                {status.label}
                                                            </option>
                                                        ),
                                                    )}
                                                </NativeSelect>
                                            </FormField>

                                            <FormField
                                                label="Inspection booked for"
                                                htmlFor="inspection_booked_for"
                                                error={
                                                    errors.inspection_booked_for
                                                }
                                            >
                                                <Input
                                                    id="inspection_booked_for"
                                                    name="inspection_booked_for"
                                                    type="datetime-local"
                                                    defaultValue={toDateTimeInputValue(
                                                        job.inspection
                                                            ?.booked_for ??
                                                            null,
                                                    )}
                                                />
                                            </FormField>

                                            <FormField
                                                label="Inspector name"
                                                htmlFor="electrical_inspector_name"
                                                error={
                                                    errors.electrical_inspector_name
                                                }
                                            >
                                                <Input
                                                    id="electrical_inspector_name"
                                                    name="electrical_inspector_name"
                                                    defaultValue={
                                                        job.inspection
                                                            ?.inspector_name ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Inspector licence number"
                                                htmlFor="electrical_inspector_licence"
                                                error={
                                                    errors.electrical_inspector_licence
                                                }
                                                hint="Required before an inspection can be recorded as passed."
                                            >
                                                <Input
                                                    id="electrical_inspector_licence"
                                                    name="electrical_inspector_licence"
                                                    defaultValue={
                                                        job.inspection
                                                            ?.inspector_licence ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Certificate type"
                                                htmlFor="certificate_type"
                                                error={errors.certificate_type}
                                                hint={
                                                    job.state_compliance
                                                        ?.certificate_name ??
                                                    null
                                                }
                                            >
                                                <Input
                                                    id="certificate_type"
                                                    name="certificate_type"
                                                    defaultValue={
                                                        job.inspection
                                                            ?.certificate
                                                            .type ?? ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Certificate number"
                                                htmlFor="certificate_number"
                                                error={
                                                    errors.certificate_number
                                                }
                                            >
                                                <Input
                                                    id="certificate_number"
                                                    name="certificate_number"
                                                    defaultValue={
                                                        job.inspection
                                                            ?.certificate
                                                            .number ?? ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Certificate issued at"
                                                htmlFor="certificate_issued_at"
                                                error={
                                                    errors.certificate_issued_at
                                                }
                                            >
                                                <Input
                                                    id="certificate_issued_at"
                                                    name="certificate_issued_at"
                                                    type="datetime-local"
                                                    defaultValue={toDateTimeInputValue(
                                                        job.inspection
                                                            ?.certificate
                                                            .issued_at ?? null,
                                                    )}
                                                />
                                            </FormField>

                                            <FormField
                                                label="Electrical licence number"
                                                htmlFor="electrical_licence_number"
                                                error={
                                                    errors.electrical_licence_number
                                                }
                                            >
                                                <Input
                                                    id="electrical_licence_number"
                                                    name="electrical_licence_number"
                                                    defaultValue={
                                                        job.credentials
                                                            .electrical_licence_number ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Defects raised"
                                                htmlFor="inspection_defects"
                                                error={
                                                    errors.inspection_defects
                                                }
                                                className="md:col-span-2"
                                            >
                                                <textarea
                                                    id="inspection_defects"
                                                    name="inspection_defects"
                                                    className={
                                                        textareaClassName
                                                    }
                                                    defaultValue={
                                                        job.inspection
                                                            ?.defects ?? ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Inspection notes"
                                                htmlFor="inspection_notes"
                                                error={errors.inspection_notes}
                                                className="md:col-span-2 lg:col-span-3"
                                            >
                                                <textarea
                                                    id="inspection_notes"
                                                    name="inspection_notes"
                                                    className={
                                                        textareaClassName
                                                    }
                                                    defaultValue={
                                                        job.inspection?.notes ??
                                                        ''
                                                    }
                                                />
                                            </FormField>
                                        </div>
                                    </SectionCard>

                                    <SectionCard
                                        title="STCs and rebates"
                                        icon={Leaf}
                                        tone="success"
                                        description="STCs are created in the Clean Energy Regulator's REC Registry after installation and must be claimed within 12 months."
                                    >
                                        {job.solar_victoria?.applies ? (
                                            <div className="mb-4 flex flex-wrap gap-2">
                                                <RuleFlag tone="violet">
                                                    {job.solar_victoria
                                                        .program ??
                                                        'State rebate program'}
                                                </RuleFlag>
                                                {job.solar_victoria
                                                    .has_sampled_audit ? (
                                                    <RuleFlag tone="amber">
                                                        Sample audit program
                                                        applies to selected
                                                        jobs
                                                    </RuleFlag>
                                                ) : null}
                                            </div>
                                        ) : null}
                                        <div className="grid gap-x-6 gap-y-4 md:grid-cols-2 lg:grid-cols-3">
                                            <div className="md:col-span-2 lg:col-span-3">
                                                <CheckboxField
                                                    label="Eligible for STCs"
                                                    name="stc_eligible"
                                                    defaultChecked={
                                                        job.stc?.eligible ??
                                                        false
                                                    }
                                                    error={errors.stc_eligible}
                                                />
                                            </div>

                                            <FormField
                                                label="STC quantity"
                                                htmlFor="stc_quantity"
                                                error={errors.stc_quantity}
                                            >
                                                <Input
                                                    id="stc_quantity"
                                                    name="stc_quantity"
                                                    type="number"
                                                    min="0"
                                                    defaultValue={
                                                        job.stc?.quantity ?? ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Zone rating"
                                                htmlFor="stc_zone_rating"
                                                error={errors.stc_zone_rating}
                                            >
                                                <Input
                                                    id="stc_zone_rating"
                                                    name="stc_zone_rating"
                                                    type="number"
                                                    min="1"
                                                    max="6"
                                                    defaultValue={
                                                        job.stc?.zone_rating ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Claim status"
                                                htmlFor="stc_claim_status"
                                                error={errors.stc_claim_status}
                                            >
                                                <NativeSelect
                                                    id="stc_claim_status"
                                                    name="stc_claim_status"
                                                    defaultValue={
                                                        job.stc?.status.value ??
                                                        'pending'
                                                    }
                                                >
                                                    {options.stcClaimStatuses.map(
                                                        (status) => (
                                                            <option
                                                                key={
                                                                    status.value
                                                                }
                                                                value={
                                                                    status.value
                                                                }
                                                            >
                                                                {status.label}
                                                            </option>
                                                        ),
                                                    )}
                                                </NativeSelect>
                                            </FormField>

                                            <FormField
                                                label="STC agent"
                                                htmlFor="stc_agent"
                                                error={errors.stc_agent}
                                            >
                                                <Input
                                                    id="stc_agent"
                                                    name="stc_agent"
                                                    defaultValue={
                                                        job.stc?.agent ?? ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Registered at"
                                                htmlFor="stc_registered_at"
                                                error={errors.stc_registered_at}
                                            >
                                                <Input
                                                    id="stc_registered_at"
                                                    name="stc_registered_at"
                                                    type="datetime-local"
                                                    defaultValue={toDateTimeInputValue(
                                                        job.stc
                                                            ?.registered_at ??
                                                            null,
                                                    )}
                                                />
                                            </FormField>

                                            <div className="md:col-span-2 lg:col-span-3">
                                                <CheckboxField
                                                    label="Customer has signed the STC assignment form"
                                                    name="stc_assignment_signed"
                                                    hint="The job cannot be completed without this."
                                                    defaultChecked={
                                                        job.stc
                                                            ?.assignment_signed ??
                                                        false
                                                    }
                                                    error={
                                                        errors.stc_assignment_signed
                                                    }
                                                />
                                            </div>

                                            <FormField
                                                label="State rebate application reference"
                                                htmlFor="solar_victoria_application_ref"
                                                error={
                                                    errors.solar_victoria_application_ref
                                                }
                                            >
                                                <Input
                                                    id="solar_victoria_application_ref"
                                                    name="solar_victoria_application_ref"
                                                    defaultValue={
                                                        job.solar_victoria
                                                            ?.application_ref ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="Rebate amount (AUD)"
                                                htmlFor="solar_victoria_rebate_amount"
                                                error={
                                                    errors.solar_victoria_rebate_amount
                                                }
                                            >
                                                <Input
                                                    id="solar_victoria_rebate_amount"
                                                    name="solar_victoria_rebate_amount"
                                                    type="number"
                                                    step="0.01"
                                                    min="0"
                                                    defaultValue={
                                                        job.solar_victoria
                                                            ?.rebate_amount ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="State audit status"
                                                htmlFor="solar_victoria_audit_status"
                                                error={
                                                    errors.solar_victoria_audit_status
                                                }
                                                hint="Only applies if this job was selected for a program audit."
                                            >
                                                <Input
                                                    id="solar_victoria_audit_status"
                                                    name="solar_victoria_audit_status"
                                                    defaultValue={
                                                        job.solar_victoria
                                                            ?.audit_status ?? ''
                                                    }
                                                />
                                            </FormField>

                                            <div className="md:col-span-2 lg:col-span-3">
                                                <CheckboxField
                                                    label="Selected for a state program audit"
                                                    name="solar_victoria_audit_selected"
                                                    defaultChecked={
                                                        job.solar_victoria
                                                            ?.audit_selected ??
                                                        false
                                                    }
                                                    error={
                                                        errors.solar_victoria_audit_selected
                                                    }
                                                />
                                            </div>
                                        </div>
                                    </SectionCard>

                                    <SectionCard
                                        title="Accreditation"
                                        icon={BadgeCheck}
                                        tone="indigo"
                                        description="Solar Accreditation Australia numbers for the people who designed and installed this system."
                                    >
                                        <div className="grid gap-x-6 gap-y-4 md:grid-cols-2">
                                            <FormField
                                                label="SAA installer number"
                                                htmlFor="saa_installer_number"
                                                error={
                                                    errors.saa_installer_number
                                                }
                                            >
                                                <Input
                                                    id="saa_installer_number"
                                                    name="saa_installer_number"
                                                    defaultValue={
                                                        job.credentials
                                                            .saa_installer_number ??
                                                        ''
                                                    }
                                                />
                                            </FormField>

                                            <FormField
                                                label="SAA designer number"
                                                htmlFor="saa_designer_number"
                                                error={
                                                    errors.saa_designer_number
                                                }
                                            >
                                                <Input
                                                    id="saa_designer_number"
                                                    name="saa_designer_number"
                                                    defaultValue={
                                                        job.credentials
                                                            .saa_designer_number ??
                                                        ''
                                                    }
                                                />
                                            </FormField>
                                        </div>
                                    </SectionCard>
                                </>
                            ) : null}

                            <SectionCard
                                title="Notes"
                                icon={StickyNote}
                                tone="slate"
                            >
                                <div className="grid gap-x-6 gap-y-4 md:grid-cols-2">
                                    <FormField
                                        label="Customer notes"
                                        htmlFor="notes"
                                        error={errors.notes}
                                    >
                                        <textarea
                                            id="notes"
                                            name="notes"
                                            className={textareaClassName}
                                            defaultValue={job.notes ?? ''}
                                        />
                                    </FormField>

                                    <FormField
                                        label="Internal notes"
                                        htmlFor="internal_notes"
                                        error={errors.internal_notes}
                                    >
                                        <textarea
                                            id="internal_notes"
                                            name="internal_notes"
                                            className={textareaClassName}
                                            defaultValue={
                                                job.internal_notes ?? ''
                                            }
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <div className="bg-background/85 supports-[backdrop-filter]:bg-background/65 sticky bottom-0 z-10 flex flex-wrap items-center gap-3 rounded-xl border border-hairline px-4 py-3 backdrop-blur">
                                <Button type="submit" disabled={processing}>
                                    Save changes
                                </Button>
                                <Button variant="ghost" asChild>
                                    <Link href={jobShow(job.id)}>
                                        Back to job
                                    </Link>
                                </Button>
                                <span className="text-muted-foreground ml-auto text-xs">
                                    Last updated{' '}
                                    {formatDate(job.dates.updated_at)}
                                </span>
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

JobsEdit.layout = {
    breadcrumbs: [
        {
            title: 'Jobs',
            href: jobsIndex(),
        },
        {
            title: 'Edit job',
            href: jobsIndex(),
        },
    ],
};
