import { useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import EmployeeController from '@/actions/App/Http/Controllers/Admin/EmployeeController';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
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';

export type TerminationReasonOption = { value: string; label: string };

type Props = {
    employeeId: number;
    employeeName: string;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    reasons: TerminationReasonOption[];
};

export function EmployeeTerminationDialog({
    employeeId,
    employeeName,
    open,
    onOpenChange,
    reasons,
}: Props) {
    const form = useForm({
        terminated_at: new Date().toISOString().slice(0, 10),
        termination_reason: reasons[0]?.value ?? 'resignation',
        termination_note: '',
        decision: null as File | null,
    });

    function close() {
        onOpenChange(false);
        form.reset();
        form.clearErrors();
    }

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

        form.transform((data) => ({
            terminated_at: data.terminated_at,
            termination_reason: data.termination_reason,
            termination_note: data.termination_note || null,
            decision: data.decision,
        }));

        form.post(EmployeeController.terminate.url(employeeId), {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => close(),
        });
    }

    return (
        <Dialog
            open={open}
            onOpenChange={(next) => {
                if (!next) {
                    close();
                }
            }}
        >
            <DialogContent className="sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>Terminer la collaboration</DialogTitle>
                    <DialogDescription>
                        Enregistrer le départ de {employeeName}. Le contrat
                        courant sera clôturé, le compte lié désactivé, et les
                        demandes ouvertes (congés à venir, notes de frais) seront
                        gelées.
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={submit} className="space-y-4">
                    <div className="grid gap-4 sm:grid-cols-2">
                        <div className="grid gap-2">
                            <Label>Motif</Label>
                            <Select
                                value={form.data.termination_reason}
                                onValueChange={(value) =>
                                    form.setData('termination_reason', value)
                                }
                            >
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    {reasons.map((reason) => (
                                        <SelectItem
                                            key={reason.value}
                                            value={reason.value}
                                        >
                                            {reason.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError
                                message={form.errors.termination_reason}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label>Date de départ</Label>
                            <Input
                                type="date"
                                value={form.data.terminated_at}
                                onChange={(e) =>
                                    form.setData(
                                        'terminated_at',
                                        e.target.value,
                                    )
                                }
                            />
                            <InputError message={form.errors.terminated_at} />
                        </div>
                    </div>

                    <div className="grid gap-2">
                        <Label>
                            Note{' '}
                            <span className="font-normal text-muted-foreground">
                                (optionnel)
                            </span>
                        </Label>
                        <Textarea
                            value={form.data.termination_note}
                            onChange={(e) =>
                                form.setData(
                                    'termination_note',
                                    e.target.value,
                                )
                            }
                        />
                        <InputError message={form.errors.termination_note} />
                    </div>

                    <div className="grid gap-2">
                        <Label>
                            Pièce de décision{' '}
                            <span className="font-normal text-muted-foreground">
                                (optionnel)
                            </span>
                        </Label>
                        <Input
                            type="file"
                            accept=".pdf,.jpg,.jpeg,.png"
                            onChange={(e) =>
                                form.setData(
                                    'decision',
                                    e.target.files?.[0] ?? null,
                                )
                            }
                        />
                        <p className="text-xs text-muted-foreground">
                            Lettre de démission, décision de licenciement… PDF,
                            JPG ou PNG, 10 Mo maximum.
                        </p>
                        <InputError message={form.errors.decision} />
                    </div>

                    <DialogFooter>
                        <Button type="button" variant="ghost" onClick={close}>
                            Annuler
                        </Button>
                        <Button type="submit" disabled={form.processing}>
                            Terminer la collaboration
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
