import React, { useState, useEffect } from 'react';
import staffService from '../services/staffService';
import staffPaymentService from '../services/staffPaymentService';
import {
    DollarSign,
    Calendar,
    Users,
    Plus,
    Search,
    Filter,
    MoreHorizontal,
    CheckCircle,
    Clock,
    Trash2,
    X,
    Building,
    TrendingUp,
    FileText,
    ArrowDownLeft,
    Wallet
} from 'lucide-react';
import { clsx } from 'clsx';

const StaffPayments = () => {
    const [payments, setPayments] = useState([]);
    const [staffList, setStaffList] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isStatusModalOpen, setIsStatusModalOpen] = useState(false);
    const [selectedStaff, setSelectedStaff] = useState(null);
    const [selectedPayment, setSelectedPayment] = useState(null);

    // Form state for recording new work
    const [formData, setFormData] = useState({
        staffId: '',
        periodStart: '',
        periodEnd: '',
        amount: 0,
        calculationBreakdown: null,
        notes: ''
    });

    // Form state for marking as paid
    const [statusData, setStatusData] = useState({
        status: 'Paid',
        paymentDate: new Date().toISOString().split('T')[0],
        paymentMethod: 'M-Pesa',
        paymentReference: ''
    });

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setLoading(true);
        try {
            const [pRes, sRes] = await Promise.all([
                staffPaymentService.getAll(),
                staffService.getAll()
            ]);
            setPayments(pRes.data);
            setStaffList(sRes.data.filter(s => s.staffType === 'Temporary'));
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleStaffChange = (e) => {
        const staffId = e.target.value;
        const staff = staffList.find(s => s.id === staffId);
        setSelectedStaff(staff);

        let initialBreakdown = null;
        if (staff) {
            if (staff.payType === 'Daily') {
                initialBreakdown = { days: 0, rate: staff.dailyRate };
            } else if (staff.payType === 'Sales') {
                const rates = staff.buildingRates ? JSON.parse(staff.buildingRates) : [];
                initialBreakdown = rates.map(r => ({
                    building: r.building,
                    fullRate: r.fullRate || r.rate || 0,
                    halfRate: r.halfRate || 0,
                    fullSales: 0,
                    halfSales: 0
                }));
            }
        }

        setFormData({
            ...formData,
            staffId,
            calculationBreakdown: initialBreakdown,
            amount: 0
        });
    };

    const calculateTotal = (breakdown, staff) => {
        if (!staff || !breakdown) return 0;
        let total = 0;
        if (staff.payType === 'Daily') {
            total = (breakdown.days || 0) * (breakdown.rate || 0);
        } else if (staff.payType === 'Sales') {
            total = breakdown.reduce((acc, curr) => {
                const fullTotal = (curr.fullSales || 0) * (curr.fullRate || 0);
                const halfTotal = (curr.halfSales || 0) * (curr.halfRate || 0);
                return acc + fullTotal + halfTotal;
            }, 0);
        }
        return total;
    };

    const updateBreakdown = (field, value, index = null) => {
        let newBreakdown;
        if (selectedStaff.payType === 'Daily') {
            newBreakdown = { ...formData.calculationBreakdown, [field]: value };
        } else {
            newBreakdown = [...formData.calculationBreakdown];
            newBreakdown[index] = { ...newBreakdown[index], [field]: value };
        }

        const newTotal = calculateTotal(newBreakdown, selectedStaff);
        setFormData({
            ...formData,
            calculationBreakdown: newBreakdown,
            amount: newTotal
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await staffPaymentService.create({
                ...formData,
                calculationBreakdown: JSON.stringify(formData.calculationBreakdown)
            });
            fetchData();
            setIsModalOpen(false);
        } catch (err) {
            alert(err.response?.data?.error || 'Failed to record work');
        }
    };

    const handleUpdateStatus = async (e) => {
        e.preventDefault();
        try {
            await staffPaymentService.updateStatus(selectedPayment.id, statusData);
            fetchData();
            setIsStatusModalOpen(false);
        } catch (err) {
            alert(err.response?.data?.error || 'Failed to update status');
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Delete this payment record? This will remove it from the records.')) {
            try {
                await staffPaymentService.delete(id);
                fetchData();
            } catch (err) {
                alert('Failed to delete');
            }
        }
    };

    return (
        <div className="space-y-10 animate-slide-up pb-20">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-emerald-500 rounded-2xl text-white shadow-xl shadow-emerald-500/20 shrink-0">
                        <DollarSign className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight leading-none truncate">Casual Staff Payments</h1>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest whitespace-nowrap">Staff Payments</span>
                            <div className="w-1 h-1 bg-slate-300 dark:bg-slate-700 rounded-full shrink-0"></div>
                            <span className="text-[10px] font-black text-emerald-500 uppercase tracking-widest whitespace-nowrap">{payments.length} Records</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={() => {
                        setFormData({
                            staffId: '',
                            periodStart: '',
                            periodEnd: '',
                            amount: 0,
                            calculationBreakdown: null,
                            notes: ''
                        });
                        setSelectedStaff(null);
                        setIsModalOpen(true);
                    }}
                    className="btn-primary !bg-emerald-600 !border-emerald-600 hover:!bg-emerald-700 flex items-center justify-center gap-2 px-8 w-full md:w-auto h-12 lg:h-14"
                >
                    <Plus className="w-4 h-4 shrink-0" />
                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Record Work</span>
                </button>
            </div>

            {/* Main Table Card */}
            <div className="premium-card overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full text-left">
                        <thead>
                            <tr className="bg-slate-50/50 dark:bg-slate-900/40 border-b border-slate-100 dark:border-slate-800">
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Employee Name</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Work Details</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Total Amount</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Payment Status</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800/50">
                            {loading ? (
                                <tr>
                                    <td colSpan="5" className="p-24 text-center">
                                        <div className="flex flex-col items-center gap-4">
                                            <div className="w-12 h-12 border-4 border-emerald-500/20 border-t-emerald-500 rounded-full animate-spin"></div>
                                            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading payments...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : payments.length === 0 ? (
                                <tr>
                                    <td colSpan="5" className="p-24 text-center">
                                        <div className="max-w-xs mx-auto space-y-4">
                                            <div className="w-16 h-16 bg-slate-50 dark:bg-slate-900 rounded-3xl flex items-center justify-center mx-auto">
                                                <DollarSign className="w-8 h-8 text-slate-200 dark:text-slate-800" />
                                            </div>
                                            <h3 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">No Payments Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Add your first staff payment record to begin tracking.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                payments.map(p => (
                                    <tr key={p.id} className="group hover:bg-emerald-50/10 transition-all duration-300">
                                        <td className="px-8 py-6">
                                            <div className="flex flex-col">
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{p.Staff?.fullName}</span>
                                                <div className="flex items-center gap-1.5 mt-1">
                                                    <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest flex items-center gap-1">
                                                        <Calendar className="w-3 h-3" /> {new Date(p.periodStart).toLocaleDateString()}
                                                    </span>
                                                    <ArrowDownLeft className="w-2 h-2 text-slate-300" />
                                                    <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">{new Date(p.periodEnd).toLocaleDateString()}</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            <div className="max-w-xs">
                                                {p.Staff?.payType === 'Daily' ? (
                                                    <span className="px-2 py-0.5 bg-slate-100 dark:bg-slate-800 rounded-md border border-slate-200 dark:border-slate-700 text-[10px] font-black text-slate-500 dark:text-slate-400 uppercase tracking-tight">
                                                        {JSON.parse(p.calculationBreakdown || '{}').days} Days Worked
                                                    </span>
                                                ) : (
                                                    <div className="flex flex-wrap gap-1.5">
                                                        {JSON.parse(p.calculationBreakdown || '[]').map((b, i) => (
                                                            <span key={i} className="bg-slate-50 dark:bg-slate-900 px-2 py-0.5 rounded-md border border-slate-100 dark:border-slate-800 text-[8px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-tighter">
                                                                {b.building}: {b.fullSales}F / {b.halfSales}H
                                                            </span>
                                                        ))}
                                                    </div>
                                                )}
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">
                                                <span className="text-[9px] mr-1 opacity-60">KES</span>
                                                {parseFloat(p.amount).toLocaleString()}
                                            </span>
                                        </td>
                                        <td className="px-8 py-6">
                                            <div className={clsx(
                                                "inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border transition-all duration-300",
                                                p.status === 'Paid'
                                                    ? "bg-emerald-500/10 text-emerald-500 border-emerald-500/20 shadow-sm shadow-emerald-500/5"
                                                    : "bg-amber-500/10 text-amber-500 border-amber-500/20 shadow-sm shadow-amber-500/5"
                                            )}>
                                                {p.status === 'Paid' ? <CheckCircle className="w-3.5 h-3.5" /> : <Clock className="w-3.5 h-3.5" />}
                                                {p.status}
                                            </div>
                                        </td>
                                        <td className="px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-1 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 transition-all lg:translate-x-2 lg:group-hover:translate-x-0 duration-300">
                                                {p.status === 'Pending' && (
                                                    <button
                                                        onClick={() => {
                                                            setSelectedPayment(p);
                                                            setIsStatusModalOpen(true);
                                                        }}
                                                        className="p-2.5 text-emerald-500 hover:bg-emerald-500/10 rounded-xl transition-all h-10 w-10 flex items-center justify-center shrink-0"
                                                        title="Settle Payrun"
                                                    >
                                                        <CheckCircle className="w-4 h-4 shrink-0" />
                                                    </button>
                                                )}
                                                <button
                                                    onClick={() => handleDelete(p.id)}
                                                    className="p-2.5 text-slate-300 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-all h-10 w-10 flex items-center justify-center shrink-0"
                                                    title="Delete Record"
                                                >
                                                    <Trash2 className="w-4 h-4 shrink-0" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Record Work Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
                    <div className="bg-white dark:bg-slate-900 w-full max-w-2xl rounded-[2.5rem] p-10 shadow-4xl relative overflow-hidden premium-card max-h-[90vh] flex flex-col">
                        <div className="absolute top-0 left-0 w-full h-2 bg-emerald-500 shadow-lg shadow-emerald-500/20" />

                        <div className="flex items-center gap-5 mb-8 shrink-0">
                            <div className="p-4 bg-emerald-500 rounded-2xl text-white shadow-xl shadow-emerald-500/20">
                                <DollarSign className="w-7 h-7" />
                            </div>
                            <div>
                                <h2 className="text-2xl font-black text-slate-800 dark:text-white tracking-tight">Record Staff Work</h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Track sales and performance</p>
                            </div>
                        </div>

                        <form onSubmit={handleSubmit} className="space-y-8 overflow-y-auto pr-2 custom-scrollbar">
                            <div className="grid grid-cols-2 gap-x-6 gap-y-8">
                                <div className="col-span-2 space-y-2">
                                    <label className="premium-label">Staff Member</label>
                                    <div className="relative group">
                                        <Users className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-emerald-500 transition-colors" />
                                        <select
                                            required
                                            className="premium-input !pl-12 !appearance-auto"
                                            value={formData.staffId}
                                            onChange={handleStaffChange}
                                        >
                                            <option value="">Select Staff Member...</option>
                                            {staffList.map(s => (
                                                <option key={s.id} value={s.id}>{s.fullName} ({s.payType})</option>
                                            ))}
                                        </select>
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <label className="premium-label">Start Date</label>
                                    <input
                                        type="date"
                                        required
                                        className="premium-input"
                                        value={formData.periodStart}
                                        onChange={(e) => setFormData({ ...formData, periodStart: e.target.value })}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <label className="premium-label">End Date</label>
                                    <input
                                        type="date"
                                        required
                                        className="premium-input"
                                        value={formData.periodEnd}
                                        onChange={(e) => setFormData({ ...formData, periodEnd: e.target.value })}
                                    />
                                </div>

                                <div className="col-span-2 space-y-4">
                                    <div className="flex items-center gap-3">
                                        <div className="h-px bg-slate-100 dark:bg-slate-800 flex-1" />
                                        <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Payment Calculation</span>
                                        <div className="h-px bg-slate-100 dark:bg-slate-800 flex-1" />
                                    </div>

                                    {selectedStaff ? (
                                        <div className="space-y-6 animate-in slide-in-from-bottom-4 duration-500">
                                            <div className="p-8 bg-emerald-500/5 dark:bg-emerald-500/10 rounded-[2rem] border border-emerald-500/10 flex justify-between items-center group">
                                                <div>
                                                    <span className="text-[10px] font-black text-emerald-500 uppercase tracking-widest block mb-1">Total Payment</span>
                                                    <p className="text-3xl font-black text-emerald-600 dark:text-emerald-400 tracking-tighter">
                                                        <span className="text-sm not-italic opacity-60 mr-2">KES</span>
                                                        {parseFloat(formData.amount).toLocaleString()}
                                                    </p>
                                                </div>
                                                <div className="p-4 bg-emerald-500 text-white rounded-[1.5rem] shadow-xl shadow-emerald-500/20 group-hover:scale-110 transition-transform">
                                                    <TrendingUp className="w-6 h-6" />
                                                </div>
                                            </div>

                                            {selectedStaff.payType === 'Daily' && (
                                                <div className="space-y-2">
                                                    <label className="premium-label">Days Worked</label>
                                                    <div className="relative group">
                                                        <Calendar className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-emerald-500 transition-colors" />
                                                        <input
                                                            type="number"
                                                            className="premium-input !pl-12 !font-black !text-xl tracking-tight"
                                                            value={formData.calculationBreakdown?.days || ''}
                                                            onChange={(e) => updateBreakdown('days', e.target.value)}
                                                            placeholder="0"
                                                        />
                                                    </div>
                                                </div>
                                            )}

                                            {selectedStaff.payType === 'Sales' && (
                                                <div className="grid grid-cols-1 gap-4 max-h-[250px] overflow-y-auto pr-2 custom-scrollbar">
                                                    {formData.calculationBreakdown?.map((b, idx) => (
                                                        <div key={idx} className="p-6 bg-white dark:bg-slate-800 rounded-2xl border border-slate-100 dark:border-slate-700 space-y-4">
                                                            <div className="flex items-center gap-2 text-emerald-500">
                                                                <Building className="w-4 h-4" />
                                                                <span className="text-[10px] font-black uppercase tracking-widest">{b.building}</span>
                                                            </div>
                                                            <div className="grid grid-cols-2 gap-4">
                                                                <div className="space-y-1">
                                                                    <span className="text-[8px] font-black text-slate-400 uppercase tracking-widest ml-1">Full Sales</span>
                                                                    <input
                                                                        type="number"
                                                                        className="w-full px-4 py-2 bg-slate-50 dark:bg-slate-900 border border-slate-100 dark:border-slate-800 rounded-xl text-xs font-black tracking-tighter focus:border-emerald-500 outline-none"
                                                                        value={b.fullSales}
                                                                        onChange={(e) => updateBreakdown('fullSales', e.target.value, idx)}
                                                                    />
                                                                </div>
                                                                <div className="space-y-1">
                                                                    <span className="text-[8px] font-black text-slate-400 uppercase tracking-widest ml-1">Half Sales</span>
                                                                    <input
                                                                        type="number"
                                                                        className="w-full px-4 py-2 bg-slate-50 dark:bg-slate-900 border border-slate-100 dark:border-slate-800 rounded-xl text-xs font-black tracking-tighter focus:border-emerald-500 outline-none"
                                                                        value={b.halfSales}
                                                                        onChange={(e) => updateBreakdown('halfSales', e.target.value, idx)}
                                                                    />
                                                                </div>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            )}
                                        </div>
                                    ) : (
                                        <div className="p-12 text-center border-2 border-dashed border-slate-100 dark:border-slate-800 rounded-[2.5rem]">
                                            <div className="w-16 h-16 bg-slate-50 dark:bg-slate-900 rounded-3xl flex items-center justify-center mx-auto mb-4">
                                                <Info className="w-8 h-8 text-slate-200 dark:text-slate-800" />
                                            </div>
                                            <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest leading-relaxed">Select a staff member<br />to calculate payment.</p>
                                        </div>
                                    )}
                                </div>
                            </div>

                            <div className="flex gap-4 pt-8 border-t border-slate-100 dark:border-slate-800 shrink-0">
                                <button
                                    type="button"
                                    onClick={() => setIsModalOpen(false)}
                                    className="flex-1 py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest hover:bg-slate-50 dark:hover:bg-slate-900 rounded-2xl transition-all"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    className="btn-primary !bg-emerald-600 !border-emerald-600 hover:!bg-emerald-700 flex-[1.5] py-4 shadow-2xl flex items-center justify-center gap-2"
                                >
                                    <CheckCircle className="w-4 h-4" />
                                    <span>Save Payment</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Mark as Paid Modal */}
            {isStatusModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
                    <div className="bg-white dark:bg-slate-900 w-full max-w-md rounded-[2.5rem] p-10 shadow-4xl relative overflow-hidden premium-card">
                        <div className="absolute top-0 left-0 w-full h-2 bg-emerald-500 shadow-lg shadow-emerald-500/20" />

                        <div className="flex items-center gap-5 mb-8">
                            <div className="p-4 bg-emerald-500 rounded-2xl text-white shadow-xl shadow-emerald-500/20">
                                <Wallet className="w-7 h-7" />
                            </div>
                            <div>
                                <h2 className="text-2xl font-black text-slate-800 dark:text-white tracking-tight">Confirm Payment</h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Confirm payment details</p>
                            </div>
                        </div>

                        <form onSubmit={handleUpdateStatus} className="space-y-6">
                            <div className="space-y-2">
                                <label className="premium-label">Payment Method</label>
                                <select
                                    className="premium-input !appearance-auto"
                                    value={statusData.paymentMethod}
                                    onChange={(e) => setStatusData({ ...statusData, paymentMethod: e.target.value })}
                                >
                                    <option>M-Pesa</option>
                                    <option>Bank Transfer</option>
                                    <option>Digital Wallet</option>
                                    <option>Cash</option>
                                </select>
                            </div>
                            <div className="space-y-2">
                                <label className="premium-label">Reference/Transaction ID</label>
                                <div className="relative group">
                                    <FileText className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-emerald-500 transition-colors" />
                                    <input
                                        type="text"
                                        required
                                        className="premium-input !pl-12 font-black uppercase tracking-widest"
                                        placeholder="T8F2...PR9"
                                        value={statusData.paymentReference}
                                        onChange={(e) => setStatusData({ ...statusData, paymentReference: e.target.value })}
                                    />
                                </div>
                            </div>
                            <button
                                type="submit"
                                className="w-full py-5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl text-[11px] font-black uppercase tracking-[0.2em] shadow-2xl shadow-emerald-500/30 transition-all flex items-center justify-center gap-3"
                            >
                                <CheckCircle className="w-4 h-4" />
                                Confirm Payment
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

const Info = (props) => (
    <svg {...props} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><path d="M12 16v-4" /><path d="M12 8h.01" /></svg>
);

export default StaffPayments;
