import { Head, useForm, usePage } from '@inertiajs/react';
import { useEffect, useState, type FormEvent } from 'react';
import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import DeleteUser from '@/components/delete-user';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useInitials } from '@/hooks/use-initials';
import { edit } from '@/routes/profile';
import type { Auth } from '@/types';

type EmployeeInfo = {
    job_title: string | null;
    department: string | null;
};

type PageProps = {
    auth: Auth;
    employeeInfo: EmployeeInfo | null;
};

export default function Profile() {
    const { auth, employeeInfo } = usePage<PageProps>().props;
    const getInitials = useInitials();
    const [avatarPreview, setAvatarPreview] = useState<string | null>(null);

    const form = useForm<{
        name: string;
        email: string;
        phone: string;
        avatar: File | null;
    }>({
        name: auth.user?.name ?? '',
        email: auth.user?.email ?? '',
        phone: auth.user?.phone ?? '',
        avatar: null,
    });

    useEffect(() => {
        return () => {
            if (avatarPreview) {
                URL.revokeObjectURL(avatarPreview);
            }
        };
    }, [avatarPreview]);

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

        form.post(ProfileController.update.form().action, {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => {
                form.setData('avatar', null);
                setAvatarPreview(null);
            },
        });
    }

    return (
        <>
            <Head title="Paramètres du profil" />

            <h1 className="sr-only">Paramètres du profil</h1>

            <div className="space-y-6">
                <Heading
                    variant="small"
                    title="Profil"
                    description="Mettez à jour vos informations personnelles"
                />

                <form onSubmit={submit} className="space-y-6">
                    <div className="grid gap-2">
                        <Label>Photo de profil</Label>
                        <div className="flex items-center gap-4">
                            <Avatar className="h-16 w-16 overflow-hidden rounded-full">
                                <AvatarImage
                                    src={
                                        avatarPreview ??
                                        auth.user?.avatar ??
                                        undefined
                                    }
                                    alt={auth.user?.name}
                                />
                                <AvatarFallback className="rounded-lg bg-neutral-200 text-black dark:bg-neutral-700 dark:text-white">
                                    {getInitials(auth.user?.name ?? '')}
                                </AvatarFallback>
                            </Avatar>
                            <Input
                                id="avatar"
                                type="file"
                                accept="image/*"
                                className="max-w-xs"
                                onChange={(e) => {
                                    const file = e.target.files?.[0] ?? null;
                                    form.setData('avatar', file);
                                    setAvatarPreview((previous) => {
                                        if (previous) {
                                            URL.revokeObjectURL(previous);
                                        }

                                        return file
                                            ? URL.createObjectURL(file)
                                            : null;
                                    });
                                }}
                            />
                        </div>
                        <InputError
                            className="mt-2"
                            message={form.errors.avatar}
                        />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="name">Nom</Label>

                        <Input
                            id="name"
                            className="mt-1 block w-full"
                            value={form.data.name}
                            onChange={(e) =>
                                form.setData('name', e.target.value)
                            }
                            required
                            autoComplete="name"
                            placeholder="Nom complet"
                        />

                        <InputError
                            className="mt-2"
                            message={form.errors.name}
                        />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="email">Adresse e-mail</Label>

                        <Input
                            id="email"
                            type="email"
                            className="mt-1 block w-full"
                            value={form.data.email}
                            onChange={(e) =>
                                form.setData('email', e.target.value)
                            }
                            required
                            autoComplete="username"
                            placeholder="Adresse e-mail"
                        />

                        <InputError
                            className="mt-2"
                            message={form.errors.email}
                        />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="phone">Téléphone</Label>

                        <Input
                            id="phone"
                            type="tel"
                            className="mt-1 block w-full"
                            value={form.data.phone}
                            onChange={(e) =>
                                form.setData('phone', e.target.value)
                            }
                            autoComplete="tel"
                            placeholder="Numéro de téléphone"
                        />

                        <InputError
                            className="mt-2"
                            message={form.errors.phone}
                        />
                    </div>

                    {employeeInfo && (
                        <div className="grid gap-3 rounded-lg border p-4">
                            <p className="text-sm font-medium">
                                Informations professionnelles
                            </p>
                            <p className="text-muted-foreground text-xs">
                                Ces informations sont gérées par les ressources
                                humaines.
                            </p>
                            <div className="grid gap-2 sm:grid-cols-2">
                                <div className="grid gap-1">
                                    <Label className="text-muted-foreground text-xs">
                                        Poste
                                    </Label>
                                    <p className="text-sm">
                                        {employeeInfo.job_title ?? '—'}
                                    </p>
                                </div>
                                <div className="grid gap-1">
                                    <Label className="text-muted-foreground text-xs">
                                        Service
                                    </Label>
                                    <p className="text-sm">
                                        {employeeInfo.department ?? '—'}
                                    </p>
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="flex items-center gap-4">
                        <Button
                            type="submit"
                            disabled={form.processing}
                            data-test="update-profile-button"
                        >
                            Enregistrer
                        </Button>
                    </div>
                </form>
            </div>

            <DeleteUser />
        </>
    );
}

Profile.layout = {
    breadcrumbs: [
        {
            title: 'Mon compte',
            href: edit(),
        },
    ],
};
