import React, { useState, useEffect } from 'react';
import payrollService from '../services/payrollService';
import { BadgeDollarSign, Users, Calendar, PlayCircle, CheckCircle, Plus, Edit2, Trash2, UserPlus, Info, Wallet, Clock, TrendingUp, Building } from 'lucide-react';
import settingsService from '../services/settingsService';
import { useNavigate } from 'react-router-dom';
import { clsx } from 'clsx';

const StatCard = ({ title, value, icon: Icon, colorClass, subtitle }) => (
    <div className="premium-card p-4 sm:p-6 group hover:scale-[1.02] transition-all duration-500 flex items-center gap-4 sm:gap-5">
        <div className={clsx("p-3 sm:p-4 rounded-2xl text-white shadow-xl transition-transform group-hover:rotate-12 duration-500 shrink-0", colorClass)}>
            <Icon className="w-5 h-5 sm:w-6 sm:h-6 shrink-0" />
        </div>
        <div className="min-w-0">
            <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] leading-tight mb-1 truncate">{title}</p>
            <h3 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight leading-tight truncate">
                {value}
            </h3>
            {subtitle && <p className="text-[8px] sm:text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest mt-0.5 truncate">{subtitle}</p>}
        </div>
    </div>
);

const PayrollDashboard = () => {
    const navigate = useNavigate();
    const [runs, setRuns] = useState([]);
    const [employees, setEmployees] = useState([]);
    const [loading, setLoading] = useState(true);
    const [currency, setCurrency] = useState('KES');

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

    const fetchData = async () => {
        setLoading(true);
        try {
            const [runRes, empRes, settingsRes] = await Promise.all([
                payrollService.getRuns(),
                payrollService.getEmployees(),
                settingsService.getSettings()
            ]);
            setRuns(runRes.data);
            setEmployees(empRes.data);
            setCurrency(settingsRes.data.DEFAULT_CURRENCY || 'KES');
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleRunPayroll = async () => {
        const month = prompt('Enter Month (YYYY-MM):', new Date().toISOString().slice(0, 7));
        if (month) {
            try {
                await payrollService.createRun({ month });
                fetchData();
            } catch (err) {
                alert(err.response?.data?.error || 'Error creating run');
            }
        }
    };

    const handleMarkPaid = async (id) => {
        if (window.confirm('Mark this payroll as PAID? This will create a finance expense record.')) {
            try {
                await payrollService.markPaid(id);
                fetchData();
            } catch (err) {
                alert('Error processing payment');
            }
        }
    };

    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">
                        <BadgeDollarSign 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">Staff Payroll</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">Permanent Payroll</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">System Active</span>
                        </div>
                    </div>
                </div>
                <div className="flex flex-col sm:flex-row items-center gap-3 w-full md:w-auto">
                    <button
                        onClick={() => navigate('/staff')}
                        className="btn-secondary flex items-center justify-center gap-2 px-6 py-3 w-full sm:w-auto h-12 lg:h-14"
                    >
                        <Users className="w-4 h-4 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Staff List</span>
                    </button>
                    <button
                        onClick={handleRunPayroll}
                        className="btn-primary !bg-emerald-600 !border-emerald-600 hover:!bg-emerald-700 flex items-center justify-center gap-2 px-8 py-3 w-full sm:w-auto h-12 lg:h-14"
                    >
                        <PlayCircle className="w-4 h-4 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Start Payroll</span>
                    </button>
                </div>
            </div>

            {/* Metrics Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
                <StatCard
                    title="Staff Members"
                    value={employees.length}
                    icon={Users}
                    colorClass="bg-primary shadow-primary/20"
                    subtitle="Active Staff"
                />
                <StatCard
                    title="Current Month"
                    value={runs[0]?.month || 'N/A'}
                    icon={Calendar}
                    colorClass="bg-blue-500 shadow-blue-500/20"
                    subtitle="Last Paid Month"
                />
                <div className="premium-card p-4 sm:p-6 flex flex-col justify-center bg-amber-500/5 dark:bg-amber-500/10 border-amber-500/20 border col-span-1 sm:col-span-2 lg:col-span-1">
                    <div className="flex items-start gap-3 text-amber-600 dark:text-amber-500">
                        <Info className="w-5 h-5 shrink-0" />
                        <p className="text-[10px] font-black uppercase tracking-widest leading-relaxed">
                            Staff designated as "Permanent" are automatically included in this payroll module.
                        </p>
                    </div>
                </div>
            </div>

            {/* Payroll History */}
            <div className="premium-card overflow-hidden">
                <div className="p-4 sm:p-6 border-b border-slate-100 dark:border-slate-800/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-900/40">
                    <div className="flex items-center gap-3">
                        <Clock className="w-4 h-4 text-emerald-500 shrink-0" />
                        <h3 className="font-black text-slate-700 dark:text-slate-300 uppercase text-[10px] tracking-widest">Payroll History</h3>
                    </div>
                </div>
                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[700px]">
                        <thead>
                            <tr className="bg-slate-50/50 dark:bg-slate-900/40 border-b border-slate-100 dark:border-slate-800">
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Month/Period</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Total Paid</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Status</th>
                                <th className="px-6 sm: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="4" 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 payroll history...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : runs.length === 0 ? (
                                <tr>
                                    <td colSpan="4" className="p-12 sm: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 shrink-0">
                                                <Wallet className="w-8 h-8 text-slate-200 dark:text-slate-800 shrink-0" />
                                            </div>
                                            <h3 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">No Payroll Records Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Start your first payroll cycle to begin tracking.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                runs.map(run => (
                                    <tr key={run.id} className="group hover:bg-emerald-50/10 transition-all duration-300">
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex items-center gap-3">
                                                <div className="w-10 h-10 bg-white dark:bg-slate-800 rounded-xl flex items-center justify-center text-primary shadow-sm border border-slate-100 dark:border-slate-800 transition-transform group-hover:scale-110 shrink-0">
                                                    <Calendar className="w-5 h-5 shrink-0" />
                                                </div>
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight uppercase tracking-widest truncate">{run.month}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tighter whitespace-nowrap">
                                                <span className="text-[9px] mr-1 opacity-60 uppercase shrink-0">{currency}</span>
                                                {Number(run.totalPaid).toLocaleString()}
                                            </span>
                                        </td>
                                        <td className="px-6 sm: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 whitespace-nowrap",
                                                run.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"
                                            )}>
                                                {run.status === 'Paid' ? <CheckCircle className="w-3.5 h-3.5 shrink-0" /> : <Clock className="w-3.5 h-3.5 shrink-0" />}
                                                {run.status}
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-2 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 transition-all lg:translate-x-2 lg:group-hover:translate-x-0 duration-300">
                                                {run.status !== 'Paid' ? (
                                                    <button
                                                        onClick={() => handleMarkPaid(run.id)}
                                                        className="px-5 py-2.5 bg-primary/10 hover:bg-primary text-primary hover:text-white rounded-xl text-[10px] font-black uppercase tracking-[0.2em] transition-all duration-300 hover:scale-105 active:scale-95 whitespace-nowrap h-10 flex items-center justify-center shrink-0"
                                                    >
                                                        Mark as Paid
                                                    </button>
                                                ) : (
                                                    <div className="flex items-center gap-2 px-5 py-2.5 bg-emerald-500/5 text-emerald-500 rounded-xl text-[10px] font-black uppercase tracking-widest border border-emerald-500/10 whitespace-nowrap h-10 shrink-0">
                                                        <CheckCircle className="w-3.5 h-3.5 shrink-0" />
                                                        Verified
                                                    </div>
                                                )}
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Enrolled Staff */}
            <div className="premium-card overflow-hidden">
                <div className="p-4 sm:p-6 border-b border-slate-100 dark:border-slate-800/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-900/40">
                    <div className="flex items-center gap-3">
                        <Users className="w-4 h-4 text-primary shrink-0" />
                        <h3 className="font-black text-slate-700 dark:text-slate-300 uppercase text-[10px] tracking-widest">Active Staff Members</h3>
                    </div>
                </div>
                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[700px]">
                        <thead>
                            <tr className="bg-slate-50/50 dark:bg-slate-900/40 border-b border-slate-100 dark:border-slate-800">
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Employee Name</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Basic Salary</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Allowance</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Gross Total</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800/50">
                            {employees.map(emp => (
                                <tr key={emp.id} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-all duration-300">
                                    <td className="px-6 sm:px-8 py-6">
                                        <div className="flex flex-col min-w-0">
                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate">{emp.fullName}</span>
                                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest mt-0.5 truncate">{emp.position}</span>
                                        </div>
                                    </td>
                                    <td className="px-6 sm:px-8 py-6">
                                        <span className="text-sm font-black text-slate-800 dark:text-white tracking-tighter whitespace-nowrap">
                                            <span className="text-[9px] mr-1 opacity-40 uppercase shrink-0">{currency}</span>
                                            {Number(emp.monthlySalary).toLocaleString()}
                                        </span>
                                    </td>
                                    <td className="px-6 sm:px-8 py-6">
                                        <span className="text-sm font-black text-slate-400 dark:text-slate-500 tracking-tighter whitespace-nowrap">
                                            <span className="text-[9px] mr-1 opacity-40 uppercase shrink-0">{currency}</span>
                                            {Number(emp.allowance).toLocaleString()}
                                        </span>
                                    </td>
                                    <td className="px-6 sm:px-8 py-6 text-right">
                                        <span className="text-sm font-black text-primary tracking-tighter transition-transform group-hover:scale-110 block origin-right duration-300 whitespace-nowrap">
                                            <span className="text-[9px] mr-1 opacity-60 uppercase shrink-0">{currency}</span>
                                            {(Number(emp.monthlySalary) + Number(emp.allowance)).toLocaleString()}
                                        </span>
                                    </td>
                                </tr>
                            ))}
                            {employees.length === 0 && !loading && (
                                <tr>
                                    <td colSpan="4" className="p-12 sm:p-24 text-center opacity-30 grayscale">
                                        <Users className="w-12 h-12 mx-auto mb-4 shrink-0" />
                                        <p className="text-[10px] font-black uppercase tracking-widest">No staff members found.</p>
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
};

export default PayrollDashboard;
