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 { Textarea } from '@/components/ui/textarea';
import { formatIDR } from '@/lib/formatters';
import type { Financing, FinancingProduct } from '@/types/financing';
import { Calculator } from 'lucide-react';
import { useMemo, useState } from 'react';

interface ApprovalModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    financing: Financing;
    product: FinancingProduct;
    onApprove: (data: { approved_amount: number; notes: string }) => void;
    loading?: boolean;
}

export function ApprovalModal({
    open,
    onOpenChange,
    financing,
    product,
    onApprove,
    loading = false,
}: ApprovalModalProps) {
    const [approvedAmount, setApprovedAmount] = useState(
        financing.principal_amount,
    );
    const [notes, setNotes] = useState('');

    // Real-time calculation based on approved amount
    const calculation = useMemo(() => {
        const principal = approvedAmount;
        const margin = principal * (product.margin_rate / 100);
        const total = principal + margin;
        const daily = total / product.installment_count;

        return {
            principal,
            margin,
            total,
            daily,
        };
    }, [approvedAmount, product.margin_rate, product.installment_count]);

    const handleSubmit = () => {
        if (approvedAmount <= 0) {
            return;
        }

        if (approvedAmount < product.min_amount) {
            alert(
                `Jumlah persetujuan minimum adalah ${formatIDR(product.min_amount)}`,
            );
            return;
        }

        if (approvedAmount > financing.principal_amount) {
            alert(
                `Jumlah persetujuan tidak boleh melebihi pengajuan (${formatIDR(financing.principal_amount)})`,
            );
            return;
        }

        onApprove({
            approved_amount: approvedAmount,
            notes,
        });
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-2xl">
                <DialogHeader>
                    <DialogTitle>Persetujuan Pembiayaan</DialogTitle>
                    <DialogDescription>
                        Review dan setujui pengajuan pembiayaan{' '}
                        {financing.account_number}
                    </DialogDescription>
                </DialogHeader>

                <div className="space-y-4 py-4">
                    {/* Financing Summary */}
                    <div className="space-y-2 rounded-lg border p-4">
                        <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">
                                Anggota
                            </span>
                            <span className="font-medium">
                                {financing.member.name}
                            </span>
                        </div>
                        <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">
                                Produk
                            </span>
                            <span className="font-medium">{product.name}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">
                                Pengajuan
                            </span>
                            <span className="font-medium">
                                {formatIDR(financing.principal_amount)}
                            </span>
                        </div>
                        <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">
                                Tujuan
                            </span>
                            <span className="max-w-[300px] text-right">
                                {financing.financing_purpose}
                            </span>
                        </div>
                        {financing.member.collectibility_score && (
                            <div className="flex justify-between text-sm">
                                <span className="text-muted-foreground">
                                    Kolektibilitas
                                </span>
                                <span
                                    className={
                                        financing.member.collectibility_score >=
                                        4
                                            ? 'font-medium text-destructive'
                                            : ''
                                    }
                                >
                                    {financing.member.collectibility_score === 5
                                        ? 'Macet'
                                        : financing.member
                                                .collectibility_score === 4
                                          ? 'Diragukan'
                                          : financing.member
                                                  .collectibility_score === 3
                                            ? 'Kurang Lancar'
                                            : financing.member
                                                    .collectibility_score === 2
                                              ? 'Dalam Perhatian'
                                              : 'Lancar'}
                                </span>
                            </div>
                        )}
                    </div>

                    {/* Approved Amount Input */}
                    <div className="space-y-2">
                        <Label htmlFor="approved_amount">
                            Jumlah Persetujuan{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="approved_amount"
                            type="number"
                            min={product.min_amount}
                            max={financing.principal_amount}
                            step={100000}
                            value={approvedAmount}
                            onChange={(e) =>
                                setApprovedAmount(Number(e.target.value))
                            }
                            required
                        />
                        <p className="text-xs text-muted-foreground">
                            Min: {formatIDR(product.min_amount)} • Max:{' '}
                            {formatIDR(financing.principal_amount)}
                        </p>
                    </div>

                    {/* Real-time Calculation */}
                    {approvedAmount > 0 && (
                        <div className="space-y-3 rounded-lg bg-primary/10 p-4">
                            <div className="flex items-center gap-2 text-sm font-medium">
                                <Calculator className="h-4 w-4" />
                                Perhitungan Baru
                            </div>
                            <div className="space-y-2 text-sm">
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Pokok
                                    </span>
                                    <span className="font-medium">
                                        {formatIDR(calculation.principal)}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Margin ({product.margin_rate}%)
                                    </span>
                                    <span className="font-medium">
                                        {formatIDR(calculation.margin)}
                                    </span>
                                </div>
                                <div className="flex justify-between border-t pt-2 font-bold">
                                    <span>Total Pengembalian</span>
                                    <span>{formatIDR(calculation.total)}</span>
                                </div>
                                <div className="flex justify-between text-lg">
                                    <span className="text-muted-foreground">
                                        Angsuran Harian
                                    </span>
                                    <span className="font-bold text-primary">
                                        {formatIDR(calculation.daily)}
                                    </span>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Notes */}
                    <div className="space-y-2">
                        <Label htmlFor="notes">Catatan (Opsional)</Label>
                        <Textarea
                            id="notes"
                            value={notes}
                            onChange={(e) => setNotes(e.target.value)}
                            placeholder="Catatan persetujuan..."
                            rows={3}
                        />
                    </div>

                    {/* Warning for High Collectibility */}
                    {financing.member.collectibility_score &&
                        financing.member.collectibility_score >= 4 && (
                            <div className="rounded-lg border border-destructive/20 bg-destructive/10 p-3">
                                <p className="text-sm font-medium text-destructive">
                                    ⚠️ Peringatan: Kolektibilitas Tinggi
                                </p>
                                <p className="mt-1 text-xs text-destructive">
                                    Anggota memiliki kolektibilitas{' '}
                                    {financing.member.collectibility_score === 5
                                        ? 'Macet'
                                        : 'Diragukan'}
                                    . Pertimbangkan risiko sebelum menyetujui.
                                </p>
                            </div>
                        )}
                </div>

                <DialogFooter>
                    <Button
                        variant="outline"
                        onClick={() => onOpenChange(false)}
                        disabled={loading}
                    >
                        Batal
                    </Button>
                    <Button
                        onClick={handleSubmit}
                        disabled={loading || approvedAmount <= 0}
                    >
                        {loading ? 'Memproses...' : 'Setujui Pembiayaan'}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
