import React, { useState, useEffect } from 'react';
import settingsService from '../services/settingsService';
import {
    Settings as SettingsIcon,
    Save,
    Globe,
    User,
    Lock,
    Mail,
    Loader2,
    CheckCircle,
    Database,
    MessageSquare,
    Eye,
    EyeOff,
    Send,
    Shield,
    Server,
    DollarSign,
    Building2,
    Upload,
    Plus,
    Trash2,
    Percent,
    AlertCircle
} from 'lucide-react';

const Settings = () => {
    const [config, setConfig] = useState({
        CRM_ADMIN_USER: '',
        CRM_ADMIN_PASS: '',
        CRM_LOGIN_URL: 'https://crm.youbroadband.co.ke/login',
        FINANCE_ADMIN_EMAIL: 'admin@financepro.com',

        // SMS Settings
        SMS_PROVIDER: '',
        SMS_API_KEY: '',
        SMS_SENDER_ID: '',
        SMS_PARTNER_ID: '',
        SMS_ENABLED: 'false',

        // Email Settings
        EMAIL_HOST: '',
        EMAIL_PORT: '587',
        EMAIL_USER: '',
        EMAIL_PASSWORD: '',
        EMAIL_ENCRYPTION: 'TLS',
        EMAIL_SENDER_NAME: '',
        EMAIL_PROVIDER_TYPE: 'SMTP',

        // Financial Settings
        DEFAULT_CURRENCY: 'KES',
        ENABLE_MULTI_CURRENCY: 'false',
        USD_EXCHANGE_RATE: '130.00',

        // Company Profile
        COMPANY_NAME: '',
        COMPANY_LOGO: '',
        COMPANY_ADDRESS: '',
        COMPANY_CITY: '',
        COMPANY_PHONE: '',
        COMPANY_EMAIL: '',
        COMPANY_WEBSITE: '',
        COMPANY_TAX_ID: '',
        COMPANY_TAX_RATE: '16',
        COMPANY_TAX_NOTES: '',
        BANK_DETAILS: 'BANK: FAMILY BANK\nACCOUNT NAME : DELIGHT OFFICE SOLUTIONS\nACCOUNT NUMBER : 0123456789\nBRANCH: KENYATTA AVENUE'
    });

    const [showApiKey, setShowApiKey] = useState(false);
    const [showEmailPass, setShowEmailPass] = useState(false);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [testingEmail, setTestingEmail] = useState(false);
    const [testRecipient, setTestRecipient] = useState('');
    const [message, setMessage] = useState({ type: '', text: '' });

    // Tax Rates State
    const [taxRates, setTaxRates] = useState([]);
    const [fetchingTaxes, setFetchingTaxes] = useState(true);
    const [newTax, setNewTax] = useState({ name: '', percentage: '', description: '' });
    const [addingTax, setAddingTax] = useState(false);

    useEffect(() => {
        fetchSettings();
        fetchTaxRates();
    }, []);

    const fetchTaxRates = async () => {
        setFetchingTaxes(true);
        try {
            const res = await settingsService.getTaxRates();
            setTaxRates(res.data);
        } catch (err) {
            console.error('Failed to fetch tax rates', err);
        } finally {
            setFetchingTaxes(false);
        }
    };

    const handleAddTax = async () => {
        if (!newTax.name || !newTax.percentage) return;
        setAddingTax(true);
        try {
            await settingsService.createTaxRate(newTax);
            setNewTax({ name: '', percentage: '', description: '' });
            fetchTaxRates();
            setMessage({ type: 'success', text: 'Tax rate added successfully!' });
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to add tax rate.' });
        } finally {
            setAddingTax(false);
        }
    };

    const handleDeleteTax = async (id) => {
        if (!window.confirm('Are you sure you want to delete this tax rate?')) return;
        try {
            await settingsService.deleteTaxRate(id);
            fetchTaxRates();
            setMessage({ type: 'success', text: 'Tax rate deleted.' });
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to delete tax rate.' });
        }
    };

    const fetchSettings = async () => {
        try {
            const res = await settingsService.getSettings();
            setConfig(prev => ({ ...prev, ...res.data }));
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async (e) => {
        if (e) e.preventDefault();
        setSaving(true);
        setMessage({ type: '', text: '' });
        try {
            await settingsService.updateSettings(config);
            setMessage({ type: 'success', text: 'Settings updated successfully!' });
            setTimeout(() => setMessage({ type: '', text: '' }), 3000);
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to update settings.' });
        } finally {
            setSaving(false);
        }
    };

    const handleTestEmail = async () => {
        if (!testRecipient) {
            alert('Please enter a recipient email address for the test.');
            return;
        }
        setTestingEmail(true);
        try {
            await settingsService.testEmail({ testEmail: testRecipient });
            alert('Test email sent! Please check your inbox.');
        } catch (err) {
            alert('Failed to send test email: ' + (err.response?.data?.error || err.message));
        } finally {
            setTestingEmail(false);
        }
    };

    const handleLogoChange = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const formData = new FormData();
        formData.append('logo', file);

        try {
            const res = await settingsService.uploadLogo(formData);
            setConfig(prev => ({ ...prev, COMPANY_LOGO: res.data.logoUrl }));
            setMessage({ type: 'success', text: 'Logo uploaded successfully!' });
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to upload logo.' });
        }
    };

    if (loading) return <div className="p-12 text-center text-slate-400 font-bold uppercase tracking-widest animate-pulse">Loading settings...</div>;

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-5 duration-1000 max-w-5xl pb-20">
            <header 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">
                        <SettingsIcon 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">System Configuration</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">Application settings</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 truncate">System active</span>
                        </div>
                    </div>
                </div>

                <button
                    onClick={handleSave}
                    disabled={saving}
                    className="btn-primary flex items-center justify-center gap-3 px-8 w-full md:w-auto h-12 lg:h-14 disabled:opacity-50"
                >
                    {saving ? <Loader2 className="w-4 h-4 animate-spin shrink-0" /> : <Save className="w-4 h-4 shrink-0" />}
                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Save Settings</span>
                </button>
            </header>

            {message.text && (
                <div className={`p-5 rounded-[24px] flex items-center gap-4 animate-in slide-in-from-top-4 duration-500 shadow-sm border ${message.type === 'success'
                    ? 'bg-emerald-50/50 dark:bg-emerald-500/10 text-emerald-600 border-emerald-100 dark:border-emerald-500/20'
                    : 'bg-rose-50/50 dark:bg-rose-500/10 text-rose-600 border-rose-100 dark:border-rose-500/20'
                    }`}>
                    {message.type === 'success' ? <CheckCircle className="w-6 h-6" /> : <Shield className="w-6 h-6" />}
                    <span className="text-sm font-bold uppercase tracking-widest">{message.text}</span>
                </div>
            )}

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
                {/* Left Column - Core Config */}
                <div className="lg:col-span-7 space-y-10">
                    <div className="premium-card overflow-hidden">
                        <div className="p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex items-center justify-between">
                            <div className="flex items-center gap-4">
                                <Building2 className="w-5 h-5 text-primary" />
                                <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">Company Details</h2>
                            </div>
                            <span className="bg-primary/10 text-primary text-[9px] font-black px-3 py-1 rounded-full uppercase tracking-tighter shadow-sm shadow-primary/5">Main Profile</span>
                        </div>

                        <div className="p-6 sm:p-8 space-y-10">
                            {/* Logo Upload */}
                            <div className="flex flex-col sm:flex-row items-center gap-6 sm:gap-8 p-6 bg-slate-50/50 dark:bg-slate-900/40 rounded-3xl border border-slate-100 dark:border-slate-800/50">
                                <div className="h-24 w-24 sm:h-28 sm:w-28 bg-white dark:bg-bg-dark border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-[24px] sm:rounded-[28px] flex items-center justify-center overflow-hidden relative group shadow-sm transition-all hover:border-primary/50 shrink-0">
                                    {config.COMPANY_LOGO ? (
                                        <img
                                            src={`http://localhost:5000${config.COMPANY_LOGO}`}
                                            alt="Company Logo"
                                            className="w-full h-full object-contain p-3"
                                            onError={(e) => { e.target.onerror = null; e.target.src = '' }}
                                        />
                                    ) : (
                                        <div className="flex flex-col items-center gap-1 sm:gap-2">
                                            <Upload className="w-5 h-5 sm:w-6 sm:h-6 text-slate-300" />
                                            <span className="text-[8px] sm:text-[9px] font-black text-slate-400 uppercase tracking-tighter text-center">No logo uploaded</span>
                                        </div>
                                    )}
                                    <div className="absolute inset-0 bg-primary/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer">
                                        <Upload className="w-8 h-8 text-white animate-bounce-subtle" />
                                    </div>
                                    <input
                                        type="file"
                                        accept="image/*"
                                        className="absolute inset-0 opacity-0 cursor-pointer"
                                        onChange={handleLogoChange}
                                    />
                                </div>
                                <div className="flex-1 space-y-2 text-center sm:text-left">
                                    <h3 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">Company Logo</h3>
                                    <p className="text-[10px] sm:text-[11px] text-slate-500 dark:text-slate-400 leading-relaxed max-w-sm">This logo will appear on your invoices and reports.</p>
                                    <div className="pt-2">
                                        <span className="text-[9px] px-2 py-1 bg-slate-100 dark:bg-slate-800 text-slate-400 font-black uppercase tracking-widest rounded-lg">PNG / SVG / WEBP · MAX 2MB</span>
                                    </div>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 sm:gap-y-8">
                                <div className="md:col-span-2">
                                    <label className="premium-label">Company Legal Name</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        value={config.COMPANY_NAME}
                                        onChange={(e) => setConfig({ ...config, COMPANY_NAME: e.target.value })}
                                        placeholder="FinancePro Enterprise Solutions"
                                    />
                                </div>

                                <div className="md:col-span-2">
                                    <label className="premium-label">Office Address</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        value={config.COMPANY_ADDRESS}
                                        onChange={(e) => setConfig({ ...config, COMPANY_ADDRESS: e.target.value })}
                                        placeholder="Building, Street, Suite Number"
                                    />
                                </div>

                                <div>
                                    <label className="premium-label">City</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        value={config.COMPANY_CITY}
                                        onChange={(e) => setConfig({ ...config, COMPANY_CITY: e.target.value })}
                                        placeholder="Nairobi, Kenya"
                                    />
                                </div>

                                <div>
                                    <label className="premium-label">Phone Contact</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        value={config.COMPANY_PHONE}
                                        onChange={(e) => setConfig({ ...config, COMPANY_PHONE: e.target.value })}
                                        placeholder="+254 7..."
                                    />
                                </div>

                                <div>
                                    <label className="premium-label">Official Email</label>
                                    <input
                                        type="email"
                                        className="premium-input w-full"
                                        value={config.COMPANY_EMAIL}
                                        onChange={(e) => setConfig({ ...config, COMPANY_EMAIL: e.target.value })}
                                        placeholder="billing@yourbrand.com"
                                    />
                                </div>

                                <div>
                                    <label className="premium-label">Public Website</label>
                                    <input
                                        type="url"
                                        className="premium-input w-full"
                                        value={config.COMPANY_WEBSITE}
                                        onChange={(e) => setConfig({ ...config, COMPANY_WEBSITE: e.target.value })}
                                        placeholder="https://..."
                                    />
                                </div>
                            </div>

                            <div className="pt-10 border-t border-slate-100 dark:border-slate-800 space-y-8">
                                <div className="flex items-center gap-2 mb-4">
                                    <div className="w-1.5 h-4 bg-primary rounded-full"></div>
                                    <h4 className="text-[11px] font-black text-slate-800 dark:text-slate-300 uppercase tracking-widest">Tax Information</h4>
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 sm:gap-y-8">
                                    <div>
                                        <label className="premium-label">Tax PIN</label>
                                        <input
                                            type="text"
                                            className="premium-input w-full"
                                            value={config.COMPANY_TAX_ID}
                                            onChange={(e) => setConfig({ ...config, COMPANY_TAX_ID: e.target.value })}
                                            placeholder="P051..."
                                        />
                                    </div>
                                    <div>
                                        <label className="premium-label">Default Tax Rate (%)</label>
                                        <input
                                            type="number"
                                            className="premium-input w-full"
                                            value={config.COMPANY_TAX_RATE}
                                            onChange={(e) => setConfig({ ...config, COMPANY_TAX_RATE: e.target.value })}
                                            placeholder="16"
                                        />
                                    </div>
                                    <div className="md:col-span-2">
                                        <label className="premium-label">Invoice Footnote</label>
                                        <textarea
                                            className="premium-input w-full min-h-[100px]"
                                            value={config.COMPANY_TAX_NOTES}
                                            onChange={(e) => setConfig({ ...config, COMPANY_TAX_NOTES: e.target.value })}
                                            placeholder="Standard text to appear at the bottom of all invoices..."
                                        />
                                    </div>
                                    <div className="md:col-span-2">
                                        <label className="premium-label">Payment Details</label>
                                        <textarea
                                            className="premium-input w-full min-h-[120px] font-mono text-xs"
                                            value={config.BANK_DETAILS}
                                            onChange={(e) => setConfig({ ...config, BANK_DETAILS: e.target.value })}
                                            placeholder="Account Name, Bank, Branch, Swift/IBAN..."
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Tax Rates Configuration */}
                    <div className="premium-card overflow-hidden">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                            <div className="flex items-center gap-4">
                                <Percent className="w-5 h-5 text-rose-500 shrink-0" />
                                <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">Additional Taxes</h2>
                            </div>
                            <span className="bg-rose-500/10 text-rose-500 text-[9px] font-black px-3 py-1 rounded-full uppercase tracking-tighter shadow-sm shadow-rose-500/5">Other Tax Rates</span>
                        </div>

                        <div className="p-6 sm:p-8 space-y-8">
                            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6 items-end p-6 sm:p-8 bg-slate-50/50 dark:bg-slate-900/40 rounded-[28px] border border-slate-100 dark:border-slate-800/50">
                                <div className="sm:col-span-2 md:col-span-1">
                                    <label className="premium-label">Tax Name</label>
                                    <input
                                        type="text"
                                        placeholder="VAT"
                                        className="premium-input w-full !py-2.5"
                                        value={newTax.name}
                                        onChange={(e) => setNewTax({ ...newTax, name: e.target.value })}
                                    />
                                </div>
                                <div className="md:col-span-1">
                                    <label className="premium-label">Rate (%)</label>
                                    <input
                                        type="number"
                                        placeholder="16"
                                        className="premium-input w-full !py-2.5"
                                        value={newTax.percentage}
                                        onChange={(e) => setNewTax({ ...newTax, percentage: e.target.value })}
                                    />
                                </div>
                                <div className="sm:col-span-2 md:col-span-1">
                                    <label className="premium-label">Info</label>
                                    <input
                                        type="text"
                                        placeholder="Optional info..."
                                        className="premium-input w-full !py-2.5"
                                        value={newTax.description}
                                        onChange={(e) => setNewTax({ ...newTax, description: e.target.value })}
                                    />
                                </div>
                                <button
                                    onClick={handleAddTax}
                                    disabled={addingTax || !newTax.name || !newTax.percentage}
                                    className="sm:col-span-2 md:col-span-1 btn-primary !py-2.5 !px-4 text-[10px] uppercase flex items-center justify-center gap-2 h-[46px]"
                                >
                                    {addingTax ? <Loader2 className="w-4 h-4 animate-spin shrink-0" /> : <Plus className="w-4 h-4 shrink-0" />}
                                    <span>Add Tax Rate</span>
                                </button>
                            </div>

                            <div className="grid grid-cols-1 gap-4">
                                {fetchingTaxes ? (
                                    <div className="py-12 flex flex-col items-center gap-4">
                                        <Loader2 className="w-8 h-8 animate-spin text-primary/40" />
                                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Loading taxes...</p>
                                    </div>
                                ) : taxRates.length === 0 ? (
                                    <div className="text-center py-16 px-8 border-2 border-dashed border-slate-100 dark:border-slate-800 rounded-[32px]">
                                        <Percent className="w-12 h-12 text-slate-200 dark:text-slate-800 mx-auto mb-4" />
                                        <p className="text-slate-400 dark:text-slate-600 text-xs font-bold uppercase tracking-[0.15em]">No additional tax rates found</p>
                                    </div>
                                ) : (
                                    taxRates.map(rate => (
                                        <div key={rate.id} className="flex items-center justify-between p-6 bg-white dark:bg-slate-900/20 border border-slate-100 dark:border-slate-800 rounded-[24px] hover:border-primary/20 hover:shadow-premium transition-all group">
                                            <div className="flex items-center gap-5">
                                                <div className="p-3 bg-slate-50 dark:bg-slate-800 rounded-2xl text-slate-400 group-hover:text-primary transition-colors">
                                                    <Percent className="w-5 h-5" />
                                                </div>
                                                <div>
                                                    <h4 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">{rate.name}</h4>
                                                    <p className="text-[10px] text-slate-500 font-bold uppercase tracking-widest mt-0.5">{rate.description || 'System-standard levy'}</p>
                                                </div>
                                            </div>
                                            <div className="flex items-center gap-8">
                                                <span className="text-2xl font-black text-primary tracking-tighter">{rate.percentage}%</span>
                                                <button
                                                    onClick={() => handleDeleteTax(rate.id)}
                                                    className="p-3 text-slate-300 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-all"
                                                >
                                                    <Trash2 className="w-5 h-5" />
                                                </button>
                                            </div>
                                        </div>
                                    ))
                                )}
                            </div>
                        </div>
                    </div>
                    <div className="premium-card overflow-hidden">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                            <div className="flex items-center gap-4">
                                <Mail className="w-5 h-5 text-blue-500 shrink-0" />
                                <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">Email Server (SMTP)</h2>
                            </div>
                            <span className="bg-blue-500/10 text-blue-500 text-[9px] font-black px-3 py-1 rounded-full uppercase tracking-tighter shadow-sm shadow-blue-500/5">System Email</span>
                        </div>

                        <div className="p-6 sm:p-8 space-y-8">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 sm:gap-y-8">
                                <div className="md:col-span-2">
                                    <label className="premium-label">Email Provider</label>
                                    <select
                                        className="premium-input w-full !appearance-auto"
                                        value={config.EMAIL_PROVIDER_TYPE}
                                        onChange={(e) => setConfig({ ...config, EMAIL_PROVIDER_TYPE: e.target.value })}
                                    >
                                        <option value="SMTP">General SMTP Gateway</option>
                                        <option value="Gmail">Google Workspace / Gmail</option>
                                        <option value="Zoho">Zoho Mail</option>
                                        <option value="Outlook">Microsoft 365 / Outlook</option>
                                    </select>
                                </div>

                                <div className="md:col-span-1">
                                    <label className="premium-label">SMTP Host</label>
                                    <div className="relative group">
                                        <Server 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"
                                            className="premium-input w-full !pl-12"
                                            placeholder="smtp.service.com"
                                            value={config.EMAIL_HOST}
                                            onChange={(e) => setConfig({ ...config, EMAIL_HOST: e.target.value })}
                                        />
                                    </div>
                                </div>

                                <div className="md:col-span-1">
                                    <label className="premium-label">Port</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        placeholder="587"
                                        value={config.EMAIL_PORT}
                                        onChange={(e) => setConfig({ ...config, EMAIL_PORT: e.target.value })}
                                    />
                                </div>

                                <div>
                                    <label className="premium-label">Email / Username</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" />
                                        <input
                                            type="text"
                                            className="premium-input w-full !pl-12"
                                            placeholder="user@domain.com"
                                            value={config.EMAIL_USER}
                                            onChange={(e) => setConfig({ ...config, EMAIL_USER: e.target.value })}
                                        />
                                    </div>
                                </div>

                                <div>
                                    <label className="premium-label">Password</label>
                                    <div className="relative group">
                                        <Lock 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={showEmailPass ? "text" : "password"}
                                            className="premium-input w-full !pl-12 !pr-12"
                                            value={config.EMAIL_PASSWORD}
                                            onChange={(e) => setConfig({ ...config, EMAIL_PASSWORD: e.target.value })}
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowEmailPass(!showEmailPass)}
                                            className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-primary transition-colors"
                                        >
                                            {showEmailPass ? <EyeOff className="w-4 h-4 shrink-0" /> : <Eye className="w-4 h-4 shrink-0" />}
                                        </button>
                                    </div>
                                </div>

                                <div>
                                    <label className="premium-label">Sender Name</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        placeholder="Finance Pro Team"
                                        value={config.EMAIL_SENDER_NAME}
                                        onChange={(e) => setConfig({ ...config, EMAIL_SENDER_NAME: e.target.value })}
                                    />
                                </div>

                                <div>
                                    <label className="premium-label">Encryption</label>
                                    <select
                                        className="premium-input w-full !appearance-auto"
                                        value={config.EMAIL_ENCRYPTION}
                                        onChange={(e) => setConfig({ ...config, EMAIL_ENCRYPTION: e.target.value })}
                                    >
                                        <option value="TLS">STARTTLS (Recommended)</option>
                                        <option value="SSL">SSL/TLS Implicit</option>
                                        <option value="None">Unencrypted (Risky)</option>
                                    </select>
                                </div>
                            </div>

                            {/* Test Email Field */}
                            <div className="mt-4 p-6 sm:p-8 bg-blue-50/50 dark:bg-blue-500/5 rounded-[32px] border border-blue-100 dark:border-blue-500/10 space-y-6">
                                <div className="flex items-center gap-3">
                                    <Send className="w-4 h-4 text-blue-500 shrink-0" />
                                    <h3 className="text-[10px] font-black text-blue-600 dark:text-blue-400 uppercase tracking-widest">Test Email</h3>
                                </div>
                                <div className="flex flex-col sm:flex-row gap-4">
                                    <div className="relative flex-1 group">
                                        <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-blue-300 group-focus-within:text-blue-500 transition-colors" />
                                        <input
                                            type="email"
                                            placeholder="recipient@example.com"
                                            className="premium-input w-full !pl-12 !bg-white dark:!bg-bg-dark border-blue-100 dark:border-blue-500/10 focus:ring-blue-500/20"
                                            value={testRecipient}
                                            onChange={(e) => setTestRecipient(e.target.value)}
                                        />
                                    </div>
                                    <button
                                        type="button"
                                        disabled={testingEmail}
                                        onClick={handleTestEmail}
                                        className="px-8 py-3.5 bg-blue-600 text-white text-[10px] font-black uppercase tracking-widest rounded-xl shadow-lg shadow-blue-500/20 hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-3 transition-all h-[46px]"
                                    >
                                        {testingEmail ? <Loader2 className="w-4 h-4 animate-spin shrink-0" /> : <Send className="w-4 h-4 shrink-0" />}
                                        <span className="whitespace-nowrap">Send Test</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* CRM Section */}
                    <div className="premium-card overflow-hidden">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex items-center gap-4">
                            <Database className="w-5 h-5 text-indigo-500 shrink-0" />
                            <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">System Integration (CRM)</h2>
                        </div>
                        <div className="p-6 sm:p-8 space-y-8">
                            <div>
                                <label className="premium-label">CRM URL</label>
                                <div className="relative group">
                                    <Globe className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-indigo-500 transition-colors" />
                                    <input
                                        type="url"
                                        className="premium-input w-full !pl-12"
                                        value={config.CRM_LOGIN_URL}
                                        onChange={(e) => setConfig({ ...config, CRM_LOGIN_URL: e.target.value })}
                                        placeholder="https://crm.yourbrand.co.ke"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 sm:gap-y-8">
                                <div>
                                    <label className="premium-label">Bridge Username</label>
                                    <input
                                        type="text"
                                        className="premium-input w-full"
                                        value={config.CRM_ADMIN_USER}
                                        onChange={(e) => setConfig({ ...config, CRM_ADMIN_USER: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label className="premium-label">Bridge Password</label>
                                    <input
                                        type="password"
                                        className="premium-input w-full"
                                        value={config.CRM_ADMIN_PASS}
                                        onChange={(e) => setConfig({ ...config, CRM_ADMIN_PASS: e.target.value })}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Right Column - SMS & Notifications */}
                <div className="lg:col-span-5 space-y-8">
                    {/* SMS Section */}
                    <div className="premium-card overflow-hidden">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                            <div className="flex items-center gap-4">
                                <MessageSquare className="w-5 h-5 text-emerald-500 shrink-0" />
                                <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">SMS Service</h2>
                            </div>
                            <span className="bg-emerald-500/10 text-emerald-500 text-[9px] font-black px-3 py-1 rounded-full uppercase tracking-tighter shadow-sm shadow-emerald-500/5">Enabled</span>
                        </div>
                        <div className="p-6 sm:p-8 space-y-8">
                            <div>
                                <label className="premium-label">Preferred Provider</label>
                                <input
                                    type="text"
                                    className="premium-input w-full"
                                    placeholder="Twilio, Nexmo, Advanta"
                                    value={config.SMS_PROVIDER}
                                    onChange={(e) => setConfig({ ...config, SMS_PROVIDER: e.target.value })}
                                />
                            </div>

                            <div>
                                <label className="premium-label">Branded Sender ID</label>
                                <input
                                    type="text"
                                    className="premium-input w-full"
                                    placeholder="ACME_LTD"
                                    value={config.SMS_SENDER_ID}
                                    onChange={(e) => setConfig({ ...config, SMS_SENDER_ID: e.target.value })}
                                />
                            </div>

                            <div>
                                <label className="premium-label">API Key</label>
                                <div className="relative group">
                                    <input
                                        type={showApiKey ? "text" : "password"}
                                        className="premium-input w-full !pr-12"
                                        value={config.SMS_API_KEY}
                                        onChange={(e) => setConfig({ ...config, SMS_API_KEY: e.target.value })}
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowApiKey(!showApiKey)}
                                        className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-primary transition-colors"
                                    >
                                        {showApiKey ? <EyeOff className="w-4 h-4 shrink-0" /> : <Eye className="w-4 h-4 shrink-0" />}
                                    </button>
                                </div>
                            </div>

                            <div className="p-6 bg-slate-50 dark:bg-slate-900/40 rounded-3xl border border-slate-100 dark:border-slate-800/50 flex items-center justify-between gap-4">
                                <div className="min-w-0">
                                    <h4 className="text-[11px] font-black text-slate-800 dark:text-slate-300 uppercase tracking-widest truncate">Global SMS Switch</h4>
                                    <p className="text-[10px] text-slate-400 font-bold uppercase tracking-tight mt-1 truncate">Enable automated alerts</p>
                                </div>
                                <button
                                    type="button"
                                    onClick={() => setConfig({ ...config, SMS_ENABLED: config.SMS_ENABLED === 'true' ? 'false' : 'true' })}
                                    className={`w-14 h-7 rounded-full transition-all relative shadow-inner shrink-0 ${config.SMS_ENABLED === 'true' ? 'bg-emerald-500' : 'bg-slate-300 dark:bg-slate-800'}`}
                                >
                                    <div className={`absolute top-1 w-5 h-5 bg-white rounded-full transition-all shadow-md ${config.SMS_ENABLED === 'true' ? 'left-8' : 'left-1'}`} />
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Financial Configuration */}
                    <div className="premium-card overflow-hidden">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex items-center gap-4">
                            <DollarSign className="w-5 h-5 text-amber-500 shrink-0" />
                            <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">Currency Settings</h2>
                        </div>
                        <div className="p-6 sm:p-8 space-y-8">
                            <div className="grid grid-cols-1 md:grid-cols-1 gap-x-8 gap-y-6 sm:gap-y-8">
                                <div>
                                    <label className="premium-label">Operating Currency</label>
                                    <select
                                        className="premium-input w-full !appearance-auto"
                                        value={config.DEFAULT_CURRENCY}
                                        onChange={(e) => setConfig({ ...config, DEFAULT_CURRENCY: e.target.value })}
                                    >
                                        <option value="KES">KES · Kenyan Shilling</option>
                                    </select>
                                    <p className="text-[10px] font-bold text-slate-400 mt-2 uppercase tracking-tight">System is locked to KES for consistency.</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Security & Admin Section */}
                    <div className="premium-card overflow-hidden">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/20 flex items-center gap-4">
                            <Shield className="w-5 h-5 text-rose-500 shrink-0" />
                            <h2 className="font-black text-slate-700 dark:text-slate-300 uppercase tracking-widest text-[11px]">Admin Contact</h2>
                        </div>
                        <div className="p-6 sm:p-8 space-y-8">
                            <div>
                                <label className="premium-label">Admin Email</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-rose-500 transition-colors" />
                                    <input
                                        type="email"
                                        className="premium-input w-full !pl-12"
                                        value={config.FINANCE_ADMIN_EMAIL}
                                        onChange={(e) => setConfig({ ...config, FINANCE_ADMIN_EMAIL: e.target.value })}
                                        placeholder="admin@enterprise.com"
                                    />
                                </div>
                                <p className="text-[10px] text-slate-400 font-bold uppercase tracking-tight mt-3 pl-1">Target email for security alerts</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Settings;
