import { Head, useForm } from '@inertiajs/react';
import { FolderTree, Plus, Save, X } from 'lucide-react';
import { useState } from 'react';
import { PageHeader, SectionCard } from '@/components/crm/page-header';
import { Field } from '@/components/crm/form-field';
import { NativeSelect } from '@/components/crm/native-select';
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 { store, update } from '@/routes/warehouse/categories';
import type { ProductCategoryRow } from '@/types';

export default function Categories({
    categories,
    can,
}: {
    categories: ProductCategoryRow[];
    can: { manage: boolean };
}) {
    const [editing, setEditing] = useState<number | null>(null);
    const [showCreate, setShowCreate] = useState(false);

    const topLevel = categories.filter(
        (category) => category.parent_id === null,
    );

    return (
        <>
            <Head title="Product categories" />

            <div className="flex flex-col gap-5">
                <PageHeader
                    eyebrow={
                        <>
                            <FolderTree className="size-3.5 text-solar" />
                            <span>Warehouse</span>
                        </>
                    }
                    title="Product categories"
                    description="The headings the catalogue is organised by. They are rows, not code, so a company can shape the catalogue around its own range."
                    actions={
                        can.manage ? (
                            <Button
                                size="sm"
                                onClick={() => setShowCreate((open) => !open)}
                            >
                                <Plus className="size-4" />
                                New category
                            </Button>
                        ) : undefined
                    }
                />

                {can.manage && showCreate ? (
                    <SectionCard
                        title="New category"
                        description="One level of nesting: a heading, and optionally a subheading."
                        icon={FolderTree}
                        tone="solar"
                    >
                        <CategoryForm
                            topLevel={topLevel}
                            onDone={() => setShowCreate(false)}
                        />
                    </SectionCard>
                ) : null}

                <SectionCard
                    title={`${categories.length} categories`}
                    description="Products are counted across the category, including archived lines."
                    icon={FolderTree}
                    flush
                >
                    {categories.length === 0 ? (
                        <p className="px-5 pb-4 text-xs text-muted-foreground">
                            No categories yet. Run the starter catalogue seeder
                            or add the first one.
                        </p>
                    ) : (
                        <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">
                                            Code
                                        </TableHead>
                                        <TableHead className="bg-surface/60 text-[11px] font-semibold tracking-wide uppercase">
                                            Category
                                        </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>
                                    {categories.map((category) =>
                                        editing === category.id ? (
                                            <TableRow key={category.id}>
                                                <TableCell
                                                    colSpan={can.manage ? 5 : 4}
                                                    className="bg-muted/20"
                                                >
                                                    <CategoryForm
                                                        category={category}
                                                        topLevel={topLevel}
                                                        onDone={() =>
                                                            setEditing(null)
                                                        }
                                                    />
                                                </TableCell>
                                            </TableRow>
                                        ) : (
                                            <TableRow key={category.id}>
                                                <TableCell className="font-mono text-xs text-muted-foreground">
                                                    {category.code ?? '—'}
                                                </TableCell>
                                                <TableCell>
                                                    <span
                                                        className={
                                                            category.parent_id
                                                                ? 'pl-4 text-sm text-muted-foreground'
                                                                : 'text-sm font-medium'
                                                        }
                                                    >
                                                        {category.parent_id
                                                            ? `↳ ${category.name}`
                                                            : category.name}
                                                    </span>
                                                    {category.description ? (
                                                        <span className="block text-xs text-muted-foreground">
                                                            {
                                                                category.description
                                                            }
                                                        </span>
                                                    ) : null}
                                                </TableCell>
                                                <TableCell className="text-right tabular-nums crm-num">
                                                    {category.products_count}
                                                </TableCell>
                                                <TableCell className="text-xs text-muted-foreground">
                                                    {category.is_active
                                                        ? 'Active'
                                                        : 'Inactive'}
                                                </TableCell>
                                                {can.manage ? (
                                                    <TableCell className="text-right">
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            onClick={() =>
                                                                setEditing(
                                                                    category.id,
                                                                )
                                                            }
                                                        >
                                                            Edit
                                                        </Button>
                                                    </TableCell>
                                                ) : null}
                                            </TableRow>
                                        ),
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    )}
                </SectionCard>
            </div>
        </>
    );
}

function CategoryForm({
    category,
    topLevel,
    onDone,
}: {
    category?: ProductCategoryRow;
    topLevel: ProductCategoryRow[];
    onDone: () => void;
}) {
    const form = useForm({
        name: category?.name ?? '',
        code: category?.code ?? '',
        description: category?.description ?? '',
        parent_id: category?.parent_id ? String(category.parent_id) : '',
        sort_order: String(category?.sort_order ?? 0),
        is_active: category?.is_active ?? true,
    });

    const submit = () => {
        if (category) {
            form.patch(update(category.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-4">
                <Field
                    label="Name"
                    htmlFor="category-name"
                    error={form.errors.name}
                    required
                >
                    <Input
                        id="category-name"
                        value={form.data.name}
                        onChange={(event) =>
                            form.setData('name', event.target.value)
                        }
                        placeholder="Mounting equipment"
                        required
                    />
                </Field>
                <Field
                    label="Code"
                    htmlFor="category-code"
                    error={form.errors.code}
                    hint="Optional short label"
                >
                    <Input
                        id="category-code"
                        value={form.data.code}
                        onChange={(event) =>
                            form.setData('code', event.target.value)
                        }
                        placeholder="D"
                        maxLength={12}
                    />
                </Field>
                <Field
                    label="Parent"
                    htmlFor="category-parent"
                    error={form.errors.parent_id}
                >
                    <NativeSelect
                        id="category-parent"
                        value={form.data.parent_id}
                        onChange={(event) =>
                            form.setData('parent_id', event.target.value)
                        }
                    >
                        <option value="">Top level</option>
                        {topLevel
                            .filter((option) => option.id !== category?.id)
                            .map((option) => (
                                <option
                                    key={option.id}
                                    value={String(option.id)}
                                >
                                    {option.name}
                                </option>
                            ))}
                    </NativeSelect>
                </Field>
                <Field
                    label="Order"
                    htmlFor="category-order"
                    error={form.errors.sort_order}
                    hint="Lower comes first"
                >
                    <Input
                        id="category-order"
                        type="number"
                        min={0}
                        value={form.data.sort_order}
                        onChange={(event) =>
                            form.setData('sort_order', event.target.value)
                        }
                    />
                </Field>
                <Field
                    label="Description"
                    htmlFor="category-description"
                    error={form.errors.description}
                    className="sm:col-span-2"
                >
                    <Input
                        id="category-description"
                        value={form.data.description}
                        onChange={(event) =>
                            form.setData('description', 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">
                    <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" />
                        {category ? 'Save' : 'Add category'}
                    </Button>
                </div>
            </div>
        </form>
    );
}
