import React, { useState, useEffect } from 'react';
import billingService from '../services/billingService';
import {
    Users,
    Plus,
    Mail,
    Phone,
    MapPin,
    CheckCircle,
    XCircle,
    Edit2,
    Trash2
} from 'lucide-react';
import AddClientModal from '../components/AddClientModal';

const ClientList = () => {
    const [clients, setClients] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingClient, setEditingClient] = useState(null);

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

    const fetchClients = async () => {
        try {
            const res = await billingService.getClients();
            setClients(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleOpenModal = () => {
        setEditingClient(null);
        setIsModalOpen(true);
    };

    const handleEdit = (client) => {
        setEditingClient(client);
        setIsModalOpen(true);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to purge this client record? Historical data will persist but future interaction will be limited.')) {
            try {
                await billingService.deleteClient(id);
                fetchClients();
            } catch (err) {
                console.error(err);
            }
        }
    };

    return (
        <div className="space-y-10 animate-slide-up">
            {/* 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">Clients</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">Client Management</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">{clients.length} Clients</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={handleOpenModal}
                    className="btn-primary 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">Register Client</span>
                </button>
            </div>

            {/* Client Table */}
            <div className="premium-card overflow-hidden">
                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[900px]">
                        <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">Client 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">Contact Information</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Billing Address</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="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 clients...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : clients.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 shrink-0">
                                                <Users 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 Clients Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Register your first client to get started.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                clients.map((client) => (
                                    <tr key={client.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 items-center gap-4">
                                                <div className="w-11 h-11 bg-indigo-500/10 text-indigo-500 rounded-2xl flex items-center justify-center shadow-sm font-black text-sm uppercase shrink-0">
                                                    {client.name.charAt(0)}
                                                </div>
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate">{client.name}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex flex-col gap-1.5">
                                                <div className="flex items-center gap-2 text-xs font-extrabold text-slate-600 dark:text-slate-400 truncate">
                                                    <Mail className="w-3.5 h-3.5 text-slate-400 shrink-0" /> {client.email}
                                                </div>
                                                {client.phone && (
                                                    <div className="flex items-center gap-2 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest truncate">
                                                        <Phone className="w-3 h-3 shrink-0" /> {client.phone}
                                                    </div>
                                                )}
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex items-center gap-2 max-w-[200px]">
                                                <MapPin className="w-3.5 h-3.5 text-slate-300 dark:text-slate-700 shrink-0" />
                                                <span className="text-xs font-bold text-slate-500 dark:text-slate-500 truncate">{client.billingAddress || 'No Address Logged'}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="inline-flex items-center gap-1.5 px-3 py-1 bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 rounded-full text-[9px] font-black uppercase tracking-widest shadow-sm shadow-emerald-500/5 whitespace-nowrap">
                                                <CheckCircle className="w-3.5 h-3.5 shrink-0" /> Active
                                            </div>
                                        </td>
                                        <td className="px-6 sm: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(client)} 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 Client"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button
                                                    onClick={() => handleDelete(client.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 Client"
                                                >
                                                    <Trash2 className="w-4 h-4 shrink-0" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            <AddClientModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onRefresh={fetchClients}
                initialData={editingClient}
            />
        </div>
    );
};

export default ClientList;
