import { Head, Link, useForm } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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 { index as employeeLoansIndex, store as employeeLoansStore } from '@/routes/admin/employee-loans';
import { ArrowLeft, Calculator, Info } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';

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

interface PageProps {
    employees: Employee[];
    types: { value: string; label: string }[];
}

export default function EmployeeLoanForm({ employees, types }: PageProps) {
    const { data, setData, post, processing, errors } = useForm({
        employee_id: '',
        type: 'loan',
        total_amount: '',
        monthly_installment: '',
        start_date: new Date().toISOString().substring(0, 7), // YYYY-MM
        reason: '',
    });

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

    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 (
        <>
            <Head title="Nouvelle demande d'avance/prêt" />

            <div className="flex flex-col gap-6 w-full max-w-3xl mx-auto py-8">
                <div className="flex items-center gap-4">
                    <Button variant="ghost" size="icon" asChild className="rounded-full">
                        <Link href={employeeLoansIndex().url}>
                            <ArrowLeft className="w-5 h-5" />
                        </Link>
                    </Button>
                    <div>
                        <h1 className="text-2xl font-semibold tracking-tight">Nouvelle demande</h1>
                        <p className="text-muted-foreground text-sm">Créez une avance sur salaire ou un prêt.</p>
                    </div>
                </div>

                <form onSubmit={submit} className="space-y-6">
                    <Card className="border-border/50 shadow-sm rounded-2xl overflow-hidden">
                        <CardHeader className="bg-muted/30 border-b border-border/50 pb-6">
                            <CardTitle className="text-lg">Informations générales</CardTitle>
                            <CardDescription>Sélectionnez l'employé et le type de demande.</CardDescription>
                        </CardHeader>
                        <CardContent className="p-6 space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-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>
                        </CardContent>
                    </Card>

                    <Card className="border-border/50 shadow-sm rounded-2xl overflow-hidden">
                        <CardHeader className="bg-muted/30 border-b border-border/50 pb-6">
                            <CardTitle className="text-lg">Montant et remboursement</CardTitle>
                            <CardDescription>Définissez le montant accordé et les modalités de retenue sur salaire.</CardDescription>
                        </CardHeader>
                        <CardContent className="p-6 space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-2">
                                    <Label htmlFor="total_amount">Montant total accordé (FCFA) *</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é à retenir (FCFA) *</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'}
                                    />
                                    {data.type === 'advance' && (
                                        <p className="text-xs text-muted-foreground">Une avance est retenue en une seule fois.</p>
                                    )}
                                    {errors.monthly_installment && <p className="text-xs text-destructive">{errors.monthly_installment}</p>}
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="start_date">Mois de début (YYYY-MM) *</Label>
                                    <Input
                                        id="start_date"
                                        type="month"
                                        value={data.start_date}
                                        onChange={(e) => setData('start_date', e.target.value)}
                                        className={errors.start_date ? 'border-destructive' : ''}
                                    />
                                    {errors.start_date && <p className="text-xs text-destructive">{errors.start_date}</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>
                                        Ce prêt sera remboursé sur <strong>{duration} mois</strong>, à hauteur de {new Intl.NumberFormat('fr-CI').format(monthly)} FCFA par mois. Le dernier mois ajustera le solde exact.
                                    </AlertDescription>
                                </Alert>
                            )}

                            <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>
                                    Attention, la loi ivoirienne encadre les retenues sur salaire (quotité saisissable). 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>
                        </CardContent>
                    </Card>

                    <Card className="border-border/50 shadow-sm rounded-2xl overflow-hidden">
                        <CardHeader className="bg-muted/30 border-b border-border/50 pb-6">
                            <CardTitle className="text-lg">Motif et Justification</CardTitle>
                        </CardHeader>
                        <CardContent className="p-6">
                            <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={3}
                                />
                                {errors.reason && <p className="text-xs text-destructive">{errors.reason}</p>}
                            </div>
                        </CardContent>
                    </Card>

                    <div className="flex justify-end gap-3">
                        <Button type="button" variant="outline" onClick={() => window.history.back()}>
                            Annuler
                        </Button>
                        <Button type="submit" disabled={processing}>
                            {processing ? 'Enregistrement...' : 'Créer la demande'}
                        </Button>
                    </div>
                </form>
            </div>
        </>
    );
}
