import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, ClipboardList } from 'lucide-react';
import type { FormEvent } from 'react';
import InventoryController from '@/actions/App/Http/Controllers/Admin/InventoryController';
import InputError from '@/components/input-error';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { dashboard } from '@/routes';
import { index as inventoriesIndex } from '@/routes/admin/inventories';

type WarehouseOption = { id: number; code: string; name: string };

export default function InventoriesCreate({
    warehouses,
}: {
    warehouses: WarehouseOption[];
}) {
    const form = useForm({
        warehouse_id: '',
        counted_at: new Date().toISOString().slice(0, 10),
        notes: '',
    });

    function submit(event: FormEvent) {
        event.preventDefault();

        form.transform((data) => ({
            warehouse_id: Number(data.warehouse_id),
            counted_at: data.counted_at,
            notes: data.notes || null,
        }));

        form.post(InventoryController.store.url());
    }

    return (
        <>
            <Head title="Nouvel inventaire" />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                    <Heading
                        title="Nouvel inventaire"
                        description="Créez un brouillon à partir du stock théorique actuel"
                    />
                    <Button variant="outline" asChild>
                        <Link href={inventoriesIndex.url()}>
                            <ArrowLeft />
                            Retour aux inventaires
                        </Link>
                    </Button>
                </div>

                <form onSubmit={submit} className="max-w-2xl">
                    <Card>
                        <CardHeader>
                            <CardTitle>Démarrer l&apos;inventaire</CardTitle>
                            <CardDescription>
                                Les produits en stock seront pré-remplis avec
                                leur quantité théorique. Vous pourrez ensuite
                                saisir les comptages réels.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="grid gap-2">
                                <Label htmlFor="warehouse_id">
                                    Entrepôt
                                    <span className="ml-0.5 text-destructive">
                                        *
                                    </span>
                                </Label>
                                <Select
                                    value={form.data.warehouse_id || undefined}
                                    onValueChange={(value) =>
                                        form.setData('warehouse_id', value)
                                    }
                                >
                                    <SelectTrigger id="warehouse_id">
                                        <SelectValue placeholder="Sélectionner un entrepôt" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {warehouses.map((warehouse) => (
                                            <SelectItem
                                                key={warehouse.id}
                                                value={String(warehouse.id)}
                                            >
                                                {warehouse.code} —{' '}
                                                {warehouse.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <InputError message={form.errors.warehouse_id} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="counted_at">
                                    Date d&apos;inventaire
                                    <span className="ml-0.5 text-destructive">
                                        *
                                    </span>
                                </Label>
                                <Input
                                    id="counted_at"
                                    type="date"
                                    value={form.data.counted_at}
                                    onChange={(event) =>
                                        form.setData(
                                            'counted_at',
                                            event.target.value,
                                        )
                                    }
                                    required
                                />
                                <InputError message={form.errors.counted_at} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="notes">Notes</Label>
                                <Textarea
                                    id="notes"
                                    rows={3}
                                    placeholder="Contexte ou périmètre de l'inventaire (optionnel)"
                                    value={form.data.notes}
                                    onChange={(event) =>
                                        form.setData('notes', event.target.value)
                                    }
                                />
                                <InputError message={form.errors.notes} />
                            </div>

                            <Button
                                type="submit"
                                disabled={
                                    form.processing ||
                                    form.data.warehouse_id === ''
                                }
                            >
                                <ClipboardList />
                                Créer le brouillon
                            </Button>
                        </CardContent>
                    </Card>
                </form>
            </div>
        </>
    );
}

InventoriesCreate.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Nouvel inventaire', href: '#' },
    ],
};
