import React, { useState, useEffect } from 'react';
import Toast from '../Components/Toast';
import { 
    ChevronLeft, 
    Edit2, 
    TrendingUp, 
    Calendar, 
    MapPin, 
    Building, 
    Wallet, 
    FileText, 
    Users, 
    Eye,
    Percent,
    Clock,
    Shield,
    CheckCircle2,
    AlertCircle,
    X,
    ArrowRight,
    Download
} from 'lucide-react';

export default function InvestorView({ id }) {
    const isReceptionist = window.__APP_DATA__?.role === 'receptionist';
    const basePath = isReceptionist ? '/receptionist/investors' : '/owner/investors';
    
    const [investor, setInvestor] = useState(null);
    const [payouts, setPayouts] = useState([]);
    const [roiStatus, setRoiStatus] = useState([]);
    const [loading, setLoading] = useState(true);
    const [toast, setToast] = useState(null);
    const [activeTab, setActiveTab] = useState('Overview');
    const [isPreviewOpen, setIsPreviewOpen] = useState(false);
    
    const [settleModal, setSettleModal] = useState({
        isOpen: false,
        month: '',
        amount: '',
        originalAmount: '',
        baseAmount: 0,
        carryOver: 0,
        date: new Date().toISOString().split('T')[0],
        method: 'Bank Transfer',
        remarks: ''
    });

    useEffect(() => {
        fetchInvestor();
        fetchPayouts();
        fetchROIStatus();
    }, [id]);

    const fetchPayouts = async () => {
        try {
            const response = await fetch(`/api/investors/${id}/payouts`);
            const data = await response.json();
            setPayouts(data);
        } catch (error) {
            console.error('Error fetching payouts:', error);
        }
    };

    const fetchROIStatus = async () => {
        try {
            const response = await fetch(`/api/investors/${id}/roi-status`);
            const data = await response.json();
            setRoiStatus(data);
        } catch (error) {
            console.error('Error fetching ROI status:', error);
        }
    };

    const fetchInvestor = async () => {
        try {
            const response = await fetch(`/api/investors/${id}`);
            const data = await response.json();
            setInvestor(data);
        } catch (error) {
            console.error('Error fetching investor:', error);
            setToast({ message: 'Failed to load investor details.', type: 'error' });
        } finally {
            setLoading(false);
        }
    };

    const handleSettleROI = async (e) => {
        e.preventDefault();

        // Validation: Remarks mandatory if amount is adjusted
        if (parseFloat(settleModal.amount) !== parseFloat(settleModal.originalAmount) && !settleModal.remarks?.trim()) {
            setToast({ message: 'Remarks field is mandatory when adjusting the payment amount.', type: 'error' });
            return;
        }

        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
        try {
            const response = await fetch(`/api/investors/${id}/settle-roi`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({
                    payout_month: settleModal.month,
                    amount: settleModal.amount,
                    payout_date: settleModal.date,
                    payment_method: settleModal.method,
                    remarks: settleModal.remarks
                })
            });

            if (response.ok) {
                setToast({ message: 'ROI settled successfully!', type: 'success' });
                setSettleModal({ 
                    isOpen: false,
                    month: '',
                    amount: '',
                    originalAmount: '',
                    date: new Date().toISOString().split('T')[0],
                    method: 'Bank Transfer',
                    remarks: ''
                });
                fetchPayouts();
                fetchROIStatus();
            } else {
                setToast({ message: 'Settlement failed.', type: 'error' });
            }
        } catch (error) {
            setToast({ message: 'Error during settlement.', type: 'error' });
        }
    };

    if (loading) return (
        <div className="min-h-screen bg-[#FDFDFD] flex items-center justify-center">
            <div className="animate-spin rounded-full h-12 w-12 border-4 border-emerald-500 border-t-transparent shadow-lg shadow-emerald-100"></div>
        </div>
    );
    
    if (!investor) return (
        <div className="min-h-screen bg-[#FDFDFD] flex flex-col items-center justify-center space-y-4">
            <AlertCircle size={64} className="text-red-500 opacity-20" />
            <h1 className="text-2xl font-black text-gray-900 uppercase italic">Investor Not Found</h1>
            <button onClick={() => window.location.href = basePath} className="px-6 py-2 bg-gray-900 text-white rounded-xl text-sm font-bold">Return to Registry</button>
        </div>
    );

    const initials = investor.name?.split(' ').map(n => n[0]).join('').toUpperCase() || 'INV';
    const totalPayouts = payouts.reduce((acc, p) => acc + parseFloat(p.amount || 0), 0);

    return (
        <>
            {toast && <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />}

            <main className="p-10 max-w-[1400px] mx-auto space-y-10">
                {/* Navigation & Actions */}
                <div className="flex items-center justify-between">
                    <button onClick={() => window.location.href = basePath} className="group flex items-center gap-3 text-sm font-black text-gray-400 hover:text-gray-900 transition-all uppercase tracking-widest">
                        <div className="p-2 rounded-xl group-hover:bg-gray-100 transition-colors">
                            <ChevronLeft size={20} />
                        </div>
                        <span>Back to Registry</span>
                    </button>
                    
                    <div className="flex items-center gap-3">
                        <button 
                            onClick={() => window.location.href = `${basePath}/edit/${investor.id}`}
                            className="flex items-center gap-2 px-6 py-3 bg-white border border-gray-200 text-gray-700 rounded-2xl font-black text-xs hover:bg-gray-50 transition-all shadow-sm uppercase tracking-widest"
                        >
                            <Edit2 size={16} />
                            <span>Modify Profile</span>
                        </button>
                    </div>
                </div>

                {/* Profile Identity Card */}
                <div className="bg-white rounded-[3rem] border border-gray-100 shadow-2xl shadow-emerald-100/20 p-12 relative overflow-hidden">
                    <div className="absolute top-0 right-0 w-64 h-64 bg-emerald-50 rounded-full blur-3xl -mr-32 -mt-32 opacity-50"></div>
                    
                    <div className="relative flex flex-col md:flex-row items-center gap-10">
                        <div className="w-32 h-32 bg-[#111827] rounded-[2.5rem] flex items-center justify-center text-white text-4xl font-black border-4 border-gray-50 shadow-2xl rotate-3">
                            {initials}
                        </div>
                        
                        <div className="flex-1 space-y-4 text-center md:text-left">
                            <div className="space-y-1">
                                <div className="flex items-center justify-center md:justify-start gap-4">
                                    <h1 className="text-4xl font-black text-[#111827] tracking-tighter uppercase italic">{investor.name}</h1>
                                    <span className="px-4 py-1.5 bg-emerald-50 text-emerald-600 border border-emerald-100 rounded-full text-[10px] font-black uppercase tracking-widest">Active Investor</span>
                                </div>
                                <div className="flex items-center justify-center md:justify-start gap-6 text-[#98A2B3] text-[11px] font-black uppercase tracking-[0.2em]">
                                    <div className="flex items-center gap-1.5">
                                        <Building size={14} className="text-gray-400" />
                                        {investor.applicable_to_all_branches ? "Global Portfolio" : `${investor.branches?.length || 0} Branches`}
                                    </div>
                                    <div className="flex items-center gap-1.5">
                                        <Calendar size={14} className="text-gray-400" />
                                        Since {new Date(investor.investment_date).toLocaleDateString()}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4 w-full md:w-auto">
                            <div className="bg-gray-50/50 p-6 rounded-3xl border border-gray-100 text-center space-y-1">
                                <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Total Capital</p>
                                <p className="text-xl font-black text-gray-900">{parseFloat(investor.investment_amount).toLocaleString()} <span className="text-[10px]">AED</span></p>
                            </div>
                            <div className="bg-emerald-50/30 p-6 rounded-3xl border border-emerald-50 text-center space-y-1">
                                <p className="text-[10px] font-black text-emerald-600 uppercase tracking-widest">ROI Yielded</p>
                                <p className="text-xl font-black text-emerald-700">{totalPayouts.toLocaleString()} <span className="text-[10px]">AED</span></p>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Tabs & Content */}
                <div className="space-y-8">
                    <div className="flex items-center gap-12 border-b border-gray-100">
                        {['Overview', 'ROI Payouts', 'Monthly Status'].map(tab => (
                            <button
                                key={tab}
                                onClick={() => setActiveTab(tab)}
                                className={`pb-4 text-xs font-black uppercase tracking-[0.2em] transition-all relative ${
                                    activeTab === tab 
                                    ? 'text-emerald-600' 
                                    : 'text-gray-400 hover:text-gray-600'
                                }`}
                            >
                                {tab}
                                {activeTab === tab && <div className="absolute bottom-0 left-0 right-0 h-1 bg-emerald-500 rounded-full"></div>}
                            </button>
                        ))}
                    </div>

                    {activeTab === 'Overview' && (
                        <div className="grid grid-cols-3 gap-8 animate-in fade-in slide-in-from-bottom-2 duration-500">
                            <div className="col-span-2 space-y-8">
                                <div className="bg-white rounded-[2.5rem] border border-gray-100 shadow-sm overflow-hidden">
                                    <div className="p-8 border-b border-gray-50 flex items-center justify-between">
                                        <div className="flex items-center gap-3">
                                            <div className="p-2 bg-blue-50 text-blue-600 rounded-xl font-black">
                                                <TrendingUp size={20} />
                                            </div>
                                            <h2 className="text-lg font-black text-[#111827] uppercase italic">Investment Terms</h2>
                                        </div>
                                    </div>
                                    <div className="p-10 grid grid-cols-2 gap-y-12">
                                        <div className="space-y-2">
                                            <p className="text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">
                                                {investor.roi_type === 'Percentage' ? 'ROI Interest' : 'Fixed ROI'}
                                            </p>
                                            <div className="flex items-end gap-2">
                                                <p className="text-3xl font-black text-gray-900">
                                                    {investor.roi_value}
                                                    {investor.roi_type === 'Percentage' ? '%' : ' AED'}
                                                </p>
                                                <p className="text-xs font-bold text-gray-400 pb-1 mb-1 uppercase bg-gray-50 px-2 py-0.5 rounded-md">PER {investor.roi_period || 'MONTH'}</p>
                                            </div>
                                        </div>
                                        <div className="col-span-2 space-y-4">
                                            <p className="text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Strategic Allocation</p>
                                            <div className="flex flex-wrap gap-2">
                                                {investor.applicable_to_all_branches ? (
                                                    <div className="px-5 py-2.5 bg-[#111827] text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] flex items-center gap-2">
                                                        <Shield size={14} className="text-emerald-400" />
                                                        Organization Wide Equity
                                                    </div>
                                                ) : (
                                                    investor.branches?.map(branch => (
                                                        <div key={branch.id} className="px-5 py-2.5 bg-gray-50 text-gray-600 border border-gray-100 rounded-2xl text-[10px] font-black uppercase tracking-[0.2em]">
                                                            {branch.name}
                                                        </div>
                                                    ))
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="space-y-8">
                                <div className="bg-white rounded-[2.5rem] border border-gray-100 shadow-sm overflow-hidden min-h-[300px]">
                                    <div className="p-8 border-b border-gray-50 flex items-center gap-3">
                                        <div className="p-2 bg-amber-50 text-amber-600 rounded-xl font-black">
                                            <Shield size={20} />
                                        </div>
                                        <h2 className="text-lg font-black text-[#111827] uppercase italic tracking-tight">Security & Docs</h2>
                                    </div>
                                    <div className="p-8 flex flex-col items-center justify-center text-center space-y-6">
                                        {investor.security_proof_document ? (
                                            <div className="group w-full p-8 bg-gray-50 rounded-[2rem] border border-gray-100 flex flex-col items-center gap-4 hover:bg-white hover:border-blue-200 transition-all cursor-pointer" onClick={() => setIsPreviewOpen(true)}>
                                                <div className="w-20 h-20 bg-white shadow-xl rounded-3xl flex items-center justify-center text-blue-600 group-hover:scale-110 transition-transform">
                                                    <FileText size={40} />
                                                </div>
                                                <div className="space-y-1">
                                                    <p className="text-sm font-black text-gray-900 uppercase italic">Security Proof</p>
                                                    <p className="text-[10px] font-black text-blue-500 uppercase tracking-widest">Click to View</p>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="space-y-4 opacity-50">
                                                <div className="w-20 h-20 bg-gray-50 rounded-3xl flex items-center justify-center text-gray-300 mx-auto">
                                                    <FileText size={40} />
                                                </div>
                                                <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">No Document provided</p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {activeTab === 'ROI Payouts' && (
                        <div className="bg-white rounded-[3rem] border border-gray-100 shadow-sm overflow-hidden animate-in fade-in slide-in-from-bottom-2 duration-500">
                            <div className="p-10 border-b border-gray-50 flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                    <div className="p-3 bg-emerald-500 shadow-lg shadow-emerald-100 rounded-2xl text-white font-black">
                                        <Wallet size={24} />
                                    </div>
                                    <div>
                                        <h2 className="text-xl font-black text-[#111827] uppercase italic">Distribution History</h2>
                                        <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Total ROI Settled: {totalPayouts.toLocaleString()} AED</p>
                                    </div>
                                </div>
                            </div>
                            <div className="overflow-x-auto">
                                <table className="w-full">
                                    <thead>
                                        <tr className="bg-gray-50/50">
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Period</th>
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Amount (AED)</th>
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Payment Date</th>
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Method</th>
                                            <th className="px-10 py-6 text-right text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-50">
                                        {payouts.length > 0 ? (
                                            payouts.map(p => (
                                                <tr key={p.id} className="hover:bg-gray-50/30 transition-colors">
                                                    <td className="px-10 py-8 font-black text-gray-900 text-sm">{p.payout_month}</td>
                                                    <td className="px-10 py-8 font-black text-emerald-600 text-sm">{(parseFloat(p.amount) || 0).toLocaleString()} AED</td>
                                                    <td className="px-10 py-8 text-xs font-bold text-gray-400 uppercase tracking-widest">{new Date(p.payout_date).toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric' })}</td>
                                                    <td className="px-10 py-8 text-[10px] font-black text-gray-500 uppercase tracking-widest underline decoration-gray-200 decoration-2 underline-offset-4">{p.payment_method}</td>
                                                    <td className="px-10 py-8 text-right">
                                                        <span className="px-4 py-1.5 bg-emerald-50 text-emerald-600 border border-emerald-100 rounded-full text-[10px] font-black uppercase tracking-widest">
                                                            {p.status || 'Paid'}
                                                        </span>
                                                    </td>
                                                </tr>
                                            ))
                                        ) : (
                                            <tr>
                                                <td colSpan="5" className="px-10 py-24 text-center">
                                                    <div className="space-y-4 opacity-20">
                                                        <Wallet size={48} className="mx-auto" />
                                                        <p className="text-sm font-black uppercase italic italic tracking-widest">No ROI distributions recorded</p>
                                                    </div>
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}

                    {activeTab === 'Monthly Status' && (
                        <div className="bg-white rounded-[3rem] border border-gray-100 shadow-sm overflow-hidden animate-in fade-in slide-in-from-bottom-2 duration-500">
                             <div className="p-10 border-b border-gray-50 flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                    <div className="p-3 bg-amber-500 shadow-lg shadow-amber-100 rounded-2xl text-white font-black">
                                        <Clock size={24} />
                                    </div>
                                    <div>
                                        <h2 className="text-xl font-black text-[#111827] uppercase italic">Settlement Tracking</h2>
                                        <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Unpaid ROI Periods since Investment</p>
                                    </div>
                                </div>
                            </div>
                            <div className="overflow-x-auto">
                                <table className="w-full">
                                    <thead>
                                        <tr className="bg-gray-50/50">
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">ROI Period</th>
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Breakdown</th>
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Net Due</th>
                                            <th className="px-10 py-6 text-left text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Status</th>
                                            <th className="px-10 py-6 text-right text-[10px] font-black text-gray-400 uppercase tracking-[0.2em]">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-50">
                                        {roiStatus.filter(s => s.status === 'Pending' || s.status === 'Partial').length > 0 ? (
                                            roiStatus.filter(s => s.status === 'Pending' || s.status === 'Partial').map((s, idx) => (
                                                <tr key={idx} className="hover:bg-amber-50/20 transition-colors">
                                                    <td className="px-10 py-8 font-black text-gray-900 text-sm">{s.month}</td>
                                                    <td className="px-10 py-4">
                                                        <div className="space-y-1">
                                                            <p className="text-[10px] font-black text-gray-400 flex justify-between w-40">
                                                                <span>Base ROI:</span> <span>{(parseFloat(s.base_amount) || 0).toLocaleString()} AED</span>
                                                            </p>
                                                            {parseFloat(s.carry_from_previous) !== 0 && (
                                                                <p className={`text-[10px] font-black flex justify-between w-40 ${parseFloat(s.carry_from_previous) > 0 ? 'text-amber-500' : 'text-emerald-500'}`}>
                                                                    <span>Carry Over:</span> <span>{parseFloat(s.carry_from_previous) > 0 ? '+' : ''}{parseFloat(s.carry_from_previous).toLocaleString()} AED</span>
                                                                </p>
                                                            )}
                                                            {s.paid > 0 && (
                                                                <p className="text-[10px] font-black text-emerald-500 flex justify-between w-40">
                                                                    <span>Allocated:</span> <span>-{(parseFloat(s.paid) || 0).toLocaleString()} AED</span>
                                                                </p>
                                                            )}
                                                        </div>
                                                    </td>
                                                    <td className="px-10 py-8 font-black text-gray-900 text-sm">{(parseFloat(s.amount) || 0).toLocaleString()} AED</td>
                                                    <td className="px-10 py-8">
                                                        {s.status === 'Pending' ? (
                                                            <span className="px-4 py-1.5 bg-red-50 text-red-600 border border-red-100 rounded-full text-[10px] font-black uppercase tracking-widest leading-none inline-flex items-center gap-2">
                                                                <AlertCircle size={10} /> Pending
                                                            </span>
                                                        ) : (
                                                            <span className="px-4 py-1.5 bg-amber-50 text-amber-600 border border-amber-100 rounded-full text-[10px] font-black uppercase tracking-widest leading-none inline-flex items-center gap-2">
                                                                <AlertCircle size={10} /> Partially Paid
                                                            </span>
                                                        )}
                                                    </td>
                                                    <td className="px-10 py-8 text-right">
                                                        {s.can_settle ? (
                                                            <button 
                                                                onClick={() => setSettleModal({ 
                                                                    ...settleModal, 
                                                                    isOpen: true, 
                                                                    month: s.month, 
                                                                    amount: s.amount, 
                                                                    originalAmount: s.amount,
                                                                    baseAmount: s.base_amount,
                                                                    carryOver: s.carry_from_previous
                                                                })}
                                                                className="px-6 py-2.5 bg-[#111827] text-white rounded-xl text-[10px] font-black uppercase tracking-widest hover:scale-105 transition-all shadow-lg active:scale-95"
                                                            >
                                                                Settle Now
                                                            </button>
                                                        ) : (
                                                            <button 
                                                                disabled
                                                                title="Older months must be settled first."
                                                                className="px-6 py-2.5 bg-gray-100 text-gray-400 border border-gray-200 rounded-xl text-[10px] font-black uppercase tracking-widest cursor-not-allowed"
                                                            >
                                                                Locked
                                                            </button>
                                                        )}
                                                    </td>
                                                </tr>
                                            ))
                                        ) : (
                                            <tr>
                                                <td colSpan="5" className="px-10 py-24 text-center">
                                                    <div className="space-y-4">
                                                        <CheckCircle2 size={48} className="mx-auto text-emerald-500 opacity-40 hover:scale-110 transition-transform cursor-pointer" />
                                                        <p className="text-sm font-black uppercase tracking-widest text-emerald-600">All ROI Distributions Up to Date</p>
                                                    </div>
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </div>

                {/* Document Preview Modal */}
                {isPreviewOpen && (
                    <div className="fixed inset-0 z-[100] bg-black/90 backdrop-blur-md flex items-center justify-center p-10">
                        <div className="relative w-full max-w-5xl h-full flex flex-col items-center justify-center animate-in zoom-in-95 duration-200">
                             <button onClick={() => setIsPreviewOpen(false)} className="fixed top-8 right-8 p-3 bg-white/10 hover:bg-white/20 text-white rounded-full transition-all group">
                                <X size={24} className="group-hover:rotate-90 transition-transform" />
                            </button>
                             <div className="w-full h-full bg-white/5 rounded-[4rem] border border-white/10 p-4 relative flex items-center justify-center overflow-hidden">
                                {investor.security_proof_document.toLowerCase().endsWith('.pdf') ? (
                                    <iframe src={`/storage/${investor.security_proof_document}`} className="w-full h-full rounded-[3.5rem]" />
                                ) : (
                                    <img src={`/storage/${investor.security_proof_document}`} className="max-w-full max-h-full object-contain rounded-2xl shadow-2xl shadow-black/50" alt="Document Preview" />
                                )}
                            </div>
                            <div className="mt-8 flex gap-4">
                                <a 
                                    href={`/storage/${investor.security_proof_document}`} 
                                    download 
                                    className="px-8 py-3 bg-white text-gray-900 rounded-2xl font-black text-xs uppercase tracking-widest flex items-center gap-2 hover:scale-105 transition-all"
                                >
                                    <Download size={18} />
                                    Download Original
                                </a>
                            </div>
                        </div>
                    </div>
                )}

                {/* Settle ROI Modal */}
                {settleModal.isOpen && (
                    <div className="fixed inset-0 z-[90] bg-black/50 backdrop-blur-sm flex items-center justify-center p-4">
                        <div className="bg-white rounded-[3rem] w-full max-w-md shadow-2xl border border-gray-100 overflow-hidden animate-in fade-in zoom-in-95 duration-200">
                            <div className="p-10 border-b border-gray-50 flex items-center justify-between bg-gray-50/50">
                                <div className="space-y-1">
                                    <h3 className="text-2xl font-black text-[#111827] uppercase italic">ROI Settlement</h3>
                                    <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Distributing ROI for {settleModal.month}</p>
                                </div>
                                <button onClick={() => setSettleModal({...settleModal, isOpen: false})} className="p-3 hover:bg-white rounded-full transition-colors text-gray-400 border border-transparent hover:border-gray-100">
                                    <X size={20} />
                                </button>
                            </div>
                            
                            <form onSubmit={handleSettleROI} className="p-10 space-y-8">
                                <div className="space-y-6">
                                    <div className="bg-[#111827] p-8 rounded-[2rem] text-center space-y-4 relative overflow-hidden group">
                                        <TrendingUp className="absolute top-4 right-4 text-emerald-500/20 w-24 h-24 -rotate-12 transition-transform group-hover:scale-110" />
                                        
                                        <div className="space-y-1 relative z-10">
                                            <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">
                                                {parseFloat(settleModal.amount) !== parseFloat(settleModal.originalAmount) ? 'Adjusted Payout' : 'Calculated Payout'}
                                            </p>
                                            <div className="flex items-center justify-center gap-2">
                                                <input 
                                                    type="number"
                                                    className="bg-transparent border-b border-gray-700 text-4xl font-black text-white text-center w-32 outline-none focus:border-emerald-500 transition-colors"
                                                    value={settleModal.amount}
                                                    onChange={(e) => setSettleModal({...settleModal, amount: e.target.value})}
                                                />
                                                <span className="text-xs text-gray-500">AED</span>
                                            </div>
                                        </div>

                                        <div className="pt-4 border-t border-gray-800 space-y-2 relative z-10">
                                            <div className="flex justify-between text-[10px] font-black uppercase tracking-widest">
                                                <span className="text-gray-500">Base ROI:</span>
                                                <span className="text-gray-300">{parseFloat(settleModal.baseAmount).toLocaleString()} AED</span>
                                            </div>
                                            {parseFloat(settleModal.carryOver) !== 0 && (
                                                <div className="flex justify-between text-[10px] font-black uppercase tracking-widest">
                                                    <span className="text-gray-500">Carry Over:</span>
                                                    <span className={parseFloat(settleModal.carryOver) > 0 ? 'text-amber-500' : 'text-emerald-500'}>
                                                        {parseFloat(settleModal.carryOver) > 0 ? '+' : ''}{parseFloat(settleModal.carryOver).toLocaleString()} AED
                                                    </span>
                                                </div>
                                            )}
                                        </div>

                                        {parseFloat(settleModal.amount) !== parseFloat(settleModal.originalAmount) && (
                                            <p className="text-[9px] font-black text-amber-500 uppercase tracking-widest pt-2 relative z-10">Adjustment detected: Remarks required</p>
                                        )}
                                    </div>

                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-2">
                                            <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block pl-1">Settlement Date</label>
                                            <input 
                                                type="date"
                                                required
                                                className="w-full px-5 py-4 bg-gray-50 border border-gray-100 rounded-2xl outline-none focus:ring-4 focus:ring-emerald-500/10 focus:border-emerald-500 transition-all font-black text-sm"
                                                value={settleModal.date}
                                                onChange={(e) => setSettleModal({...settleModal, date: e.target.value})}
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block pl-1">Method</label>
                                            <select 
                                                className="w-full px-5 py-4 bg-gray-50 border border-gray-100 rounded-2xl outline-none focus:ring-4 focus:ring-emerald-500/10 focus:border-emerald-500 transition-all font-black text-[10px] tracking-widest uppercase appearance-none"
                                                value={settleModal.method}
                                                onChange={(e) => setSettleModal({...settleModal, method: e.target.value})}
                                            >
                                                <option value="Bank Transfer">Bank Transfer</option>
                                                <option value="Cash">Cash</option>
                                                <option value="Cheque">Cheque</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest block pl-1">
                                            Notes / Reference {parseFloat(settleModal.amount) !== parseFloat(settleModal.originalAmount) && <span className="text-red-500">*</span>}
                                        </label>
                                        <textarea 
                                            className={`w-full px-5 py-4 bg-gray-50 border ${parseFloat(settleModal.amount) !== parseFloat(settleModal.originalAmount) && !settleModal.remarks ? 'border-amber-200' : 'border-gray-100'} rounded-2xl outline-none focus:ring-4 focus:ring-emerald-500/10 focus:border-emerald-500 transition-all text-xs font-bold resize-none h-24 placeholder:text-gray-300`}
                                            placeholder={parseFloat(settleModal.amount) !== parseFloat(settleModal.originalAmount) ? "Reason for adjustment (Mandatory)" : "Optional remarks..."}
                                            value={settleModal.remarks}
                                            onChange={(e) => setSettleModal({...settleModal, remarks: e.target.value})}
                                        />
                                    </div>
                                </div>

                                <div className="flex gap-4 pt-4">
                                    <button 
                                        type="button"
                                        onClick={() => setSettleModal({...settleModal, isOpen: false})}
                                        className="flex-1 px-8 py-5 bg-gray-50 text-gray-400 rounded-[1.5rem] font-black text-xs uppercase tracking-widest hover:bg-gray-100 transition-all"
                                    >
                                        Dismiss
                                    </button>
                                    <button 
                                        type="submit"
                                        className="flex-[1.5] px-8 py-5 bg-emerald-600 text-white rounded-[1.5rem] font-black text-xs uppercase tracking-[0.2em] hover:scale-[1.02] active:scale-[0.98] transition-all shadow-xl shadow-emerald-100 flex items-center justify-center gap-2"
                                    >
                                        <CheckCircle2 size={18} />
                                        Confirm Pay
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </main>
        </>
    );
}
