import { useState, useRef } from 'react';
import { useForm, router } from '@inertiajs/react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { SignaturePad, type SignaturePadHandle } from '@/components/signature-pad';
import { motion } from 'framer-motion';
import { sign as employeeLoansSign } from '@/routes/admin/employee-loans';

interface SignLoanModalProps {
    isOpen: boolean;
    onClose: () => void;
    loan: any;
}

export function SignLoanModal({ isOpen, onClose, loan }: SignLoanModalProps) {
    const signatureRef = useRef<SignaturePadHandle>(null);
    const { post, processing, errors, transform } = useForm({
        signature: '',
    });

    if (!loan) return null;

    const formatCurrency = (amount: string | number) => {
        return new Intl.NumberFormat('fr-CI', { style: 'currency', currency: 'XOF' }).format(Number(amount));
    };

    const handleConfirm = () => {
        const signature = signatureRef.current?.toDataURL();
        
        if (!signature) {
            alert('Veuillez signer le document avant de confirmer.');
            return;
        }

        transform(() => ({ signature }));

        post(employeeLoansSign(loan.id).url, {
            onSuccess: () => {
                onClose();
            },
        });
    };

    return (
        <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="max-w-2xl 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">Signature de l'accord de prélèvement</DialogTitle>
                        <DialogDescription>
                            Veuillez vérifier les informations ci-dessous et signer pour confirmer votre accord sur les retenues salariales.
                        </DialogDescription>
                    </DialogHeader>

                <div className="grid gap-4 py-4">
                    <div className="bg-muted p-4 rounded-lg space-y-3 text-sm">
                        <div className="flex justify-between border-b pb-2">
                            <span className="text-muted-foreground">Type de demande</span>
                            <span className="font-medium">{loan.type === 'loan' ? 'Prêt' : 'Avance sur salaire'}</span>
                        </div>
                        <div className="flex justify-between border-b pb-2">
                            <span className="text-muted-foreground">Montant Total</span>
                            <span className="font-medium">{formatCurrency(loan.total_amount)}</span>
                        </div>
                        <div className="flex justify-between border-b pb-2">
                            <span className="text-muted-foreground">Mensualité retenue</span>
                            <span className="font-medium text-primary">{formatCurrency(loan.monthly_installment)} / mois</span>
                        </div>
                        <div className="flex justify-between">
                            <span className="text-muted-foreground">Début des prélèvements</span>
                            <span className="font-medium">{loan.start_date}</span>
                        </div>
                    </div>

                        <div className="space-y-2 mt-4">
                            <Label className="text-sm font-semibold">Votre signature</Label>
                            <div className="border rounded-md bg-white flex flex-col justify-center">
                                <SignaturePad ref={signatureRef} />
                            </div>
                            {errors.signature && (
                                <p className="text-sm text-destructive mt-1">{errors.signature}</p>
                            )}
                        </div>
                    </div>

                    <DialogFooter className="mt-6 pt-4 border-t border-border">
                        <Button variant="outline" onClick={onClose} disabled={processing} className="rounded-xl">
                            Annuler
                        </Button>
                        <Button onClick={handleConfirm} disabled={processing} className="rounded-xl bg-orange-600 hover:bg-orange-700 text-white">
                            {processing ? 'Signature en cours...' : 'Signer l\'accord'}
                        </Button>
                    </DialogFooter>
                </motion.div>
            </DialogContent>
        </Dialog>
    );
}
