import { Form, Head, Link } from '@inertiajs/react';
import { Mail } from 'lucide-react';
import { useMemo, useState } from 'react';
import UserController from '@/actions/App/Http/Controllers/Admin/UserController';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { SearchableSelect } from '@/components/searchable-select';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { create, index } from '@/routes/admin/users';
import { dashboard } from '@/routes';

type RoleOption = {
    name: string;
    label: string;
};

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

export default function UsersCreate({
    roles,
    departments,
}: {
    roles: RoleOption[];
    departments: DepartmentOption[];
}) {
    const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
    const [departmentId, setDepartmentId] = useState('none');

    const departmentOptions = useMemo(
        () =>
            departments.map((department) => ({
                value: String(department.id),
                label: `${department.code} — ${department.name}`,
            })),
        [departments],
    );

    function toggleRole(role: string, checked: boolean) {
        setSelectedRoles((current) =>
            checked
                ? [...current, role]
                : current.filter((value) => value !== role),
        );
    }

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

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <Heading
                    title="Nouvel utilisateur"
                    description="Créer un compte et lui assigner des rôles"
                />

                <Form
                    {...UserController.store.form()}
                    className="max-w-xl space-y-6"
                >
                    {({ processing, errors }) => (
                        <>
                            <div className="grid gap-2">
                                <Label htmlFor="name">Nom</Label>
                                <Input id="name" name="name" required />
                                <InputError message={errors.name} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="email">E-mail</Label>
                                <Input
                                    id="email"
                                    name="email"
                                    type="email"
                                    required
                                />
                                <InputError message={errors.email} />
                            </div>

                            <div className="flex items-start gap-2 rounded-md border border-dashed p-3 text-sm text-muted-foreground">
                                <Mail className="mt-0.5 size-4 shrink-0" />
                                <p>
                                    Un e-mail d'invitation sera envoyé à cette
                                    adresse pour permettre à l'utilisateur de
                                    définir son mot de passe.
                                </p>
                            </div>

                            <div className="grid gap-2">
                                <Label>Département</Label>
                                <SearchableSelect
                                    options={departmentOptions}
                                    value={departmentId}
                                    onChange={setDepartmentId}
                                    placeholder="Choisir un département…"
                                    noneLabel="Aucun"
                                    noneValue="none"
                                />
                                {departmentId !== 'none' && (
                                    <input
                                        type="hidden"
                                        name="department_id"
                                        value={departmentId}
                                    />
                                )}
                                <p className="text-muted-foreground text-xs">
                                    Appliqué à la fiche collaborateur associée.
                                </p>
                                <InputError message={errors.department_id} />
                            </div>

                            <div className="grid gap-3">
                                <Label>Rôles</Label>
                                {roles.map((role) => (
                                    <label
                                        key={role.name}
                                        className="flex items-center gap-2 text-sm"
                                    >
                                        <Checkbox
                                            checked={selectedRoles.includes(
                                                role.name,
                                            )}
                                            onCheckedChange={(checked) =>
                                                toggleRole(
                                                    role.name,
                                                    checked === true,
                                                )
                                            }
                                        />
                                        <span>{role.label}</span>
                                        {selectedRoles.includes(role.name) && (
                                            <input
                                                type="hidden"
                                                name="roles[]"
                                                value={role.name}
                                            />
                                        )}
                                    </label>
                                ))}
                                <InputError message={errors.roles} />
                            </div>

                            <div className="flex gap-3">
                                <Button disabled={processing}>Créer</Button>
                                <Button variant="outline" asChild>
                                    <Link href={index()}>Annuler</Link>
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

UsersCreate.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Utilisateurs', href: index() },
        { title: 'Créer', href: create() },
    ],
};
