import { Head, router, useForm } from '@inertiajs/react';
import { Plus, Save, Truck, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { PageHeader, SectionCard } from '@/components/crm/page-header';
import { Field } from '@/components/crm/form-field';
import {
    DataPagination,
    FilterBar,
    SearchInput,
} from '@/components/crm/toolbar';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    index as suppliersIndex,
    store,
    update,
} from '@/routes/warehouse/suppliers';
import type { Paginated, SupplierRow } from '@/types';

export default function Suppliers({
    suppliers,
    filters,
    can,
}: {
    suppliers: Paginated<SupplierRow>;
    filters: { search: string | null };
    can: { manage: boolean };
}) {
    const [search, setSearch] = useState(filters.search ?? '');
    const [editing, setEditing] = useState<number | null>(null);
    const [showCreate, setShowCreate] = useState(false);

    useEffect(() => {
        setSearch(filters.search ?? '');
    }, [filters.search]);

    const applySearch = (value: string) => {
        router.get(suppliersIndex().url, value ? { search: value } : {}, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    return (
        <>
            <Head title="Suppliers" />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <Truck className="size-3.5 text-solar" />
                            <span>Warehouse</span>
                        </>
                    }
                    title="Suppliers"
                    description="Who the company buys from, with the account reference and lead time a buyer needs when stock runs short. Suppliers are deactivated rather than deleted."
                    actions={
                        can.manage ? (
                            <Button
                                size="sm"
                                onClick={() => setShowCreate((open) => !open)}
                            >
                                <Plus className="size-4" />
                                New supplier
                            </Button>
                        ) : undefined
                    }
                />

                {can.manage && showCreate ? (
                    <SectionCard
                        title="New supplier"
                        description="Only the name is required. Everything else can be added when it is known."
                        icon={Truck}
                        tone="solar"
                    >
                        <SupplierForm onDone={() => setShowCreate(false)} />
                    </SectionCard>
                ) : null}

                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        applySearch(search);
                    }}
                >
                    <FilterBar>
                        <SearchInput
                            value={search}
                            onChange={setSearch}
                            placeholder="Supplier, contact or email"
                            className="min-w-[16rem]"
                        />
                    </FilterBar>
                </form>

                <SectionCard
                    title={`${suppliers.total} suppliers`}
                    description="A product can be linked to several; one is marked preferred."
                    icon={Truck}
                    flush
                >
                    <div className="crm-scroll overflow-x-auto">
                        <Table>
                            <TableHeader>
                                <TableRow className="hover:bg-transparent">
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Supplier
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Contact
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Lead time
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-right text-[11px] font-semibold tracking-wide uppercase">
                                        Products
                                    </TableHead>
                                    <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                        Status
                                    </TableHead>
                                    {can.manage ? (
                                        <TableHead className="bg-surface/60" />
                                    ) : null}
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {suppliers.data.length === 0 ? (
                                    <TableRow>
                                        <TableCell
                                            colSpan={can.manage ? 6 : 5}
                                            className="px-4 py-8 text-center text-sm text-muted-foreground"
                                        >
                                            No suppliers yet.
                                        </TableCell>
                                    </TableRow>
                                ) : null}
                                {suppliers.data.map((supplier) =>
                                    editing === supplier.id ? (
                                        <TableRow key={supplier.id}>
                                            <TableCell
                                                colSpan={can.manage ? 6 : 5}
                                                className="bg-muted/20"
                                            >
                                                <SupplierForm
                                                    supplier={supplier}
                                                    onDone={() =>
                                                        setEditing(null)
                                                    }
                                                />
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        <TableRow key={supplier.id}>
                                            <TableCell>
                                                <span className="block text-sm font-medium">
                                                    {supplier.name}
                                                </span>
                                                {supplier.account_reference ? (
                                                    <span className="block font-mono text-xs text-muted-foreground">
                                                        Account{' '}
                                                        {
                                                            supplier.account_reference
                                                        }
                                                    </span>
                                                ) : null}
                                            </TableCell>
                                            <TableCell className="text-xs text-muted-foreground">
                                                {supplier.contact_name ? (
                                                    <span className="block text-foreground">
                                                        {supplier.contact_name}
                                                    </span>
                                                ) : null}
                                                {supplier.email ? (
                                                    <span className="block">
                                                        {supplier.email}
                                                    </span>
                                                ) : null}
                                                {supplier.phone ? (
                                                    <span className="block">
                                                        {supplier.phone}
                                                    </span>
                                                ) : null}
                                                {!supplier.contact_name &&
                                                !supplier.email &&
                                                !supplier.phone
                                                    ? '—'
                                                    : null}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums crm-num">
                                                {supplier.lead_time_days ===
                                                null
                                                    ? '—'
                                                    : `${supplier.lead_time_days} days`}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums crm-num">
                                                {supplier.products_count}
                                            </TableCell>
                                            <TableCell className="text-xs text-muted-foreground">
                                                {supplier.is_active
                                                    ? 'Active'
                                                    : 'Inactive'}
                                            </TableCell>
                                            {can.manage ? (
                                                <TableCell className="text-right">
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() =>
                                                            setEditing(
                                                                supplier.id,
                                                            )
                                                        }
                                                    >
                                                        Edit
                                                    </Button>
                                                </TableCell>
                                            ) : null}
                                        </TableRow>
                                    ),
                                )}
                            </TableBody>
                        </Table>
                    </div>
                    <DataPagination page={suppliers} noun="suppliers" />
                </SectionCard>
            </div>
        </>
    );
}

function SupplierForm({
    supplier,
    onDone,
}: {
    supplier?: SupplierRow;
    onDone: () => void;
}) {
    const form = useForm({
        name: supplier?.name ?? '',
        contact_name: supplier?.contact_name ?? '',
        email: supplier?.email ?? '',
        phone: supplier?.phone ?? '',
        website: supplier?.website ?? '',
        account_reference: supplier?.account_reference ?? '',
        catalogue_url: supplier?.catalogue_url ?? '',
        lead_time_days:
            supplier?.lead_time_days === null ||
            supplier?.lead_time_days === undefined
                ? ''
                : String(supplier.lead_time_days),
        notes: supplier?.notes ?? '',
        is_active: supplier?.is_active ?? true,
    });

    const submit = () => {
        if (supplier) {
            form.patch(update(supplier.id).url, {
                preserveScroll: true,
                onSuccess: onDone,
            });
        } else {
            form.post(store().url, {
                preserveScroll: true,
                onSuccess: () => {
                    form.reset();
                    onDone();
                },
            });
        }
    };

    return (
        <form
            onSubmit={(event) => {
                event.preventDefault();
                submit();
            }}
            className="flex flex-col gap-3"
        >
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                <Field
                    label="Name"
                    htmlFor="supplier-name"
                    error={form.errors.name}
                    required
                >
                    <Input
                        id="supplier-name"
                        value={form.data.name}
                        onChange={(event) =>
                            form.setData('name', event.target.value)
                        }
                        required
                    />
                </Field>
                <Field
                    label="Contact name"
                    htmlFor="supplier-contact"
                    error={form.errors.contact_name}
                >
                    <Input
                        id="supplier-contact"
                        value={form.data.contact_name}
                        onChange={(event) =>
                            form.setData('contact_name', event.target.value)
                        }
                    />
                </Field>
                <Field
                    label="Email"
                    htmlFor="supplier-email"
                    error={form.errors.email}
                >
                    <Input
                        id="supplier-email"
                        type="email"
                        value={form.data.email}
                        onChange={(event) =>
                            form.setData('email', event.target.value)
                        }
                    />
                </Field>
                <Field
                    label="Phone"
                    htmlFor="supplier-phone"
                    error={form.errors.phone}
                >
                    <Input
                        id="supplier-phone"
                        value={form.data.phone}
                        onChange={(event) =>
                            form.setData('phone', event.target.value)
                        }
                    />
                </Field>
                <Field
                    label="Website"
                    htmlFor="supplier-website"
                    error={form.errors.website}
                >
                    <Input
                        id="supplier-website"
                        type="url"
                        value={form.data.website}
                        onChange={(event) =>
                            form.setData('website', event.target.value)
                        }
                        placeholder="https://"
                    />
                </Field>
                <Field
                    label="Account reference"
                    htmlFor="supplier-account"
                    error={form.errors.account_reference}
                    hint="The company's account number"
                >
                    <Input
                        id="supplier-account"
                        value={form.data.account_reference}
                        onChange={(event) =>
                            form.setData(
                                'account_reference',
                                event.target.value,
                            )
                        }
                    />
                </Field>
                <Field
                    label="Catalogue URL"
                    htmlFor="supplier-catalogue"
                    error={form.errors.catalogue_url}
                >
                    <Input
                        id="supplier-catalogue"
                        type="url"
                        value={form.data.catalogue_url}
                        onChange={(event) =>
                            form.setData('catalogue_url', event.target.value)
                        }
                        placeholder="https://"
                    />
                </Field>
                <Field
                    label="Lead time (days)"
                    htmlFor="supplier-lead"
                    error={form.errors.lead_time_days}
                >
                    <Input
                        id="supplier-lead"
                        type="number"
                        min={0}
                        value={form.data.lead_time_days}
                        onChange={(event) =>
                            form.setData('lead_time_days', event.target.value)
                        }
                    />
                </Field>
                <Field
                    label="Notes"
                    htmlFor="supplier-notes"
                    error={form.errors.notes}
                >
                    <Input
                        id="supplier-notes"
                        value={form.data.notes}
                        onChange={(event) =>
                            form.setData('notes', event.target.value)
                        }
                    />
                </Field>
                <label className="flex items-center gap-2 self-end text-sm">
                    <Checkbox
                        checked={form.data.is_active}
                        onCheckedChange={(checked) =>
                            form.setData('is_active', checked === true)
                        }
                    />
                    Active
                </label>
                <div className="flex items-end justify-end gap-2 lg:col-span-2">
                    <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={onDone}
                    >
                        <X className="size-4" />
                        Cancel
                    </Button>
                    <Button type="submit" size="sm" disabled={form.processing}>
                        <Save className="size-4" />
                        {supplier ? 'Save' : 'Add supplier'}
                    </Button>
                </div>
            </div>
        </form>
    );
}
