import { Form, Head, Link } from '@inertiajs/react';
import { useState } from 'react';
import {
    ClipboardList,
    DollarSign,
    MapPin,
    PanelTop,
    Plus,
    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 { PageHeader, SectionCard } from '@/components/crm/page-header';
import { FormField, NativeSelect } from '@/components/crm/native-select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { create as jobsCreate, index as jobsIndex } from '@/routes/jobs';
import type { OptionsBundle } from '@/types';

type Props = {
    options: OptionsBundle;
    customers: CustomerOption[];
    selectedCustomerId: number | null;
};

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]';

export default function JobsCreate({
    options,
    customers,
    selectedCustomerId,
}: Props) {
    // Opened from a customer's page, that customer is already chosen and their
    // first site follows with it. Everybody else is found by searching.
    const [customerId, setCustomerId] = useState<number | null>(
        () => selectedCustomerId,
    );
    const [siteId, setSiteId] = useState<number | null>(
        () =>
            customers.find((customer) => customer.id === selectedCustomerId)
                ?.sites[0]?.id ?? null,
    );

    return (
        <>
            <Head title="New job" />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <Plus className="size-3.5 text-solar" />
                            <span>New installation job</span>
                        </>
                    }
                    title="New job"
                    description="Create the job, then work it through the installation pipeline from the job page."
                    actions={
                        <Button variant="outline" size="sm" asChild>
                            <Link href={jobsIndex()}>Cancel</Link>
                        </Button>
                    }
                />

                <Form
                    {...JobController.store.form()}
                    className="flex flex-col gap-5"
                >
                    {({ processing, errors }) => (
                        <>
                            <SectionCard
                                title="Customer and site"
                                description="The site decides which distribution network and which inspection rules apply."
                                icon={MapPin}
                                tone="solar"
                            >
                                <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,
                                    }}
                                />
                            </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="residential_install"
                                        >
                                            {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="normal"
                                        >
                                            {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"
                                        />
                                    </FormField>

                                    <FormField
                                        label="Title"
                                        htmlFor="title"
                                        error={errors.title}
                                        className="md:col-span-2"
                                    >
                                        <Input
                                            id="title"
                                            name="title"
                                            placeholder="e.g. 6.6kW solar system with 5kW inverter"
                                        />
                                    </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"
                                        />
                                    </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}
                                            placeholder="What the customer has agreed to, and anything the design must respect."
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Team"
                                description="Who sells it, who runs it and who installs it."
                                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=""
                                        >
                                            <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=""
                                        >
                                            <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=""
                                        >
                                            <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=""
                                        >
                                            <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 company / subcontractor"
                                        htmlFor="installer_company"
                                        error={errors.installer_company}
                                    >
                                        <Input
                                            id="installer_company"
                                            name="installer_company"
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Commercials"
                                description="Only staff with financial access will see these figures."
                                icon={DollarSign}
                                tone="success"
                            >
                                <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"
                                        />
                                    </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"
                                        />
                                    </FormField>

                                    <FormField
                                        label="Finance provider"
                                        htmlFor="finance_provider"
                                        error={errors.finance_provider}
                                    >
                                        <Input
                                            id="finance_provider"
                                            name="finance_provider"
                                            placeholder="e.g. Brighte, Plenti"
                                        />
                                    </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"
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Proposed system"
                                description="The design that will be lodged with the network and installed on site."
                                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="grid"
                                        >
                                            {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"
                                        />
                                    </FormField>

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

                                    <EquipmentFields
                                        kind="panel"
                                        label="Panel"
                                        makeName="panel_make"
                                        modelName="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"
                                        />
                                    </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"
                                        />
                                    </FormField>

                                    <EquipmentFields
                                        kind="inverter"
                                        label="Inverter"
                                        makeName="inverter_make"
                                        modelName="inverter_model"
                                        makeError={errors.inverter_make}
                                        modelError={errors.inverter_model}
                                    />

                                    <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"
                                        />
                                    </FormField>

                                    <EquipmentFields
                                        kind="battery"
                                        label="Battery"
                                        makeName="battery_make"
                                        modelName="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"
                                        />
                                    </FormField>

                                    <FormField
                                        label="Export limit (kW)"
                                        htmlFor="export_limit_kw"
                                        error={errors.export_limit_kw}
                                        hint="Usually set by the distribution network."
                                    >
                                        <Input
                                            id="export_limit_kw"
                                            name="export_limit_kw"
                                            type="number"
                                            step="0.01"
                                            min="0"
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

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

                            <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}
                                        />
                                    </FormField>

                                    <FormField
                                        label="Internal notes"
                                        htmlFor="internal_notes"
                                        error={errors.internal_notes}
                                    >
                                        <textarea
                                            id="internal_notes"
                                            name="internal_notes"
                                            className={textareaClassName}
                                        />
                                    </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 || siteId === null}
                                >
                                    Create job
                                </Button>
                                <Button variant="ghost" asChild>
                                    <Link href={jobsIndex()}>Cancel</Link>
                                </Button>
                                <span className="text-muted-foreground ml-auto text-xs">
                                    The job starts at Lead / enquiry and moves
                                    through the pipeline from its own page.
                                </span>
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

JobsCreate.layout = {
    breadcrumbs: [
        {
            title: 'Jobs',
            href: jobsIndex(),
        },
        {
            title: 'New job',
            href: jobsCreate(),
        },
    ],
};
