import React, { useState, useEffect } from 'react';
import expenseService from '../services/expenseService';
import { Plus, User, Mail, Phone, Edit2, Trash2, Search, Briefcase, FileText } from 'lucide-react';

const VendorList = () => {
    const [vendors, setVendors] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingVendor, setEditingVendor] = useState(null);
    const [formData, setFormData] = useState({ name: '', contactPerson: '', email: '', phone: '', notes: '' });
    const [isSubmitting, setIsSubmitting] = useState(false);

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

    const fetchVendors = async () => {
        try {
            const res = await expenseService.getVendors();
            setVendors(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleOpenModal = () => {
        setEditingVendor(null);
        setFormData({ name: '', contactPerson: '', email: '', phone: '', notes: '' });
        setIsModalOpen(true);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setFormData({ name: '', contactPerson: '', email: '', phone: '', notes: '' });
    };

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

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            if (editingVendor) {
                await expenseService.updateVendor(editingVendor.id, formData);
            } else {
                await expenseService.createVendor(formData);
            }
            await fetchVendors();
            handleCloseModal();
        } catch (err) {
            console.error(err);
            alert(err.response?.data?.error || err.response?.data?.message || 'Failed to save vendor');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleEdit = (vendor) => {
        setEditingVendor(vendor);
        setFormData({
            name: vendor.name,
            contactPerson: vendor.contactPerson || '',
            email: vendor.email || '',
            phone: vendor.phone || '',
            notes: vendor.notes || ''
        });
        setIsModalOpen(true);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this vendor? This will not delete past expenses associated with them.')) {
            try {
                await expenseService.deleteVendor(id);
                fetchVendors();
            } catch (err) {
                console.error('Delete Vendor UI Error:', err);
                const msg = err.response?.data?.error || err.response?.data?.message || err.message || 'Failed to delete vendor';
                alert(msg);
            }
        }
    };

    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">
                        <Briefcase 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">Vendors</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">Vendor 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">{vendors.length} Vendors</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">Add Vendor</span>
                </button>
            </div>

            {/* Vendor Table */}
            <div className="premium-card overflow-hidden">
                <div className="p-4 sm: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 shrink-0" />
                        <input
                            type="text"
                            placeholder="Search vendors..."
                            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 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">Vendor 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 Details</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">Balance State</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-primary/20 border-t-primary rounded-full animate-spin"></div>
                                            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading vendors...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : vendors.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">
                                                <Briefcase 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 Vendors Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Add your first vendor to start tracking expenses.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                vendors.map((vendor) => (
                                    <tr key={vendor.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 min-w-0">
                                                <div className="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center shadow-sm shrink-0">
                                                    <Briefcase className="w-5 h-5 text-primary shrink-0" />
                                                </div>
                                                <div className="min-w-0">
                                                    <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate block">{vendor.name}</span>
                                                    <div className="flex items-center gap-2 mt-1">
                                                        <User className="w-3 h-3 text-slate-300 shrink-0" />
                                                        <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest truncate">{vendor.contactPerson || 'No Contact'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="space-y-1 min-w-0">
                                                <div className="flex items-center gap-2 text-xs font-bold text-slate-500 dark:text-slate-400">
                                                    <Mail className="w-3.5 h-3.5 text-slate-300 shrink-0" />
                                                    <span className="truncate">{vendor.email || '--'}</span>
                                                </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 shrink-0" />
                                                    <span className="truncate">{vendor.phone || '--'}</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex flex-col items-end">
                                                {Number(vendor.pendingBalance) > 0 ? (
                                                    // Pending Balance State
                                                    <>
                                                        <span className="text-sm font-black text-rose-500 tracking-tighter whitespace-nowrap">
                                                            <span className="text-[9px] not-italic mr-1 opacity-70">PENDING</span>
                                                            {Number(vendor.pendingBalance).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                                                        </span>
                                                        <div className="flex items-center gap-1.5 mt-1">
                                                            <div className="w-1.5 h-1.5 rounded-full bg-rose-500 shrink-0"></div>
                                                            <span className="text-[9px] font-black text-rose-400 uppercase tracking-widest whitespace-nowrap">Payment Due</span>
                                                        </div>
                                                    </>
                                                ) : Number(vendor.creditBalance) > 0 ? (
                                                    // Credit Balance State
                                                    <>
                                                        <span className="text-sm font-black text-emerald-500 tracking-tighter whitespace-nowrap">
                                                            <span className="text-[9px] not-italic mr-1 opacity-70">CREDIT</span>
                                                            {Number(vendor.creditBalance).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                                                        </span>
                                                        <div className="flex items-center gap-1.5 mt-1">
                                                            <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 shrink-0"></div>
                                                            <span className="text-[9px] font-black text-emerald-400 uppercase tracking-widest whitespace-nowrap">Available Credit</span>
                                                        </div>
                                                    </>
                                                ) : (
                                                    // Settled State
                                                    <>
                                                        <span className="text-sm font-black text-slate-300 dark:text-slate-600 tracking-tighter whitespace-nowrap">
                                                            --
                                                        </span>
                                                        <div className="flex items-center gap-1.5 mt-1">
                                                            <div className="w-1.5 h-1.5 rounded-full bg-slate-300 dark:bg-slate-700 shrink-0"></div>
                                                            <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest whitespace-nowrap">Settled</span>
                                                        </div>
                                                    </>
                                                )}
                                            </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(vendor)} className="p-2.5 text-slate-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Edit Vendor"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleDelete(vendor.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 shrink-0 h-10 w-10 flex items-center justify-center" title="Delete Vendor"><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-xl rounded-[2.5rem] shadow-4xl relative overflow-hidden premium-card flex flex-col max-h-[95vh]">
                        <div className="absolute top-0 left-0 w-full h-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-5 shrink-0">
                            <div className="p-3.5 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <Briefcase className="w-6 h-6 sm:w-7 sm:h-7 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight truncate">
                                    {editingVendor ? 'Edit Vendor' : 'Add Vendor'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Enter vendor details</p>
                            </div>
                        </div>

                        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto px-6 sm:px-10 py-6 space-y-8 custom-scrollbar">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-8">
                                <div className="sm:col-span-2 space-y-2">
                                    <label className="premium-label">Company Name</label>
                                    <div className="relative group">
                                        <Briefcase 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 shrink-0" />
                                        <input
                                            required
                                            name="name"
                                            placeholder="e.g. Acme Corporations"
                                            className="premium-input !pl-12 h-12 sm:h-14"
                                            value={formData.name}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>

                                <div className="sm:col-span-2 space-y-2">
                                    <label className="premium-label">Contact Name</label>
                                    <div className="relative group">
                                        <User 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 shrink-0" />
                                        <input
                                            name="contactPerson"
                                            placeholder="e.g. John Doe (Procurement)"
                                            className="premium-input !pl-12 h-12 sm:h-14"
                                            value={formData.contactPerson}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <label className="premium-label">Email Address</label>
                                    <div className="relative group">
                                        <Mail 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 shrink-0" />
                                        <input
                                            type="email"
                                            name="email"
                                            placeholder="billing@acme.com"
                                            className="premium-input !pl-12 h-12 sm:h-14"
                                            value={formData.email}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <label className="premium-label">Phone Number</label>
                                    <div className="relative group">
                                        <Phone 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 shrink-0" />
                                        <input
                                            type="tel"
                                            name="phone"
                                            placeholder="+254 700 000 000"
                                            className="premium-input !pl-12 h-12 sm:h-14"
                                            value={formData.phone}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>

                                <div className="sm:col-span-2 space-y-2">
                                    <label className="premium-label">Notes</label>
                                    <div className="relative group">
                                        <FileText className="absolute left-4 top-4 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                        <textarea
                                            name="notes"
                                            rows="4"
                                            placeholder="Technical capabilities, billing preferences, etc."
                                            className="premium-input !pl-12 py-3"
                                            value={formData.notes}
                                            onChange={handleChange}
                                        />
                                    </div>
                                </div>
                            </div>

                            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                                <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 h-12 sm:h-14 flex items-center justify-center shrink-0"
                                >
                                    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 h-12 sm:h-14 shrink-0"
                                >
                                    {isSubmitting ? (
                                        <div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin shrink-0"></div>
                                    ) : (
                                        <Plus className="w-4 h-4 shrink-0" />
                                    )}
                                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">{editingVendor ? 'Save Changes' : 'Register Vendor'}</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default VendorList;
