import { useForm } from '@inertiajs/react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { store as employeeLoansStore } from '@/routes/admin/employee-loans';
import { Calculator, Info, CalendarIcon } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { usePage } from '@inertiajs/react';
import type { Auth } from '@/types';
import { format, parse } from 'date-fns';
import { fr } from 'date-fns/locale';
import { cn } from '@/lib/utils';
import { motion } from 'framer-motion';

type PageProps = {
    auth: Auth;
};

interface Employee {
    id: number;
    first_name: string;
    last_name: string;
}

interface CreateLoanModalProps {
    isOpen: boolean;
    onClose: () => void;
    employees: Employee[];
    types: { value: string; label: string }[];
}

export function CreateLoanModal({ isOpen, onClose, employees, types }: CreateLoanModalProps) {
    const { auth } = usePage<PageProps>().props;
    const isValidator = auth.user?.permissions?.includes('employee-loans.validate') ?? false;

    const { data, setData, post, processing, errors, reset } = useForm({
        employee_id: !isValidator && employees.length > 0 ? employees[0].id.toString() : '',
        type: 'loan',
        total_amount: '',
        monthly_installment: '',
        start_date: format(new Date(), 'yyyy-MM'),
        reason: '',
    });

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        post(employeeLoansStore().url, {
            onSuccess: () => {
                reset();
                onClose();
            },
        });
    };

    const total = Number(data.total_amount) || 0;
    const monthly = Number(data.monthly_installment) || 0;
    const duration = monthly > 0 && total > 0 ? Math.ceil(total / monthly) : 0;

    return (
        <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="w-[95vw] !max-w-xl p-1 border border-border/10 shadow-2xl bg-gray-200 dark:bg-gray-800 sm:rounded-[32px]">
                <motion.div
                    initial={{ opacity: 0, scale: 0.96, y: 15 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
                    className="bg-background w-full h-full sm:rounded-[26px] p-6 sm:p-8 shadow-sm border border-border/30 overflow-y-auto max-h-[90vh]"
                >
                    <DialogHeader className="mb-4 pb-4 border-b border-border">
                        <DialogTitle className="text-orange-600 font-bold text-xl">Nouvelle demande</DialogTitle>
                        <DialogDescription>
                            Créez une avance sur salaire ou un prêt.
                        </DialogDescription>
                    </DialogHeader>

                <form onSubmit={submit} className="space-y-6 mt-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {isValidator && (
                            <div className="space-y-2 md:col-span-2">
                                <Label htmlFor="employee_id">Employé *</Label>
                                <Select
                                    value={data.employee_id}
                                    onValueChange={(val) => setData('employee_id', val)}
                                >
                                    <SelectTrigger id="employee_id" className={errors.employee_id ? 'border-destructive' : ''}>
                                        <SelectValue placeholder="Sélectionner un employé" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {employees.map((emp) => (
                                            <SelectItem key={emp.id} value={emp.id.toString()}>
                                                {emp.first_name} {emp.last_name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                {errors.employee_id && <p className="text-xs text-destructive">{errors.employee_id}</p>}
                            </div>
                        )}

                        <div className="space-y-2">
                            <Label htmlFor="type">Type *</Label>
                            <Select
                                value={data.type}
                                onValueChange={(val) => {
                                    setData('type', val);
                                    if (val === 'advance') {
                                        setData('monthly_installment', data.total_amount);
                                    }
                                }}
                            >
                                <SelectTrigger id="type" className={errors.type ? 'border-destructive' : ''}>
                                    <SelectValue placeholder="Sélectionner le type" />
                                </SelectTrigger>
                                <SelectContent>
                                    {types.map((type) => (
                                        <SelectItem key={type.value} value={type.value}>
                                            {type.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            {errors.type && <p className="text-xs text-destructive">{errors.type}</p>}
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="start_date">Mois de début (YYYY-MM) *</Label>
                            <Popover>
                                <PopoverTrigger asChild>
                                    <Button
                                        variant={"outline"}
                                        className={cn(
                                            "w-full justify-start text-left font-normal",
                                            !data.start_date && "text-muted-foreground",
                                            errors.start_date && "border-destructive"
                                        )}
                                    >
                                        <CalendarIcon className="mr-2 h-4 w-4" />
                                        {data.start_date ? (
                                            <span className="capitalize">
                                                {format(parse(data.start_date, 'yyyy-MM', new Date()), 'MMMM yyyy', { locale: fr })}
                                            </span>
                                        ) : (
                                            <span>Sélectionner le mois</span>
                                        )}
                                    </Button>
                                </PopoverTrigger>
                                <PopoverContent className="w-auto p-0" align="start">
                                    <Calendar
                                        mode="single"
                                        selected={data.start_date ? parse(data.start_date, 'yyyy-MM', new Date()) : undefined}
                                        onSelect={(date) => {
                                            if (date) {
                                                setData('start_date', format(date, 'yyyy-MM'));
                                            }
                                        }}
                                        initialFocus
                                    />
                                </PopoverContent>
                            </Popover>
                            {errors.start_date && <p className="text-xs text-destructive">{errors.start_date}</p>}
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">


                        <div className="space-y-2">
                            <Label htmlFor="total_amount">Montant total *</Label>
                            <Input
                                id="total_amount"
                                type="number"
                                min="1"
                                value={data.total_amount}
                                onChange={(e) => {
                                    setData('total_amount', e.target.value);
                                    if (data.type === 'advance') {
                                        setData('monthly_installment', e.target.value);
                                    }
                                }}
                                className={errors.total_amount ? 'border-destructive' : ''}
                                placeholder="Ex: 500000"
                            />
                            {errors.total_amount && <p className="text-xs text-destructive">{errors.total_amount}</p>}
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="monthly_installment">Mensualité *</Label>
                            <Input
                                id="monthly_installment"
                                type="number"
                                min="1"
                                max={data.total_amount || undefined}
                                value={data.monthly_installment}
                                onChange={(e) => setData('monthly_installment', e.target.value)}
                                className={errors.monthly_installment ? 'border-destructive' : ''}
                                placeholder="Ex: 50000"
                                readOnly={data.type === 'advance'}
                            />
                            {errors.monthly_installment && <p className="text-xs text-destructive">{errors.monthly_installment}</p>}
                        </div>

                    </div>

                    {duration > 0 && data.type === 'loan' && (
                        <Alert className="bg-primary/5 border-primary/20 text-primary">
                            <Calculator className="h-4 w-4" />
                            <AlertTitle>Simulation du remboursement</AlertTitle>
                            <AlertDescription>
                                <p>Ce prêt sera remboursé sur <strong>{duration} mois</strong>, à hauteur de {new Intl.NumberFormat('fr-CI').format(monthly)} FCFA par mois.</p>
                            </AlertDescription>
                        </Alert>
                    )}

                    {isValidator && (
                        <Alert className="bg-orange-50 dark:bg-orange-950/30 border-orange-200 dark:border-orange-900 text-orange-800 dark:text-orange-300">
                            <Info className="h-4 w-4" />
                            <AlertTitle>Quotité Saisissable</AlertTitle>
                            <AlertDescription>
                                Veillez à ce que la mensualité demandée ne dépasse pas la fraction saisissable du salaire net de l'employé au moment du calcul de la paie.
                            </AlertDescription>
                        </Alert>
                    )}

                    <div className="space-y-2">
                        <Label htmlFor="reason">Motif (optionnel)</Label>
                        <Textarea
                            id="reason"
                            value={data.reason}
                            onChange={(e) => setData('reason', e.target.value)}
                            placeholder="Raison de l'avance ou du prêt..."
                            rows={8}
                            className="resize-none"
                        />
                        {errors.reason && <p className="text-xs text-destructive">{errors.reason}</p>}
                    </div>

                    <DialogFooter className="mt-6 pt-4 border-t border-border">
                        <Button type="button" variant="outline" onClick={onClose} disabled={processing} className="rounded-xl">
                            Annuler
                        </Button>
                        <Button type="submit" disabled={processing} className="rounded-xl bg-orange-600 hover:bg-orange-700 text-white">
                            {processing ? 'Enregistrement...' : 'Soumettre la demande'}
                        </Button>
                    </DialogFooter>
                </form>
                </motion.div>
            </DialogContent>
        </Dialog>
    );
}
