import React, { useState, useEffect } from 'react';
import staffService from '../services/staffService';
import { Plus, User, Mail, Phone, Edit2, Trash2, Search, Briefcase, DollarSign, Calendar, TrendingUp, Users, Building, X, CheckCircle, ArrowRight, Tag, Info, UserCircle } from 'lucide-react';
import settingsService from '../services/settingsService';
import { clsx } from 'clsx';

const StaffList = () => {
    const [staff, setStaff] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingStaff, setEditingStaff] = useState(null);
    const [formData, setFormData] = useState({
        fullName: '',
        position: '',
        email: '',
        phone: '',
        gender: '',
        staffType: 'Permanent',
        monthlySalary: '',
        allowance: '',
        dailyRate: '',
        payType: 'Daily',
        commissionPercentage: '',
        buildingRates: [],
        notes: ''
    });
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [currency, setCurrency] = useState('KES');
    const [searchTerm, setSearchTerm] = useState('');

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

    const fetchStaff = async () => {
        setLoading(true);
        try {
            const [staffRes, settingsRes] = await Promise.all([
                staffService.getAll(),
                settingsService.getSettings()
            ]);
            setStaff(staffRes.data);
            setCurrency(settingsRes.data.DEFAULT_CURRENCY || 'KES');
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleOpenModal = () => {
        setEditingStaff(null);
        setFormData({
            fullName: '',
            position: '',
            email: '',
            phone: '',
            gender: '',
            staffType: 'Permanent',
            monthlySalary: '',
            allowance: '',
            dailyRate: '',
            payType: 'Daily',
            commissionPercentage: '',
            buildingRates: [],
            notes: ''
        });
        setIsModalOpen(true);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setEditingStaff(null);
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value });
    };

    const addBuildingRate = () => {
        setFormData({
            ...formData,
            buildingRates: [...formData.buildingRates, { id: Date.now(), building: '', fullRate: '', halfRate: '' }]
        });
    };

    const removeBuildingRate = (id) => {
        setFormData({
            ...formData,
            buildingRates: formData.buildingRates.filter(r => r.id !== id)
        });
    };

    const updateBuildingRate = (id, field, value) => {
        setFormData({
            ...formData,
            buildingRates: formData.buildingRates.map(r =>
                r.id === id ? { ...r, [field]: value } : r
            )
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            const dataToSubmit = {
                ...formData,
                monthlySalary: formData.monthlySalary || 0,
                allowance: formData.allowance || 0,
                dailyRate: formData.dailyRate || 0,
                commissionPercentage: formData.commissionPercentage || 0,
                buildingRates: JSON.stringify(formData.buildingRates)
            };

            if (editingStaff) {
                await staffService.update(editingStaff.id, dataToSubmit);
            } else {
                await staffService.create(dataToSubmit);
            }
            await fetchStaff();
            handleCloseModal();
        } catch (err) {
            console.error(err);
            alert(err.response?.data?.error || 'Failed to save staff member');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleEdit = (member) => {
        let parsedRates = [];
        try {
            parsedRates = member.buildingRates ? JSON.parse(member.buildingRates) : [];
            parsedRates = parsedRates.map((r, idx) => ({
                ...r,
                id: r.id || idx,
                fullRate: r.fullRate || r.rate || '',
                halfRate: r.halfRate || ''
            }));
        } catch (e) { console.error("Parse error", e); }

        setEditingStaff(member);
        setFormData({
            fullName: member.fullName,
            position: member.position,
            email: member.email || '',
            phone: member.phone || '',
            gender: member.gender || '',
            staffType: member.staffType,
            monthlySalary: member.monthlySalary || '',
            allowance: member.allowance || '',
            dailyRate: member.dailyRate || '',
            payType: member.payType || 'Daily',
            commissionPercentage: member.commissionPercentage || '',
            buildingRates: parsedRates,
            notes: member.notes || ''
        });
        setIsModalOpen(true);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this staff member? This will remove all their contract associations.')) {
            try {
                await staffService.delete(id);
                fetchStaff();
            } catch (err) {
                alert(err.response?.data?.error || 'Failed to delete staff member');
            }
        }
    };

    const filteredStaff = staff.filter(s =>
        s.fullName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        s.position.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const StatCard = ({ icon: Icon, label, value, color }) => (
        <div className="premium-card p-6 flex items-center gap-5 group hover:scale-[1.02] transition-all duration-300">
            <div className={clsx("p-4 rounded-2xl text-white shadow-lg transition-transform group-hover:rotate-12 duration-300", color)}>
                <Icon className="w-6 h-6" />
            </div>
            <div>
                <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">{label}</p>
                <div className="flex items-center gap-2 mt-1">
                    <p className="text-2xl font-black text-slate-800 dark:text-white tracking-tight">{value}</p>
                </div>
            </div>
        </div>
    );

    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-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <Users 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 Management</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 List</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-primary uppercase tracking-widest whitespace-nowrap">{staff.length} Active Staff</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={handleOpenModal}
                    className="w-full md:w-auto btn-primary flex items-center justify-center gap-2 px-8 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">Register Staff</span>
                </button>
            </div>

            {/* Stats Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
                <StatCard icon={Users} label="Total Staff" value={staff.length} color="bg-indigo-500" />
                <StatCard icon={Briefcase} label="Permanent Staff" value={staff.filter(s => s.staffType === 'Permanent').length} color="bg-emerald-500" />
                <StatCard icon={Calendar} label="Contractors" value={staff.filter(s => s.staffType === 'Temporary').length} color="bg-amber-500" />
                <StatCard icon={TrendingUp} label="Operational" value={staff.filter(s => s.isActive).length} color="bg-primary" />
            </div>

            {/* Main Table Card */}
            <div className="premium-card overflow-hidden">
                <div className="p-6 border-b border-slate-100 dark:border-slate-800/50 flex flex-col md:flex-row justify-between items-center gap-6">
                    <div className="relative flex-1 w-full group">
                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors" />
                        <input
                            type="text"
                            placeholder="Search for staff by name or role..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="w-full !pl-12 !py-3 !bg-slate-50/50 dark:!bg-slate-900/40 border-slate-100 dark:border-slate-800/50 rounded-2xl outline-none"
                        />
                    </div>
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full text-left min-w-[1000px]">
                        <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">Staff Details</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Type</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Contact Info</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Salary/Rate</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-primary/20 border-t-primary rounded-full animate-spin"></div>
                                            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading staff...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : filteredStaff.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">
                                                <Users 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 Staff Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Register your first team member to begin.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                filteredStaff.map((member) => (
                                    <tr key={member.id} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-all duration-300">
                                        <td className="px-8 py-6">
                                            <div className="flex items-center gap-4">
                                                <div className="w-11 h-11 bg-slate-100 dark:bg-slate-800 rounded-2xl flex items-center justify-center font-black text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-slate-700 shadow-sm">
                                                    {member.fullName.charAt(0)}
                                                </div>
                                                <div>
                                                    <p className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{member.fullName}</p>
                                                    <p className="text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest flex items-center gap-1.5 mt-0.5">
                                                        <Tag className="w-3 h-3" /> {member.position}
                                                    </p>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            <div className="flex flex-col gap-2">
                                                <div className={clsx(
                                                    "px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border w-fit transition-all duration-300",
                                                    member.staffType === 'Permanent'
                                                        ? "bg-emerald-500/10 text-emerald-500 border-emerald-500/20 shadow-sm shadow-emerald-500/5"
                                                        : "bg-amber-500/10 text-amber-600 border-amber-500/20 shadow-sm shadow-amber-500/5"
                                                )}>
                                                    {member.staffType}
                                                </div>
                                                <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-[0.2em] ml-1">
                                                    {member.gender || 'NOT SPECIFIED'}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            <div className="space-y-2">
                                                <div className="flex items-center gap-2 text-xs font-bold text-slate-600 dark:text-slate-400">
                                                    <Mail className="w-3.5 h-3.5 text-slate-300 dark:text-slate-700" />
                                                    {member.email || '--'}
                                                </div>
                                                <div className="flex items-center gap-2 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">
                                                    <Phone className="w-3.5 h-3.5 text-slate-300 dark:text-slate-700" />
                                                    {member.phone || '--'}
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            {member.staffType === 'Permanent' ? (
                                                <div className="space-y-1.5">
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Salary:</span>
                                                        <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{currency} {parseFloat(member.monthlySalary).toLocaleString()}</span>
                                                    </div>
                                                    {member.allowance > 0 && (
                                                        <div className="flex items-center gap-2 opacity-60">
                                                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Alloc:</span>
                                                            <span className="text-xs font-extrabold text-slate-600 dark:text-slate-400 tracking-tight">{currency} {parseFloat(member.allowance).toLocaleString()}</span>
                                                        </div>
                                                    )}
                                                </div>
                                            ) : (
                                                <div className="space-y-1.5">
                                                    {member.payType === 'Daily' ? (
                                                        <div className="flex items-center gap-2">
                                                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Daily:</span>
                                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{currency} {parseFloat(member.dailyRate).toLocaleString()}</span>
                                                        </div>
                                                    ) : member.payType === 'Commission' ? (
                                                        <div className="flex items-center gap-2">
                                                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Comm:</span>
                                                            <span className="text-sm font-black text-emerald-500 tracking-tight">{member.commissionPercentage}%</span>
                                                        </div>
                                                    ) : (
                                                        <div className="space-y-2">
                                                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Sales Metrics:</span>
                                                            {member.buildingRates && JSON.parse(member.buildingRates).length > 0 ? (
                                                                <div className="flex flex-wrap gap-1.5">
                                                                    {JSON.parse(member.buildingRates).slice(0, 2).map((r, i) => (
                                                                        <div key={i} className="px-2 py-0.5 bg-slate-50 dark:bg-slate-900 rounded border border-slate-100 dark:border-slate-800 text-[8px] font-black text-slate-500 uppercase tracking-tighter">
                                                                            {r.building}: {r.fullRate || 0}
                                                                        </div>
                                                                    ))}
                                                                </div>
                                                            ) : (
                                                                <p className="text-[9px] text-slate-400 dark:text-slate-600 font-bold uppercase tracking-widest">No rates set</p>
                                                            )}
                                                        </div>
                                                    )}
                                                </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">
                                                <button onClick={() => handleEdit(member)} className="p-2.5 text-slate-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-xl transition-all h-10 w-10 flex items-center justify-center shrink-0" title="Edit Staff"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleDelete(member.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 Staff"><Trash2 className="w-4 h-4 shrink-0" /></button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* 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-[2rem] sm:rounded-[2.5rem] shadow-4xl relative overflow-hidden premium-card max-h-[90vh] flex flex-col">
                        <div className="absolute top-0 left-0 w-full h-1.5 sm:h-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-4 sm:gap-5 shrink-0">
                            <div className="p-3 sm:p-4 bg-primary rounded-xl sm:rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <UserCircle className="w-6 h-6 sm:w-7 sm:h-7" />
                            </div>
                            <div>
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight">
                                    {editingStaff ? 'Edit Staff Member' : 'Add Staff Member'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Enter staff details and compensation</p>
                            </div>
                        </div>

                        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-6 sm:p-10 pt-4 custom-scrollbar">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8 sm:gap-12">
                                {/* Left Column: Personal Information */}
                                <div className="space-y-6">
                                    <h3 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4">Personal Information</h3>

                                    <div className="space-y-4">
                                        <label className="premium-label">Full Name</label>
                                        <input
                                            required
                                            name="fullName"
                                            placeholder="John Alexander Doe"
                                            className="premium-input"
                                            value={formData.fullName}
                                            onChange={handleChange}
                                        />
                                    </div>

                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-4">
                                            <label className="premium-label">Gender</label>
                                            <select
                                                name="gender"
                                                value={formData.gender}
                                                onChange={handleChange}
                                                className="premium-input !appearance-auto"
                                                required
                                            >
                                                <option value="">Select</option>
                                                <option value="Male">Male</option>
                                                <option value="Female">Female</option>
                                                <option value="Other">Other</option>
                                            </select>
                                        </div>
                                        <div className="space-y-4">
                                            <label className="premium-label">Position</label>
                                            <input
                                                required
                                                name="position"
                                                placeholder="Position"
                                                className="premium-input"
                                                value={formData.position}
                                                onChange={handleChange}
                                            />
                                        </div>
                                    </div>

                                    <div className="space-y-4">
                                        <label className="premium-label">Email</label>
                                        <input
                                            type="email"
                                            name="email"
                                            placeholder="john@example.com"
                                            className="premium-input"
                                            value={formData.email}
                                            onChange={handleChange}
                                        />
                                    </div>

                                    <div className="space-y-4">
                                        <label className="premium-label">Phone</label>
                                        <input
                                            type="tel"
                                            name="phone"
                                            placeholder="+254..."
                                            className="premium-input"
                                            value={formData.phone}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>

                                {/* Right Column: Contract & Pay */}
                                <div className="space-y-6">
                                    <h3 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4">Contract & Pay</h3>

                                    <div className="space-y-4">
                                        <label className="premium-label">Staff Type</label>
                                        <select
                                            name="staffType"
                                            value={formData.staffType}
                                            onChange={(e) => setFormData({ ...formData, staffType: e.target.value })}
                                            className="premium-input !appearance-auto font-bold"
                                        >
                                            <option value="Permanent">Permanent (Auto-Payroll)</option>
                                            <option value="Temporary">Temporary / Contract</option>
                                        </select>
                                    </div>

                                    {formData.staffType === 'Permanent' ? (
                                        <div className="grid grid-cols-2 gap-4">
                                            <div className="space-y-4">
                                                <label className="premium-label">Monthly Salary</label>
                                                <div className="relative">
                                                    <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">$</span>
                                                    <input
                                                        type="number"
                                                        name="monthlySalary"
                                                        placeholder="0.00"
                                                        className="premium-input !pl-8"
                                                        value={formData.monthlySalary}
                                                        onChange={handleChange}
                                                        required
                                                    />
                                                </div>
                                            </div>
                                            <div className="space-y-4">
                                                <label className="premium-label">Allowance</label>
                                                <div className="relative">
                                                    <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-bold">$</span>
                                                    <input
                                                        type="number"
                                                        name="allowance"
                                                        placeholder="0.00"
                                                        className="premium-input !pl-8"
                                                        value={formData.allowance}
                                                        onChange={handleChange}
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="space-y-4 bg-slate-50 dark:bg-slate-900/40 p-4 rounded-xl border border-slate-100 dark:border-slate-800">
                                            <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Compensation Model</p>
                                            <div className="flex flex-wrap gap-2 mb-4">
                                                {['Daily', 'Commission', 'Sales'].map((type) => (
                                                    <button
                                                        key={type}
                                                        type="button"
                                                        onClick={() => setFormData({ ...formData, payType: type })}
                                                        className={clsx(
                                                            "px-3 py-1.5 rounded-lg text-[9px] font-black uppercase tracking-widest border transition-colors",
                                                            formData.payType === type
                                                                ? "bg-white dark:bg-slate-800 text-primary border-primary shadow-sm"
                                                                : "border-transparent text-slate-400 hover:bg-white/50"
                                                        )}
                                                    >
                                                        {type}
                                                    </button>
                                                ))}
                                            </div>

                                            {/* Dynamic Fields for Temporary Staff */}
                                            {formData.payType === 'Daily' && (
                                                <div className="space-y-2">
                                                    <label className="premium-label">Daily Rate ({currency})</label>
                                                    <input type="number" name="dailyRate" value={formData.dailyRate} onChange={handleChange} className="premium-input" placeholder="0.00" />
                                                </div>
                                            )}
                                            {formData.payType === 'Commission' && (
                                                <div className="space-y-2">
                                                    <label className="premium-label">Commission %</label>
                                                    <input type="number" name="commissionPercentage" value={formData.commissionPercentage} onChange={handleChange} className="premium-input" placeholder="0" />
                                                </div>
                                            )}
                                            {formData.payType === 'Sales' && (
                                                <div className="space-y-2">
                                                    <div className="flex justify-between items-center">
                                                        <label className="premium-label">Building Rates</label>
                                                        <button type="button" onClick={addBuildingRate} className="text-[9px] font-black text-primary uppercase tracking-widest">+ Add</button>
                                                    </div>
                                                    <div className="space-y-2 max-h-[150px] overflow-y-auto">
                                                        {formData.buildingRates.map((rate) => (
                                                            <div key={rate.id} className="flex gap-2">
                                                                <input placeholder="Building" className="premium-input text-[10px] flex-1 min-w-0" value={rate.building} onChange={(e) => updateBuildingRate(rate.id, 'building', e.target.value)} />
                                                                <input type="number" placeholder="Full" className="premium-input text-[10px] w-16" value={rate.fullRate} onChange={(e) => updateBuildingRate(rate.id, 'fullRate', e.target.value)} />
                                                                <button type="button" onClick={() => removeBuildingRate(rate.id)} className="text-rose-500"><X className="w-4 h-4" /></button>
                                                            </div>
                                                        ))}
                                                        {formData.buildingRates.length === 0 && <p className="text-xs text-slate-400 italic">No rates added</p>}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    )}

                                    <div className="space-y-4">
                                        <label className="premium-label">Notes / Terms</label>
                                        <textarea
                                            name="notes"
                                            value={formData.notes}
                                            onChange={handleChange}
                                            rows="4"
                                            className="premium-input py-3 min-h-[100px]"
                                            placeholder="Terms..."
                                        />
                                    </div>
                                </div>
                            </div>

                            <div className="flex flex-col sm:flex-row gap-4 pt-8 border-t border-slate-100 dark:border-slate-800 shrink-0">
                                <button
                                    type="button"
                                    onClick={handleCloseModal}
                                    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 order-2 sm:order-1"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={isSubmitting}
                                    className="btn-primary flex-[1.5] py-4 shadow-2xl disabled:opacity-50 flex items-center justify-center gap-2 order-1 sm:order-2"
                                >
                                    {isSubmitting ? (
                                        <div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
                                    ) : (
                                        <CheckCircle className="w-4 h-4" />
                                    )}
                                    <span className="whitespace-nowrap">{editingStaff ? 'Update Staff Member' : 'Register Staff'}</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default StaffList;
