import React, { useState, useEffect } from 'react';
import billingService from '../services/billingService';
import {
    X, User, Mail, Phone, MapPin, Loader2, Copy, Check, Globe, HelpCircle,
    Plus, Trash2, ShieldCheck, Key, Eye, EyeOff, RefreshCw, Smartphone,
    Briefcase, UserPlus, Info, Save, ChevronDown, MailPlus, Database,
    Activity, Shield, Laptop
} from 'lucide-react';
import { clsx } from 'clsx';

const AddClientModal = ({ isOpen, onClose, onRefresh, initialData }) => {
    const [loading, setLoading] = useState(false);
    const [createdCredentials, setCreatedCredentials] = useState(null);
    const [activeTab, setActiveTab] = useState('details'); // details, address, contacts, custom, reporting, remarks
    const [showPassword, setShowPassword] = useState(false);

    const [formData, setFormData] = useState({
        type: 'Business',
        name: '',
        companyName: '',
        email: '',
        salutation: 'Mr.',
        firstName: '',
        lastName: '',
        phone: '',
        mobile: '',
        website: '',
        billingAddress: '',
        shippingAddress: '',
        currency: 'KES',
        openingBalance: 0,
        paymentTerms: 'Due on Receipt',
        portalLanguage: 'English',
        portalAccess: true,
        sendLoginDetails: true,
        customPassword: ''
    });

    const [contactPersons, setContactPersons] = useState([]);

    useEffect(() => {
        if (!isOpen) {
            setCreatedCredentials(null);
            setFormData({
                type: 'Business',
                name: '',
                companyName: '',
                email: '',
                salutation: 'Mr.',
                firstName: '',
                lastName: '',
                phone: '',
                mobile: '',
                website: '',
                billingAddress: '',
                shippingAddress: '',
                currency: 'KES',
                openingBalance: 0,
                paymentTerms: 'Due on Receipt',
                portalLanguage: 'English',
                portalAccess: true,
                sendLoginDetails: true,
                customPassword: ''
            });
            setContactPersons([]);
            setActiveTab('details');
        }
    }, [isOpen]);

    useEffect(() => {
        if (initialData) {
            setFormData({
                type: initialData.type || 'Business',
                name: initialData.name || '',
                companyName: initialData.companyName || initialData.firstName ? `${initialData.firstName} ${initialData.lastName}` : '',
                email: initialData.email || '',
                salutation: initialData.salutation || 'Mr.',
                firstName: initialData.firstName || '',
                lastName: initialData.lastName || '',
                phone: initialData.phone || '',
                mobile: initialData.mobile || '',
                website: initialData.website || '',
                billingAddress: initialData.billingAddress || '',
                shippingAddress: initialData.shippingAddress || '',
                currency: initialData.currency || 'KES',
                openingBalance: initialData.openingBalance || 0,
                paymentTerms: initialData.paymentTerms || 'Due on Receipt',
                portalLanguage: initialData.portalLanguage || 'English',
                portalAccess: initialData.portalAccess ?? true,
                sendLoginDetails: false,
                customPassword: ''
            });
            if (initialData.contactPersons) {
                setContactPersons(initialData.contactPersons);
            }
        }
    }, [initialData]);

    const handleSubmit = async (e) => {
        if (e) e.preventDefault();
        setLoading(true);
        try {
            const dataToSend = {
                ...formData,
                contactPersons
            };

            if (initialData) {
                await billingService.updateClient(initialData.id, dataToSend);
                onRefresh();
                onClose();
            } else {
                const res = await billingService.createClient(dataToSend);
                onRefresh();

                if (res.data.generatedPassword) {
                    setCreatedCredentials({
                        email: res.data.email,
                        password: res.data.generatedPassword
                    });
                } else {
                    onClose();
                }
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const copyToClipboard = (text) => {
        navigator.clipboard.writeText(text);
    };

    const addContactPerson = () => {
        setContactPersons([...contactPersons, { salutation: 'Mr.', firstName: '', lastName: '', email: '', phone: '', mobile: '' }]);
    };

    const removeContactPerson = (index) => {
        setContactPersons(contactPersons.filter((_, i) => i !== index));
    };

    const updateContactPerson = (index, field, value) => {
        const updated = [...contactPersons];
        updated[index][field] = value;
        setContactPersons(updated);
    };

    const copyBillingToShipping = () => {
        setFormData({ ...formData, shippingAddress: formData.billingAddress });
    };

    if (!isOpen) return null;

    const tabs = [
        { id: 'details', label: 'Client Details', icon: Info },
        { id: 'address', label: 'Address Information', icon: MapPin },
        { id: 'contacts', label: 'Contact Persons', icon: UserPlus },
        { id: 'reporting', label: 'Settings', icon: Activity },
    ];

    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-900/60 dark:bg-black/80 backdrop-blur-md animate-in fade-in duration-300">
            <div className="bg-white dark:bg-slate-900 w-full max-w-6xl rounded-[3rem] shadow-4xl overflow-hidden animate-in zoom-in-95 duration-500 flex flex-col max-h-[92vh] border border-white/20 dark:border-slate-800 relative">
                <div className="absolute top-0 left-0 w-full h-1.5 bg-gradient-to-r from-emerald-600 to-indigo-600"></div>

                {/* Header */}
                <div className="p-6 sm:p-10 pb-4 sm:pb-6 border-b border-slate-100 dark:border-slate-800 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-6 bg-white/50 dark:bg-slate-900/50 backdrop-blur-md sticky top-0 z-20 shrink-0">
                    <div>
                        <div className="flex items-center gap-4">
                            <div className="p-3 bg-emerald-600/10 rounded-2xl text-emerald-600 shrink-0">
                                <UserPlus className="w-6 h-6" />
                            </div>
                            <div>
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white uppercase tracking-tight">
                                    {initialData ? 'Edit Client' : 'Add New Client'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.3em] mt-1 ml-0.5">Manage client information</p>
                            </div>
                        </div>
                    </div>
                    <div className="flex items-center gap-4 w-full sm:w-auto">
                        {!createdCredentials && (
                            <button
                                onClick={handleSubmit}
                                disabled={loading}
                                className="flex-1 sm:flex-initial btn-primary !py-3 !sm:py-3.5 !px-6 sm:px-8 shadow-2xl shadow-emerald-500/20 active:scale-95 transition-all flex items-center justify-center"
                            >
                                {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <>
                                    <Save className="w-4 h-4 mr-1" />
                                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-[0.2em]">Save Client</span>
                                </>}
                            </button>
                        )}
                        <button onClick={onClose} className="p-3 sm:p-3.5 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-[1.25rem] transition-all group border border-slate-100 dark:border-slate-800 shrink-0">
                            <X className="w-5 h-5 text-slate-400 group-hover:rotate-90 transition-transform duration-300" />
                        </button>
                    </div>
                </div>

                {/* Main Content Area */}
                <div className="flex-1 overflow-hidden flex flex-col">
                    {createdCredentials ? (
                        <div className="p-16 flex flex-col items-center justify-center text-center animate-in zoom-in-95 duration-500 h-full">
                            <div className="w-24 h-24 bg-emerald-500/10 rounded-[2rem] flex items-center justify-center text-emerald-500 mb-8 border border-emerald-500/20 animate-bounce">
                                <Check className="w-12 h-12" />
                            </div>
                            <h3 className="text-3xl font-black text-slate-800 dark:text-white uppercase tracking-tighter mb-4">Client Successfully Added</h3>
                            <p className="text-slate-500 dark:text-slate-400 max-w-md mx-auto mb-12 font-medium">
                                The client has been registered and portal credentials have been generated automatically.
                            </p>

                            <div className="grid grid-cols-2 gap-8 w-full max-w-3xl">
                                <div className="p-8 bg-slate-50 dark:bg-slate-900/50 rounded-[2.5rem] border border-slate-100 dark:border-slate-800 relative group overflow-hidden">
                                    <div className="absolute top-0 right-0 p-4 opacity-5 group-hover:opacity-20 transition-opacity">
                                        <User className="w-12 h-12" />
                                    </div>
                                    <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1 mb-3">Email Address</label>
                                    <div className="flex items-center justify-between gap-4">
                                        <span className="text-lg font-black text-slate-800 dark:text-white tabular-nums truncate">{createdCredentials.email}</span>
                                        <button onClick={() => copyToClipboard(createdCredentials.email)} className="p-3 bg-white dark:bg-slate-800 rounded-xl shadow-sm hover:text-emerald-500 transition-colors">
                                            <Copy className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>

                                <div className="p-8 bg-slate-900 dark:bg-black rounded-[2.5rem] text-white relative group overflow-hidden border border-white/5">
                                    <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-30 transition-opacity">
                                        <Key className="w-12 h-12" />
                                    </div>
                                    <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest pl-1 mb-3">Temporary Password</label>
                                    <div className="flex items-center justify-between gap-4">
                                        <span className="text-lg font-black text-emerald-400 tabular-nums tracking-widest">{createdCredentials.password}</span>
                                        <button onClick={() => copyToClipboard(createdCredentials.password)} className="p-3 bg-white/10 rounded-xl hover:bg-white/20 transition-all">
                                            <Copy className="w-4 h-4 text-emerald-400" />
                                        </button>
                                    </div>
                                    <p className="text-[9px] font-black text-rose-500 uppercase tracking-widest mt-4 animate-pulse">* Copy this immediately</p>
                                </div>
                            </div>

                            <button onClick={onClose} className="mt-16 btn-primary !bg-slate-900 !py-4 px-12 rounded-[1.5rem] shadow-xl">
                                <span className="text-[11px] font-black uppercase tracking-[0.3em]">Close Window</span>
                            </button>
                        </div>
                    ) : (
                        <>
                            {/* Tabs Navigation */}
                            <div className="px-6 sm:px-10 bg-slate-50/50 dark:bg-slate-900/30 border-b border-slate-100 dark:border-slate-800 shrink-0 overflow-x-auto custom-scrollbar">
                                <div className="flex gap-6 sm:gap-10 min-w-max">
                                    {tabs.map((tab) => (
                                        <button
                                            key={tab.id}
                                            onClick={() => setActiveTab(tab.id)}
                                            className={clsx(
                                                "py-4 sm:py-5 text-[9px] sm:text-[10px] font-black uppercase tracking-[0.2em] border-b-2 transition-all flex items-center gap-2 sm:gap-3 relative group",
                                                activeTab === tab.id
                                                    ? "border-emerald-600 text-emerald-600"
                                                    : "border-transparent text-slate-400 dark:text-slate-600 hover:text-slate-600 dark:hover:text-slate-400"
                                            )}
                                        >
                                            <tab.icon className={clsx("w-3 sm:h-3.5", activeTab === tab.id ? "animate-pulse" : "group-hover:scale-110 transition-transform")} />
                                            {tab.label}
                                            {activeTab === tab.id && (
                                                <div className="absolute inset-0 bg-emerald-600/5 blur-xl -z-10 animate-pulse"></div>
                                            )}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            <div className="flex-1 overflow-y-auto p-6 sm:p-12 custom-scrollbar">
                                {activeTab === 'details' && (
                                    <div className="space-y-12 animate-in fade-in slide-in-from-bottom-4 duration-500">
                                        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 sm:gap-12">
                                            <div className="lg:col-span-12 xl:col-span-7 space-y-10">
                                                <div className="space-y-4">
                                                    <label className="premium-label !ml-1">Client Type</label>
                                                    <div className="flex flex-col sm:flex-row gap-4 sm:gap-6">
                                                        {['Business', 'Individual'].map(type => (
                                                            <button
                                                                key={type}
                                                                onClick={() => setFormData({ ...formData, type })}
                                                                className={clsx(
                                                                    "flex-1 py-4 px-6 rounded-2xl border-2 transition-all flex items-center gap-4 font-black text-xs uppercase tracking-widest",
                                                                    formData.type === type
                                                                        ? "bg-slate-900 dark:bg-white text-white dark:text-slate-900 border-slate-900 dark:border-white shadow-xl"
                                                                        : "bg-white dark:bg-slate-900 text-slate-400 border-slate-100 dark:border-slate-800 hover:border-slate-200"
                                                                )}
                                                            >
                                                                {type === 'Business' ? <Briefcase className="w-5 h-5" /> : <User className="w-5 h-5" />}
                                                                {type}
                                                            </button>
                                                        ))}
                                                    </div>
                                                </div>

                                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 sm:gap-8">
                                                    <div className="sm:col-span-2 space-y-3">
                                                        <label className="premium-label !ml-1">Company / Legal Name*</label>
                                                        <div className="relative group/input">
                                                            <Globe className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-600 transition-colors" />
                                                            <input
                                                                required
                                                                className="premium-input !pl-12 !py-4 font-black !text-sm"
                                                                placeholder="Enter company or client name"
                                                                value={formData.name}
                                                                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                                            />
                                                        </div>
                                                    </div>

                                                    <div className="space-y-3">
                                                        <label className="premium-label !ml-1">Primary Contact Name</label>
                                                        <div className="flex gap-2 sm:gap-3">
                                                            <select
                                                                className="w-20 sm:w-24 premium-input !py-3 font-black !text-[10px] appearance-none cursor-pointer"
                                                                value={formData.salutation}
                                                                onChange={(e) => setFormData({ ...formData, salutation: e.target.value })}
                                                            >
                                                                <option value="Mr.">MR.</option>
                                                                <option value="Mrs.">MRS.</option>
                                                                <option value="Ms.">MS.</option>
                                                                <option value="Dr.">DR.</option>
                                                            </select>
                                                            <input
                                                                placeholder="First Name"
                                                                className="flex-1 premium-input !py-3 font-bold !text-xs"
                                                                value={formData.firstName}
                                                                onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                                                            />
                                                        </div>
                                                    </div>

                                                    <div className="space-y-3 flex items-end">
                                                        <input
                                                            placeholder="Last Name"
                                                            className="w-full premium-input !py-3 font-bold !text-xs"
                                                            value={formData.lastName}
                                                            onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                                                        />
                                                    </div>

                                                    <div className="space-y-3">
                                                        <label className="premium-label !ml-1">Email Address</label>
                                                        <div className="relative group/input">
                                                            <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-600 transition-colors" />
                                                            <input
                                                                type="email"
                                                                className="premium-input !pl-12 !py-3 font-bold !text-xs"
                                                                value={formData.email}
                                                                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                                            />
                                                        </div>
                                                    </div>

                                                    <div className="space-y-3">
                                                        <label className="premium-label !ml-1">Website</label>
                                                        <div className="relative group/input">
                                                            <Laptop className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-emerald-600 transition-colors" />
                                                            <input
                                                                className="premium-input !pl-12 !py-3 font-bold !text-xs"
                                                                value={formData.website}
                                                                onChange={(e) => setFormData({ ...formData, website: e.target.value })}
                                                            />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="lg:col-span-12 xl:col-span-5 space-y-10">
                                                <div className="p-6 sm:p-10 bg-slate-900 dark:bg-slate-950 rounded-[2.5rem] sm:rounded-[3.5rem] text-white relative overflow-hidden group border border-white/5">
                                                    <div className="absolute top-0 right-0 w-48 h-48 -mr-12 -mt-12 bg-emerald-500/10 rounded-full blur-[80px]" />

                                                    <div className="relative z-10 space-y-8">
                                                        <div className="flex items-center justify-between">
                                                            <h4 className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-500 flex items-center gap-3">
                                                                <Shield className="w-4 h-4 text-emerald-500" />
                                                                Portal Access
                                                            </h4>
                                                            <button
                                                                type="button"
                                                                onClick={() => setFormData({ ...formData, portalAccess: !formData.portalAccess })}
                                                                className={clsx(
                                                                    "relative inline-flex h-6 w-12 shrink-0 cursor-pointer rounded-full transition-all border-2 border-transparent",
                                                                    formData.portalAccess ? "bg-emerald-600" : "bg-slate-700"
                                                                )}
                                                            >
                                                                <span className={clsx("h-5 w-5 transform rounded-full bg-white transition-all shadow-xl", formData.portalAccess ? "translate-x-6" : "translate-x-0")} />
                                                            </button>
                                                        </div>

                                                        {formData.portalAccess && (
                                                            <div className="space-y-6 sm:space-y-8 animate-in slide-in-from-top-4 duration-500">
                                                                <div className="space-y-3">
                                                                    <label className="text-[9px] font-black text-slate-500 uppercase tracking-widest pl-1">Password</label>
                                                                    <div className="flex flex-col sm:flex-row gap-3">
                                                                        <div className="relative flex-1 group/pass">
                                                                            <input
                                                                                type={showPassword ? "text" : "password"}
                                                                                placeholder="Auto-Generate"
                                                                                className="w-full pl-5 pr-12 py-3.5 bg-white/5 border border-white/5 rounded-2xl text-sm font-black text-emerald-400 outline-none focus:border-emerald-500/30 transition-all placeholder:text-slate-700"
                                                                                value={formData.customPassword}
                                                                                onChange={(e) => setFormData({ ...formData, customPassword: e.target.value })}
                                                                            />
                                                                            <button
                                                                                type="button"
                                                                                onClick={() => setShowPassword(!showPassword)}
                                                                                className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-600 hover:text-white transition-colors"
                                                                            >
                                                                                {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                                                                            </button>
                                                                        </div>
                                                                        <button
                                                                            type="button"
                                                                            onClick={() => {
                                                                                const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
                                                                                let retVal = "";
                                                                                for (let i = 0; i < 12; i++) retVal += charset.charAt(Math.floor(Math.random() * charset.length));
                                                                                setFormData({ ...formData, customPassword: retVal });
                                                                                setShowPassword(true);
                                                                            }}
                                                                            className="w-full sm:w-auto p-4 bg-white/10 hover:bg-white/20 rounded-2xl transition-all group/gen flex items-center justify-center"
                                                                        >
                                                                            <RefreshCw className="w-5 h-5 group-hover/gen:rotate-180 transition-transform duration-500" />
                                                                        </button>
                                                                    </div>
                                                                </div>

                                                                <div className="flex items-center gap-4 p-5 bg-white/5 rounded-3xl border border-white/5 group-hover:border-emerald-500/20 transition-all">
                                                                    <input
                                                                        type="checkbox"
                                                                        id="sendToken"
                                                                        className="w-5 h-5 rounded-lg border-white/10 bg-transparent text-emerald-500 focus:ring-emerald-500"
                                                                        checked={formData.sendLoginDetails}
                                                                        onChange={(e) => setFormData({ ...formData, sendLoginDetails: e.target.checked })}
                                                                    />
                                                                    <label htmlFor="sendToken" className="text-[10px] font-black uppercase tracking-widest text-slate-400 cursor-pointer">Email login details to client</label>
                                                                </div>
                                                            </div>
                                                        )}

                                                        <div className="pt-8 border-t border-white/5 flex items-center justify-between">
                                                            <div className="flex flex-col">
                                                                <span className="text-[11px] font-black text-slate-300 uppercase">Opening Balance</span>
                                                                <p className="text-[9px] text-slate-500 font-bold uppercase mt-1">Starting balance</p>
                                                            </div>
                                                            <div className="flex items-baseline gap-1 text-xl sm:text-2xl font-black">
                                                                <span className="text-xs not-italic opacity-40">KES</span>
                                                                <input
                                                                    type="number"
                                                                    className="bg-transparent border-none text-right focus:ring-0 w-20 sm:w-24 tabular-nums"
                                                                    value={formData.openingBalance}
                                                                    onChange={(e) => setFormData({ ...formData, openingBalance: e.target.value })}
                                                                />
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {activeTab === 'address' && (
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8 md:gap-12 animate-in fade-in slide-in-from-right-4 duration-500">
                                        <div className="space-y-4">
                                            <label className="premium-label !ml-1 flex items-center gap-2">
                                                <div className="w-1.5 h-1.5 rounded-full bg-indigo-500" />
                                                Billing Address
                                            </label>
                                            <textarea
                                                rows="6"
                                                className="premium-input !p-6 sm:p-8 !text-sm !font-black !leading-relaxed resize-none"
                                                value={formData.billingAddress}
                                                onChange={(e) => setFormData({ ...formData, billingAddress: e.target.value })}
                                                placeholder="Enter primary billing address..."
                                            />
                                        </div>
                                        <div className="space-y-4">
                                            <div className="flex justify-between items-center">
                                                <label className="premium-label !ml-1 flex items-center gap-2">
                                                    <div className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                                                    Shipping Address
                                                </label>
                                                <button onClick={copyBillingToShipping} type="button" className="text-[9px] font-black uppercase tracking-[0.2em] text-emerald-600 hover:brightness-125 transition-all bg-emerald-50 dark:bg-emerald-900/40 px-3 py-1.5 rounded-xl border border-emerald-100 dark:border-emerald-800">Copy Billing</button>
                                            </div>
                                            <textarea
                                                rows="6"
                                                className="premium-input !p-6 sm:p-8 !text-sm !font-black !leading-relaxed resize-none"
                                                value={formData.shippingAddress}
                                                onChange={(e) => setFormData({ ...formData, shippingAddress: e.target.value })}
                                                placeholder="Enter shipping address..."
                                            />
                                        </div>
                                    </div>
                                )}

                                {activeTab === 'contacts' && (
                                    <div className="space-y-10 animate-in fade-in slide-in-from-left-4 duration-500">
                                        <div className="premium-card !p-0 overflow-hidden !rounded-[2.5rem] border-slate-100 dark:border-slate-800">
                                            <div className="overflow-x-auto custom-scrollbar">
                                                <table className="w-full text-left min-w-[800px]">
                                                    <thead>
                                                        <tr className="bg-slate-50/50 dark:bg-slate-900/50 border-b border-slate-100 dark:border-slate-800">
                                                            <th className="px-8 py-5 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Title</th>
                                                            <th className="px-6 py-5 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Name</th>
                                                            <th className="px-6 py-5 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Email</th>
                                                            <th className="px-6 py-5 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest">Phone</th>
                                                            <th className="px-4 py-5 w-14"></th>
                                                        </tr>
                                                    </thead>
                                                    <tbody className="divide-y divide-slate-50 dark:divide-slate-800/50">
                                                        {contactPersons.length === 0 ? (
                                                            <tr>
                                                                <td colSpan="5" className="px-8 py-20 text-center animate-pulse">
                                                                    <div className="flex flex-col items-center gap-4 text-slate-300 dark:text-slate-700">
                                                                        <UserPlus className="w-12 h-12 opacity-20" />
                                                                        <p className="text-[10px] font-black uppercase tracking-[0.4em] mb-1">No Contact Persons Added</p>
                                                                        <button onClick={addContactPerson} className="text-emerald-500 text-[9px] font-black uppercase tracking-widest hover:underline px-4 py-2 bg-emerald-500/5 rounded-xl">Add First Contact</button>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        ) : contactPersons.map((contact, idx) => (
                                                            <tr key={idx} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-colors">
                                                                <td className="p-4 px-8">
                                                                    <select
                                                                        className="w-full premium-input !py-2 !text-[10px] font-black appearance-none cursor-pointer text-center"
                                                                        value={contact.salutation}
                                                                        onChange={(e) => updateContactPerson(idx, 'salutation', e.target.value)}
                                                                    >
                                                                        <option value="Mr.">MR.</option>
                                                                        <option value="Mrs.">MRS.</option>
                                                                        <option value="Ms.">MS.</option>
                                                                        <option value="Dr.">DR.</option>
                                                                    </select>
                                                                </td>
                                                                <td className="p-4 px-6 flex gap-3">
                                                                    <input
                                                                        placeholder="First Name"
                                                                        className="flex-1 premium-input !py-2 !text-xs font-bold italic"
                                                                        value={contact.firstName}
                                                                        onChange={(e) => updateContactPerson(idx, 'firstName', e.target.value)}
                                                                    />
                                                                    <input
                                                                        placeholder="Last Name"
                                                                        className="flex-1 premium-input !py-2 !text-xs font-bold italic"
                                                                        value={contact.lastName}
                                                                        onChange={(e) => updateContactPerson(idx, 'lastName', e.target.value)}
                                                                    />
                                                                </td>
                                                                <td className="p-4 px-6">
                                                                    <input
                                                                        placeholder="email@example.com"
                                                                        className="w-full premium-input !py-2 !text-xs font-bold italic"
                                                                        value={contact.email}
                                                                        onChange={(e) => updateContactPerson(idx, 'email', e.target.value)}
                                                                    />
                                                                </td>
                                                                <td className="p-4 px-6">
                                                                    <input
                                                                        placeholder="+123..."
                                                                        className="w-full premium-input !py-2 !text-xs font-black tabular-nums"
                                                                        value={contact.mobile}
                                                                        onChange={(e) => updateContactPerson(idx, 'mobile', e.target.value)}
                                                                    />
                                                                </td>
                                                                <td className="p-4 px-4 text-center">
                                                                    <button onClick={() => removeContactPerson(idx)} className="p-3 text-slate-300 dark:text-slate-700 hover:text-rose-500 hover:bg-rose-500/10 rounded-xl transition-all opacity-0 group-hover:opacity-100">
                                                                        <Trash2 className="w-5 h-5" />
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        {contactPersons.length > 0 && (
                                            <button
                                                type="button"
                                                onClick={addContactPerson}
                                                className="text-[10px] font-black text-emerald-600 hover:brightness-125 flex items-center gap-3 px-6 py-3 bg-white dark:bg-slate-800 rounded-2xl border border-emerald-100 dark:border-slate-800/50 shadow-sm transition-all uppercase tracking-widest"
                                            >
                                                <Plus className="w-4 h-4 bg-emerald-600 text-white rounded-lg p-0.5" /> Add Contact Person
                                            </button>
                                        )}
                                    </div>
                                )}

                                {activeTab === 'reporting' && (
                                    <div className="flex flex-col items-center justify-center py-12 sm:py-24 text-center animate-pulse">
                                        <div className="p-6 sm:p-8 bg-slate-50 dark:bg-slate-900/50 rounded-[2rem] sm:rounded-[3rem] border border-slate-100 dark:border-slate-800 flex flex-col items-center gap-6">
                                            <Database className="w-12 h-12 sm:w-16 sm:h-16 text-slate-200 dark:text-slate-800" />
                                            <div>
                                                <p className="font-black text-slate-800 dark:text-white uppercase tracking-[0.2em]">No Data Available</p>
                                                <p className="text-[10px] text-slate-400 dark:text-slate-600 font-bold uppercase tracking-widest mt-2">Extended analytic parameters coming soon</p>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </>
                    )}
                </div>

                {/* Magnitude Tracking Footer */}
                {!createdCredentials && (
                    <div className="px-6 sm:px-10 py-4 sm:py-6 bg-slate-50/50 dark:bg-slate-900/50 border-t border-slate-100 dark:border-slate-800 flex flex-col sm:flex-row justify-between items-center rounded-b-[3rem] shrink-0 gap-6">
                        <div className="flex flex-col sm:flex-row gap-6 sm:gap-10 w-full sm:w-auto">
                            <div className="flex items-center gap-4">
                                <div className="p-2.5 bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-100 dark:border-slate-700">
                                    <Smartphone className="w-4 h-4 text-emerald-600" />
                                </div>
                                <div className="truncate">
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Client Type</p>
                                    <p className="text-[11px] font-black text-slate-800 dark:text-white uppercase tracking-tight">{formData.type}</p>
                                </div>
                            </div>
                            <div className="flex items-center gap-4">
                                <div className="p-2.5 bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-100 dark:border-slate-700">
                                    <MailPlus className="w-4 h-4 text-indigo-600" />
                                </div>
                                <div className="truncate">
                                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Email Status</p>
                                    <p className="text-[11px] font-black text-slate-800 dark:text-white uppercase tracking-tight">{formData.email || 'Pending...'}</p>
                                </div>
                            </div>
                        </div>
                        <div className="flex items-center gap-3 opacity-50 grayscale hover:grayscale-0 transition-all duration-700">
                            <Shield className="w-5 h-5" />
                            <ShieldCheck className="w-5 h-5" />
                            <Globe className="w-5 h-5" />
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default AddClientModal;
