import { useState } from 'react';
import { Form, Head, Link } from '@inertiajs/react';
import {
    Building2,
    HardHat,
    Mail,
    MapPin,
    Target,
    UserPlus,
    UserRound,
} from 'lucide-react';
import CustomerController from '@/actions/App/Http/Controllers/CustomerController';
import { Callout, 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 { index as customersIndex } from '@/routes/customers';
import type { OptionsBundle } from '@/types';

export default function CustomerCreate({
    options,
    builder,
}: {
    options: OptionsBundle;
    /**
     * The builder whose page opened this form, when it did. The client is saved
     * under that account in the same request, so there is nothing to remember
     * to do afterwards.
     */
    builder: { id: number; name: string; customer_number: string } | null;
}) {
    const [type, setType] = useState('residential');

    // Everything except a residential customer is billed as an organisation,
    // which matches App\Enums\CustomerType::isOrganisation() on the backend.
    const isOrganisation = type !== 'residential';

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

            <Form
                {...CustomerController.store.form()}
                options={{ preserveScroll: true }}
                className="flex flex-col gap-5"
            >
                {({ processing, errors }) => (
                    <>
                        <PageHeader
                            eyebrow={
                                <>
                                    <UserPlus className="text-solar size-3.5" />
                                    <span>New customer record</span>
                                </>
                            }
                            title="New customer"
                            description="Record the billing party. Sites and jobs are added against the customer afterwards."
                            actions={
                                <>
                                    <Button variant="outline" asChild>
                                        <Link href={customersIndex()}>
                                            Cancel
                                        </Link>
                                    </Button>
                                    <Button
                                        type="submit"
                                        disabled={processing}
                                        data-test="create-customer-button"
                                    >
                                        Create customer
                                    </Button>
                                </>
                            }
                        />

                        {builder ? (
                            <Callout
                                tone="info"
                                icon={HardHat}
                                title={`This client will be under ${builder.name}`}
                            >
                                {builder.name} ({builder.customer_number}) is the
                                builder account. Their own sites, jobs and
                                billing are recorded here, and the account whose
                                client they are is recorded against this
                                customer.
                                <input
                                    type="hidden"
                                    name="builder_id"
                                    value={builder.id}
                                />
                            </Callout>
                        ) : null}

                        <div className="grid gap-4 lg:grid-cols-2">
                            <SectionCard
                                title="Customer type"
                                description="The type decides whether this is billed as a person or an organisation."
                                icon={Building2}
                                tone="solar"
                            >
                                <FormField
                                    label="Type"
                                    htmlFor="type"
                                    error={errors.type}
                                    required
                                >
                                    <NativeSelect
                                        id="type"
                                        name="type"
                                        value={type}
                                        onChange={(event) =>
                                            setType(event.target.value)
                                        }
                                    >
                                        {options.customerTypes.map((option) => (
                                            <option
                                                key={option.value}
                                                value={option.value}
                                            >
                                                {option.label}
                                            </option>
                                        ))}
                                    </NativeSelect>
                                </FormField>
                            </SectionCard>

                            <SectionCard
                                title="Details"
                                icon={UserRound}
                                tone="info"
                                description={
                                    isOrganisation
                                        ? 'Company name and ABN, plus the main person we deal with.'
                                        : 'The account holder’s name.'
                                }
                            >
                                <div className="grid gap-4 sm:grid-cols-2">
                                    {isOrganisation ? (
                                        <>
                                            <FormField
                                                label="Company name"
                                                htmlFor="company_name"
                                                error={errors.company_name}
                                                required
                                                className="sm:col-span-2"
                                            >
                                                <Input
                                                    id="company_name"
                                                    name="company_name"
                                                    defaultValue=""
                                                    autoComplete="organization"
                                                />
                                            </FormField>
                                            <FormField
                                                label="ABN"
                                                htmlFor="abn"
                                                error={errors.abn}
                                                hint="11 digits"
                                            >
                                                <Input
                                                    id="abn"
                                                    name="abn"
                                                    inputMode="numeric"
                                                    placeholder="12345678901"
                                                />
                                            </FormField>
                                            <FormField
                                                label="ACN"
                                                htmlFor="acn"
                                                error={errors.acn}
                                                hint="9 digits, if registered"
                                            >
                                                <Input
                                                    id="acn"
                                                    name="acn"
                                                    inputMode="numeric"
                                                />
                                            </FormField>
                                            <FormField
                                                label="Contact first name"
                                                htmlFor="first_name"
                                                error={errors.first_name}
                                            >
                                                <Input
                                                    id="first_name"
                                                    name="first_name"
                                                    autoComplete="given-name"
                                                />
                                            </FormField>
                                            <FormField
                                                label="Contact last name"
                                                htmlFor="last_name"
                                                error={errors.last_name}
                                            >
                                                <Input
                                                    id="last_name"
                                                    name="last_name"
                                                    autoComplete="family-name"
                                                />
                                            </FormField>
                                        </>
                                    ) : (
                                        <>
                                            <FormField
                                                label="First name"
                                                htmlFor="first_name"
                                                error={errors.first_name}
                                                required
                                            >
                                                <Input
                                                    id="first_name"
                                                    name="first_name"
                                                    autoComplete="given-name"
                                                />
                                            </FormField>
                                            <FormField
                                                label="Last name"
                                                htmlFor="last_name"
                                                error={errors.last_name}
                                                required
                                            >
                                                <Input
                                                    id="last_name"
                                                    name="last_name"
                                                    autoComplete="family-name"
                                                />
                                            </FormField>
                                        </>
                                    )}
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Contact details"
                                description="How we reach the customer."
                                icon={Mail}
                                tone="violet"
                            >
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <FormField
                                        label="Email"
                                        htmlFor="email"
                                        error={errors.email}
                                    >
                                        <Input
                                            id="email"
                                            name="email"
                                            type="email"
                                            autoComplete="email"
                                        />
                                    </FormField>
                                    <FormField
                                        label="Phone"
                                        htmlFor="phone"
                                        error={errors.phone}
                                    >
                                        <Input
                                            id="phone"
                                            name="phone"
                                            type="tel"
                                            autoComplete="tel"
                                        />
                                    </FormField>
                                    <FormField
                                        label="Alternate phone"
                                        htmlFor="alternate_phone"
                                        error={errors.alternate_phone}
                                    >
                                        <Input
                                            id="alternate_phone"
                                            name="alternate_phone"
                                            type="tel"
                                        />
                                    </FormField>
                                    <FormField
                                        label="Preferred contact method"
                                        htmlFor="preferred_contact_method"
                                        error={errors.preferred_contact_method}
                                    >
                                        <NativeSelect
                                            id="preferred_contact_method"
                                            name="preferred_contact_method"
                                            defaultValue=""
                                        >
                                            <option value="">No preference</option>
                                            {options.contactMethods.map(
                                                (option) => (
                                                    <option
                                                        key={option.value}
                                                        value={option.value}
                                                    >
                                                        {option.label}
                                                    </option>
                                                ),
                                            )}
                                        </NativeSelect>
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Billing address"
                                description="Where invoices are sent. Installation addresses are recorded as sites."
                                icon={MapPin}
                            >
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <FormField
                                        label="Address line 1"
                                        htmlFor="billing_address_line1"
                                        error={errors.billing_address_line1}
                                        className="sm:col-span-2"
                                    >
                                        <Input
                                            id="billing_address_line1"
                                            name="billing_address_line1"
                                            autoComplete="address-line1"
                                        />
                                    </FormField>
                                    <FormField
                                        label="Address line 2"
                                        htmlFor="billing_address_line2"
                                        error={errors.billing_address_line2}
                                        className="sm:col-span-2"
                                    >
                                        <Input
                                            id="billing_address_line2"
                                            name="billing_address_line2"
                                            autoComplete="address-line2"
                                        />
                                    </FormField>
                                    <FormField
                                        label="Suburb"
                                        htmlFor="billing_suburb"
                                        error={errors.billing_suburb}
                                    >
                                        <Input
                                            id="billing_suburb"
                                            name="billing_suburb"
                                            autoComplete="address-level2"
                                        />
                                    </FormField>
                                    <FormField
                                        label="State"
                                        htmlFor="billing_state"
                                        error={errors.billing_state}
                                    >
                                        <NativeSelect
                                            id="billing_state"
                                            name="billing_state"
                                            defaultValue=""
                                        >
                                            <option value="">Select a state</option>
                                            {options.states.map((option) => (
                                                <option
                                                    key={option.value}
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>
                                    <FormField
                                        label="Postcode"
                                        htmlFor="billing_postcode"
                                        error={errors.billing_postcode}
                                        hint="4 digits"
                                    >
                                        <Input
                                            id="billing_postcode"
                                            name="billing_postcode"
                                            inputMode="numeric"
                                            autoComplete="postal-code"
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>

                            <SectionCard
                                title="Sales and ownership"
                                description="Where the lead came from and who owns the relationship."
                                icon={Target}
                                tone="amber"
                            >
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <FormField
                                        label="Lead source"
                                        htmlFor="lead_source"
                                        error={errors.lead_source}
                                    >
                                        <NativeSelect
                                            id="lead_source"
                                            name="lead_source"
                                            defaultValue=""
                                        >
                                            <option value="">Not recorded</option>
                                            {options.leadSources.map((option) => (
                                                <option
                                                    key={option.value}
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>
                                    <FormField
                                        label="Lead source detail"
                                        htmlFor="lead_source_detail"
                                        error={errors.lead_source_detail}
                                        hint="For example the referring customer or campaign."
                                    >
                                        <Input
                                            id="lead_source_detail"
                                            name="lead_source_detail"
                                        />
                                    </FormField>
                                    <FormField
                                        label="Account owner"
                                        htmlFor="owner_id"
                                        error={errors.owner_id}
                                        className="sm:col-span-2"
                                    >
                                        <NativeSelect
                                            id="owner_id"
                                            name="owner_id"
                                            defaultValue=""
                                        >
                                            <option value="">
                                                Leave blank to assign me
                                            </option>
                                            {options.staff.map((option) => (
                                                <option
                                                    key={option.value}
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                    {option.role
                                                        ? ` (${option.role})`
                                                        : ''}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FormField>
                                    <FormField
                                        label="Notes"
                                        htmlFor="notes"
                                        error={errors.notes}
                                        className="sm:col-span-2"
                                    >
                                        <textarea
                                            id="notes"
                                            name="notes"
                                            rows={4}
                                            className="border-input dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:ring-[3px]"
                                        />
                                    </FormField>
                                </div>
                            </SectionCard>
                        </div>
                    </>
                )}
            </Form>
        </>
    );
}

CustomerCreate.layout = {
    breadcrumbs: [
        { title: 'Customers', href: customersIndex() },
        { title: 'New customer', href: '' },
    ],
};
