import React, { useState, useEffect } from 'react';
import { User, Shield, Key, Bell, CreditCard, Save, RefreshCw, AlertCircle, Mail, Globe, Phone, MapPin, Building, ChevronRight } from 'lucide-react';
import { ClientDetails, DashboardView } from '../types';
import { getClientDetails, updateClientDetails, getPaymentMethods, getCountries } from '../services/whmcsService';
import AccountSidebar from './AccountSidebar';

interface MyDetailsViewProps {
    clientId: number;
    setView: (view: DashboardView) => void;
}

const MyDetailsView: React.FC<MyDetailsViewProps> = ({ clientId, setView }) => {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [client, setClient] = useState<ClientDetails | null>(null);
    const [paymentMethods, setPaymentMethods] = useState<{ module: string; displayName: string }[]>([]);
    const [countries, setCountries] = useState<Record<string, string>>({});

    // Form State
    const [formData, setFormData] = useState({
        firstname: '',
        lastname: '',
        email: '',
        phonenumber: '',
        language: 'english',
        companyname: '',
        address1: '',
        address2: '',
        city: '',
        state: '',
        postcode: '',
        country: '',
        paymentmethod: '',
        billingcid: '0',
        marketing_emails: false,
        customfields: {} as Record<string, any>
    });

    useEffect(() => {
        fetchData();
    }, [clientId]);

    const fetchData = async () => {
        setLoading(true);
        setError(null);
        try {
            const [clientData, methods, countriesData] = await Promise.all([
                getClientDetails(clientId),
                getPaymentMethods(),
                getCountries()
            ]);

            setClient(clientData);
            setPaymentMethods(methods || []);
            setCountries(countriesData || {});

            // Map custom fields (already normalized by the service as a flat array)
            const customFieldsMap: Record<string, any> = {};
            if (clientData && clientData.customfields) {
                const fields = clientData.customfields;

                fields.forEach((field: any) => {
                    if (field && field.id) {
                        customFieldsMap[field.id] = field.value || '';
                    }
                });
            }

            setFormData({
                firstname: clientData?.firstname || '',
                lastname: clientData?.lastname || '',
                email: clientData?.email || '',
                phonenumber: clientData?.phonenumber || '',
                language: clientData?.language || 'english',
                companyname: clientData?.companyname || '',
                address1: clientData?.address1 || '',
                address2: clientData?.address2 || '',
                city: clientData?.city || '',
                state: clientData?.state || '',
                postcode: clientData?.postcode || '',
                country: clientData?.country || '',
                paymentmethod: clientData?.paymentmethod || '',
                billingcid: clientData?.billingcid || '0',
                marketing_emails: clientData?.email_preferences?.general === '1',
                customfields: customFieldsMap
            });

        } catch (err) {
            console.error("Fetch Data Error:", err);
            setError(err instanceof Error ? err.message : 'Failed to load details');
        } finally {
            setLoading(false);
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value, type } = e.target as HTMLInputElement;
        const checked = (e.target as HTMLInputElement).checked;

        if (name.startsWith('customfield[')) {
            const fieldId = name.match(/\[(\d+)\]/)?.[1];
            if (fieldId) {
                setFormData(prev => ({
                    ...prev,
                    customfields: {
                        ...prev.customfields,
                        [fieldId]: value
                    }
                }));
            }
        } else {
            setFormData(prev => ({
                ...prev,
                [name]: type === 'checkbox' ? checked : value
            }));
        }
    };

    const handleSave = async () => {
        setSaving(true);
        setError(null);
        setSuccess(null);
        try {
            // WHMCS API UpdateClient expects customfields as an object/array handled by whmcsService
            const res = await updateClientDetails(clientId, formData);
            if (res.result === 'success') {
                setSuccess('Changes saved successfully!');
                // Wait a bit then clear success
                setTimeout(() => setSuccess(null), 3000);

                const updated = await getClientDetails(clientId);
                setClient(updated);
            } else {
                setError(res.message || 'Failed to update details');
            }
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Update failed');
        } finally {
            setSaving(false);
        }
    };

    if (loading) {
        return (
            <div className="flex flex-col items-center justify-center min-h-[500px] space-y-4">
                <div className="relative">
                    <div className="absolute inset-0 bg-blue-500/20 blur-xl rounded-full animate-pulse"></div>
                    <RefreshCw className="animate-spin text-blue-600 relative z-10" size={48} />
                </div>
                <p className="text-slate-400 font-medium animate-pulse">Loading your profile...</p>
            </div>
        );
    }

    const InputField = ({ label, name, value, disabled = false, type = "text", placeholder = "" }: { label: string, name: string, value: string, disabled?: boolean, type?: string, placeholder?: string }) => (
        <div className="space-y-1.5">
            <label className="text-[10px] font-bold text-slate-500 uppercase tracking-widest ml-1">
                {label}
            </label>
            <div className={`relative ${disabled ? 'opacity-70' : ''}`}>
                <input
                    type={type}
                    name={name}
                    value={value}
                    onChange={handleChange}
                    disabled={disabled}
                    placeholder={placeholder}
                    className={`w-full p-3 bg-white border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500/10 focus:border-blue-500 outline-none transition-all text-sm font-medium text-slate-700 ${disabled ? 'bg-slate-50 cursor-not-allowed' : 'hover:border-slate-300 shadow-sm'}`}
                />
            </div>
        </div>
    );

    const SelectField = ({ label, name, value, options }: { label: string, name: string, value: string, options: Array<{ value: string, label: string }> }) => (
        <div className="space-y-1.5">
            <label className="text-[10px] font-bold text-slate-500 uppercase tracking-widest ml-1">
                {label}
            </label>
            <div className="relative">
                <select
                    name={name}
                    value={value}
                    onChange={handleChange}
                    className="w-full p-3 bg-white border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500/10 focus:border-blue-500 outline-none appearance-none transition-all text-sm font-medium text-slate-700 cursor-pointer shadow-sm hover:border-slate-300"
                >
                    {options.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
                </select>
                <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400">
                    <ChevronRight className="rotate-90" size={14} />
                </div>
            </div>
        </div>
    );

    return (
        <div className="min-h-screen bg-[#F8FAFC]">
            {/* Professional Header Section */}
            <div className="bg-white border-b border-slate-200">
                <div className="max-w-7xl mx-auto px-6 py-8 relative z-10">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
                        <div className="space-y-1">
                            <h1 className="text-2xl font-bold text-slate-900 tracking-tight text-center md:text-left">
                                My Accounts <span className="text-blue-600">Details</span>
                            </h1>
                            <div className="flex items-center justify-center md:justify-start gap-2 text-[11px] text-slate-400 font-bold uppercase tracking-wider">
                                <span className="hover:text-blue-600 transition-colors cursor-pointer">Client Area</span>
                                <ChevronRight size={10} className="text-slate-300" />
                                <span className="text-slate-500">Account Settings</span>
                            </div>
                        </div>
                        <div className="flex justify-center gap-3">
                            <button
                                onClick={handleSave}
                                disabled={saving}
                                className="px-6 py-2.5 bg-blue-600 text-white text-xs font-black rounded-lg shadow-sm hover:bg-blue-700 transition-all flex items-center gap-2 disabled:opacity-70 uppercase tracking-widest"
                            >
                                {saving ? <RefreshCw className="animate-spin" size={14} /> : <Save size={14} />}
                                <span>Save Changes</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div className="max-w-7xl mx-auto px-6 py-10">
                <div className="flex flex-col lg:flex-row gap-10">
                    {/* Sidebar Navigator */}
                    <div className="w-full lg:w-64 flex-shrink-0">
                        <AccountSidebar clientId={clientId} currentView={DashboardView.MY_DETAILS} setView={setView} />
                    </div>

                    {/* Main Content Area */}
                    <div className="flex-1 space-y-8">
                        {error && (
                            <div className="p-4 bg-red-50 border border-red-100 rounded-xl flex items-center gap-4 animate-in fade-in slide-in-from-top-4 duration-500">
                                <AlertCircle className="text-red-600" size={20} />
                                <div>
                                    <p className="text-red-800 text-sm font-bold">Error Occurred</p>
                                    <p className="text-red-600/80 text-[11px] font-medium">{error}</p>
                                </div>
                            </div>
                        )}

                        {success && (
                            <div className="p-4 bg-emerald-50 border border-emerald-100 rounded-xl flex items-center gap-4 animate-in fade-in slide-in-from-top-4 duration-500">
                                <Shield className="text-emerald-600" size={20} />
                                <div>
                                    <p className="text-emerald-800 text-sm font-bold">Success!</p>
                                    <p className="text-emerald-600/80 text-[11px] font-medium">{success}</p>
                                </div>
                            </div>
                        )}

                        {/* Personal Information */}
                        <section className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm">
                            <div className="flex items-center gap-3 mb-6">
                                <div className="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center text-blue-600">
                                    <User size={20} />
                                </div>
                                <div>
                                    <h2 className="text-base font-bold text-slate-800">Personal Information</h2>
                                    <p className="text-slate-400 text-[11px] font-bold uppercase tracking-wider">Basic account information</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <InputField label="First Name" name="firstname" value={formData.firstname} placeholder="e.g. John" />
                                <InputField label="Last Name" name="lastname" value={formData.lastname} placeholder="e.g. Doe" />
                                <InputField label="Email Address" name="email" value={formData.email} disabled />

                                <div className="space-y-1.5">
                                    <label className="text-[10px] font-bold text-slate-500 uppercase tracking-widest ml-1">Phone Number</label>
                                    <div className="flex">
                                        <div className="flex items-center px-4 bg-slate-50 border border-r-0 border-slate-200 rounded-l-xl text-slate-500 font-bold text-xs">
                                            <span className="mr-2">🇧🇩</span> +880
                                        </div>
                                        <input
                                            name="phonenumber"
                                            value={formData.phonenumber}
                                            onChange={handleChange}
                                            className="flex-1 p-3 bg-white border border-slate-200 rounded-r-xl focus:ring-2 focus:ring-blue-500/10 focus:border-blue-500 outline-none transition-all text-sm font-medium text-slate-700 hover:border-slate-300"
                                            placeholder="1234567890"
                                        />
                                    </div>
                                </div>

                                <SelectField
                                    label="Language"
                                    name="language"
                                    value={formData.language}
                                    options={[
                                        { value: 'english', label: 'English' },
                                        { value: 'spanish', label: 'Spanish' },
                                        { value: 'french', label: 'French' },
                                        { value: 'german', label: 'German' },
                                        { value: 'italian', label: 'Italian' },
                                        { value: 'portuguese', label: 'Portuguese' },
                                        { value: 'russian', label: 'Russian' },
                                        { value: 'arabic', label: 'Arabic' },
                                        { value: 'chinese', label: 'Chinese' }
                                    ]}
                                />
                            </div>
                        </section>

                        {/* Billing Address */}
                        <section className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm">
                            <div className="flex items-center gap-3 mb-6">
                                <div className="w-10 h-10 bg-purple-50 rounded-lg flex items-center justify-center text-purple-600">
                                    <MapPin size={20} />
                                </div>
                                <div>
                                    <h2 className="text-base font-bold text-slate-800">Billing Address</h2>
                                    <p className="text-slate-400 text-[11px] font-bold uppercase tracking-wider">Company and physical location</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <InputField label="Company Name" name="companyname" value={formData.companyname} placeholder="e.g. ACME Corp" />
                                <InputField label="Address Line 1" name="address1" value={formData.address1} placeholder="Street address" />
                                <InputField label="Address Line 2" name="address2" value={formData.address2} placeholder="Suite, floor, etc." />
                                <InputField label="City" name="city" value={formData.city} placeholder="e.g. New York" />

                                <SelectField
                                    label="Country"
                                    name="country"
                                    value={formData.country}
                                    options={Object.entries(countries || {}).length > 0
                                        ? Object.entries(countries).map(([code, name]) => ({ value: String(code), label: String(name) }))
                                        : [{ value: 'BD', label: 'Bangladesh' }]
                                    }
                                />

                                <div className="grid grid-cols-2 gap-4">
                                    <InputField label="State/Region" name="state" value={formData.state} placeholder="e.g. NY" />
                                    <InputField label="Zip Code" name="postcode" value={formData.postcode} placeholder="10001" />
                                </div>

                                <SelectField
                                    label="Payment Method"
                                    name="paymentmethod"
                                    value={formData.paymentmethod}
                                    options={[
                                        { value: '', label: 'Use Default (Set Per Order)' },
                                        ...paymentMethods.map(m => ({ value: m.module, label: m.displayName }))
                                    ]}
                                />

                                <SelectField
                                    label="Default Billing Contact"
                                    name="billingcid"
                                    value={formData.billingcid}
                                    options={[{ value: '0', label: 'Use Default Contact (Details Above)' }]}
                                />
                            </div>
                        </section>

                        {/* Additional Information (Custom Fields) */}
                        <section className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm">
                            <div className="flex items-center gap-3 mb-6">
                                <div className="w-10 h-10 bg-amber-50 rounded-lg flex items-center justify-center text-amber-600">
                                    <Building size={20} />
                                </div>
                                <div>
                                    <h2 className="text-base font-bold text-slate-800">Additional Information</h2>
                                    <p className="text-slate-400 text-[11px] font-bold uppercase tracking-wider">Extra account configuration</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                {client?.customfields && client.customfields.length > 0 ? (
                                    client.customfields.map((field: any) => (
                                        <div key={field.id}>
                                            <InputField
                                                label={field.name}
                                                name={`customfield[${field.id}]`}
                                                value={formData.customfields?.[field.id] || ''}
                                                placeholder={`Enter ${field.name}`}
                                            />
                                        </div>
                                    ))
                                ) : (
                                    <div className="col-span-full py-6 text-center bg-slate-50 rounded-lg border border-dashed border-slate-200">
                                        <p className="text-slate-400 text-[11px] font-bold uppercase tracking-widest">No additional custom fields found</p>
                                    </div>
                                )}
                            </div>
                        </section>

                        {/* Email Preferences */}
                        <section className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm">
                            <div className="flex items-center gap-3 mb-6">
                                <div className="w-10 h-10 bg-emerald-50 rounded-lg flex items-center justify-center text-emerald-600">
                                    <Bell size={20} />
                                </div>
                                <div>
                                    <h2 className="text-base font-bold text-slate-800">Email Preferences</h2>
                                    <p className="text-slate-400 text-[11px] font-bold uppercase tracking-wider">Manage your notifications</p>
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-y-2 gap-x-8">
                                {[
                                    'General Emails',
                                    'Invoice Emails',
                                    'Support Emails',
                                    'Product Emails',
                                    'Domain Emails',
                                    'Affiliate Emails'
                                ].map((label, idx) => (
                                    <label key={idx} className="flex items-center justify-between p-3 rounded-lg hover:bg-slate-50 transition-colors cursor-pointer">
                                        <span className="text-slate-600 font-bold text-xs tracking-tight">{label}</span>
                                        <div className="relative inline-flex items-center cursor-pointer">
                                            <input type="checkbox" defaultChecked className="sr-only peer" />
                                            <div className="w-9 h-5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-emerald-500"></div>
                                        </div>
                                    </label>
                                ))}
                            </div>

                            <div className="mt-8 p-6 bg-slate-900 rounded-xl relative overflow-hidden group/mailing">
                                <div className="relative z-10 flex flex-col md:flex-row items-center justify-between gap-6">
                                    <div className="space-y-1 text-center md:text-left">
                                        <h3 className="text-lg font-bold text-white tracking-tight">Join our newsletter</h3>
                                        <p className="text-slate-400 text-xs font-medium max-w-md">Stay updated with our latest news and exclusive offers.</p>
                                    </div>
                                    <div className="flex items-center gap-4 bg-white/5 p-3 rounded-lg border border-white/10">
                                        <span className="text-white font-bold uppercase tracking-wider text-[10px]">Subscribe</span>
                                        <div className="relative inline-flex items-center cursor-pointer">
                                            <input
                                                type="checkbox"
                                                name="marketing_emails"
                                                checked={formData.marketing_emails}
                                                onChange={handleChange}
                                                className="sr-only peer"
                                            />
                                            <div className="w-10 h-6 bg-slate-700 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>

                        {/* Bottom Actions */}
                        <div className="flex flex-col sm:flex-row gap-4 pt-6">
                            <button
                                onClick={handleSave}
                                disabled={saving}
                                className="flex-1 px-8 py-3 bg-blue-600 text-white font-bold rounded-lg shadow-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 text-sm uppercase tracking-widest"
                            >
                                {saving ? <RefreshCw className="animate-spin" size={18} /> : <Save size={18} />}
                                Save Profile Changes
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default MyDetailsView;
