import React, { useState, useEffect } from 'react';
import axios from 'axios';
import {
    RefreshCw,
    Database,
    Calendar,
    AlertCircle,
    CheckCircle,
    Zap,
    Loader2,
    ChevronRight,
    Settings as SettingsIcon,
    X,
    Save,
    Lock,
    Globe,
    User as UserIcon,
    Clock,
    Activity,
    Shield
} from 'lucide-react';
import { clsx } from 'clsx';
import settingsService from '../services/settingsService';

const CrmImportWidget = () => {
    const [status, setStatus] = useState(null);
    const [loading, setLoading] = useState(true);
    const [running, setRunning] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const [config, setConfig] = useState({
        CRM_ADMIN_USER: '',
        CRM_ADMIN_PASS: '',
        CRM_LOGIN_URL: 'https://crm.youbroadband.co.ke/login'
    });
    const [saving, setSaving] = useState(false);

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

    const fetchSettings = async () => {
        try {
            const res = await settingsService.getSettings();
            setConfig(prev => ({ ...prev, ...res.data }));
        } catch (err) {
            console.error('Failed to load CRM settings');
        }
    };

    const fetchStatus = async () => {
        try {
            const res = await axios.get('http://localhost:5000/api/crm-import/status');
            setStatus(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleManualSync = async () => {
        if (running) return;
        setRunning(true);
        try {
            await axios.post('http://localhost:5000/api/crm-import/run');
            await fetchStatus();
        } catch (err) {
            console.error(err);
        } finally {
            setRunning(false);
        }
    };

    const handleSettingsSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            await settingsService.updateSettings(config);
            setShowSettings(false);
        } catch (err) {
            console.error(err);
        } finally {
            setSaving(false);
        }
    };

    if (loading) return (
        <div className="h-64 bg-slate-50 dark:bg-slate-900/50 rounded-[2.5rem] border border-slate-100 dark:border-slate-800 animate-pulse flex items-center justify-center">
            <Loader2 className="w-8 h-8 animate-spin text-primary opacity-20" />
        </div>
    );

    return (
        <div className="premium-card !p-0 overflow-hidden flex flex-col h-full group relative bg-white/80 dark:bg-slate-900/80 backdrop-blur-2xl">
            <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-full blur-3xl -mr-16 -mt-16 pointer-events-none" />

            <div className="p-8 border-b border-slate-100/50 dark:border-slate-800/50 flex justify-between items-center relative z-10">
                <div className="flex items-center gap-4">
                    <div className="w-14 h-14 bg-primary text-white rounded-[1.25rem] flex items-center justify-center shadow-2xl shadow-primary/30 group-hover:rotate-6 transition-transform duration-500">
                        <Database className="w-7 h-7" />
                    </div>
                    <div>
                        <h3 className="text-sm font-black text-slate-800 dark:text-white uppercase tracking-wider">CRM Integration</h3>
                        <p className="text-[10px] text-slate-400 dark:text-slate-500 font-bold uppercase tracking-widest mt-1">M-Pesa Ledger</p>
                    </div>
                </div>
                <div className="flex items-center gap-3">
                    <button
                        onClick={() => setShowSettings(!showSettings)}
                        className={clsx(
                            "p-3 rounded-2xl transition-all",
                            showSettings
                                ? "bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300"
                                : "bg-slate-50 dark:bg-slate-900 text-slate-400 hover:text-primary"
                        )}
                    >
                        {showSettings ? <X className="w-4 h-4" /> : <SettingsIcon className="w-4 h-4" />}
                    </button>
                    <button
                        onClick={handleManualSync}
                        disabled={running || showSettings}
                        className={clsx(
                            "px-6 py-3 rounded-2xl transition-all flex items-center gap-2 text-[10px] font-black uppercase tracking-widest",
                            (running || showSettings)
                                ? "bg-slate-100 dark:bg-slate-800 text-slate-400"
                                : "btn-primary !py-3 shadow-xl"
                        )}
                    >
                        {running ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4 text-amber-300" />}
                        {running ? 'Syncing...' : 'Sync Now'}
                    </button>
                </div>
            </div>

            <div className="flex-1 relative min-h-[300px]">
                {showSettings ? (
                    <form onSubmit={handleSettingsSave} className="absolute inset-0 z-20 bg-white/95 dark:bg-slate-900/95 backdrop-blur-md p-8 space-y-6 animate-in slide-in-from-top-4 duration-500">
                        <div className="space-y-5">
                            <div className="space-y-2">
                                <label className="premium-label">CRM Login URL</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-primary" />
                                    <input
                                        type="text"
                                        className="premium-input !pl-11 !text-xs !py-3"
                                        value={config.CRM_LOGIN_URL}
                                        onChange={e => setConfig({ ...config, CRM_LOGIN_URL: e.target.value })}
                                    />
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <label className="premium-label">Username</label>
                                    <div className="relative group/input">
                                        <UserIcon className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary" />
                                        <input
                                            type="text"
                                            className="premium-input !pl-11 !text-xs !py-3"
                                            value={config.CRM_ADMIN_USER}
                                            onChange={e => setConfig({ ...config, CRM_ADMIN_USER: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <label className="premium-label">Password</label>
                                    <div className="relative group/input">
                                        <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary" />
                                        <input
                                            type="password"
                                            className="premium-input !pl-11 !text-xs !py-3"
                                            value={config.CRM_ADMIN_PASS}
                                            onChange={e => setConfig({ ...config, CRM_ADMIN_PASS: e.target.value })}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <button
                            type="submit"
                            disabled={saving}
                            className="w-full btn-primary py-4 !shadow-xl flex items-center justify-center gap-3"
                        >
                            {saving ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
                            <span className="text-[11px] font-black uppercase tracking-[0.2em]">Save Settings</span>
                        </button>
                    </form>
                ) : null}

                <div className="p-8 grid grid-cols-2 gap-6 h-full">
                    <div className="p-6 bg-slate-50 dark:bg-slate-900/40 rounded-3xl border border-slate-100 dark:border-slate-800 group/stat hover:border-emerald-500/30 transition-all duration-500">
                        <div className="flex items-center gap-2 mb-4">
                            <CheckCircle className="w-4 h-4 text-emerald-500" />
                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest pl-1">Transactions Imported</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                            <span className="text-3xl font-black text-slate-800 dark:text-white group-hover/stat:scale-110 origin-left transition-transform tabular-nums">{status?.importedToday || 0}</span>
                            <span className="text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-tighter">Records</span>
                        </div>
                    </div>

                    <div className="p-6 bg-slate-50 dark:bg-slate-900/40 rounded-3xl border border-slate-100 dark:border-slate-800 group/stat hover:border-blue-500/30 transition-all duration-500">
                        <div className="flex items-center gap-2 mb-4">
                            <RefreshCw className="w-4 h-4 text-blue-500" />
                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest pl-1">Duplicates Skipped</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                            <span className="text-3xl font-black text-slate-800 dark:text-white tabular-nums">{status?.skippedToday || 0}</span>
                            <span className="text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-tighter">Already Exists</span>
                        </div>
                    </div>

                    <div className="p-6 bg-slate-50 dark:bg-slate-900/40 rounded-3xl border border-slate-100 dark:border-slate-800 group/stat hover:border-rose-500/30 transition-all duration-500">
                        <div className="flex items-center gap-2 mb-4">
                            <AlertCircle className="w-4 h-4 text-rose-500" />
                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest pl-1">Errors</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                            <span className="text-3xl font-black text-rose-600 tabular-nums">{status?.errorCount || 0}</span>
                            <span className="text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-tighter">Failed</span>
                        </div>
                    </div>

                    <div className="p-6 bg-slate-50 dark:bg-slate-900/40 rounded-3xl border border-slate-100 dark:border-slate-800 flex flex-col justify-center">
                        <div className="flex items-center gap-2 mb-2">
                            <div className={clsx(
                                "w-2.5 h-2.5 rounded-full shadow-[0_0_12px] group-hover:scale-110 transition-transform",
                                status?.status === 'Healthy' ? "bg-emerald-500 shadow-emerald-500" : "bg-rose-500 shadow-rose-500"
                            )}></div>
                            <span className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">System Status</span>
                        </div>
                        <span className={clsx(
                            "text-sm font-black uppercase tracking-widest italic",
                            status?.status === 'Healthy' ? "text-emerald-500" : "text-rose-500"
                        )}>{status?.status || 'OFFLINE'}</span>
                    </div>

                    <div className="col-span-2 p-8 bg-slate-900 dark:bg-black rounded-[2rem] text-white relative overflow-hidden group/last">
                        <div className="absolute top-0 right-0 p-4 opacity-10 group-hover/last:opacity-30 transition-opacity">
                            <Activity className="w-12 h-12" />
                        </div>
                        <div className="flex justify-between items-center mb-2 relative z-10">
                            <span className="text-[10px] font-black text-slate-500 uppercase tracking-[0.3em]">Last Sync Time</span>
                            <div className="w-3 h-3 bg-emerald-500 rounded-full animate-ping opacity-20" />
                        </div>
                        <p className="text-lg font-black italic tracking-tight relative z-10 tabular-nums">
                            {status?.lastSync ? new Date(status.lastSync).toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' }) : 'Never'}
                        </p>
                        <div className="mt-6 pt-6 border-t border-white/5 flex justify-between items-center relative z-10">
                            <div className="flex items-center gap-2">
                                <Shield className="w-4 h-4 text-primary" />
                                <span className="text-[9px] font-black text-white/40 uppercase tracking-[0.2em]">Secure Connection</span>
                            </div>
                            <span className="text-[9px] font-black text-amber-500 uppercase tracking-widest flex items-center gap-2">
                                <Zap className="w-3 h-3 fill-amber-500" /> Source System
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div className="px-10 py-5 bg-primary/5 dark:bg-primary/10 border-t border-primary/10">
                <p className="text-[9px] text-primary dark:text-indigo-400 font-black uppercase tracking-[0.2em] leading-relaxed text-center opacity-70 italic">
                    Automated sync runs daily at 00:00. Manual sync fetches today's transactions.
                </p>
            </div>
        </div>
    );
};

export default CrmImportWidget;
