import React, { useState, useEffect } from 'react';
import crmService from '../services/crmService';
import { RefreshCw, CheckCircle, AlertCircle, Clock, Zap, ExternalLink, ArrowRight, Activity, ShieldCheck, Database, Link2 } from 'lucide-react';
import { clsx } from 'clsx';

const CrmAutomation = () => {
    const [status, setStatus] = useState(null);
    const [loading, setLoading] = useState(true);
    const [syncing, setSyncing] = useState(false);
    const [result, setResult] = useState(null);

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

    const fetchStatus = async () => {
        try {
            const res = await crmService.getStatus();
            setStatus(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleSync = async () => {
        setSyncing(true);
        setResult(null);
        try {
            const res = await crmService.runImport();
            setResult(res.data);
            await fetchStatus();
        } catch (err) {
            alert('Sync failed: ' + (err.response?.data?.error || err.message));
        } finally {
            setSyncing(false);
        }
    };

    if (loading) return (
        <div className="min-h-[60vh] flex flex-col items-center justify-center gap-4 animate-pulse">
            <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
            <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading...</p>
        </div>
    );

    return (
        <div className="space-y-10 animate-slide-up pb-20">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <Zap 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">CRM Integration</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">Transaction Sync</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">Active</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={handleSync}
                    disabled={syncing}
                    className={clsx(
                        "btn-primary flex items-center justify-center gap-3 px-8 transition-all duration-500 shadow-2xl w-full md:w-auto h-12 lg:h-14",
                        syncing && "opacity-50 cursor-not-allowed"
                    )}
                >
                    <RefreshCw className={clsx("w-4 h-4 shrink-0", syncing && "animate-spin")} />
                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">{syncing ? 'Syncing...' : 'Sync Now'}</span>
                </button>
            </div>

            {/* Metrics Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
                <div className="premium-card p-6 sm:p-8 group hover:scale-[1.02] transition-all duration-500 relative overflow-hidden">
                    <div className="absolute top-0 right-0 p-4 opacity-5 group-hover:scale-110 group-hover:opacity-10 transition-all duration-500 pointer-events-none">
                        <Activity className="w-12 h-12 sm:w-16 sm:h-16 text-primary shrink-0" />
                    </div>
                    <div className="space-y-4">
                        <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] truncate">Last Sync</p>
                        <h3 className="text-lg sm:text-xl font-black text-slate-800 dark:text-white tracking-tight truncate">
                            {status?.lastSync ? new Date(status.lastSync).toLocaleString() : 'Never'}
                        </h3>
                        <div className="flex items-center gap-2 px-3 py-1 bg-slate-50 dark:bg-slate-900 w-fit rounded-lg border border-slate-100 dark:border-slate-800 shrink-0">
                            <div className={clsx("w-2 h-2 rounded-full animate-pulse shrink-0", status?.status === 'Healthy' ? 'bg-emerald-500' : 'bg-rose-500')}></div>
                            <span className="text-[10px] font-black text-slate-500 dark:text-slate-400 uppercase tracking-widest whitespace-nowrap">{status?.status === 'Healthy' ? 'Connected' : (status?.status || 'Offline')}</span>
                        </div>
                    </div>
                </div>

                <div className="premium-card p-6 sm:p-8 group hover:scale-[1.02] transition-all duration-500">
                    <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] mb-2 truncate">Transactions (Today)</p>
                    <h3 className="text-3xl sm:text-4xl font-black text-emerald-500 tracking-tighter truncate">
                        {status?.importedToday || 0}
                    </h3>
                    <p className="text-[9px] sm:text-[10px] text-slate-400 dark:text-slate-600 mt-4 flex items-center gap-2 font-black uppercase tracking-widest truncate">
                        <CheckCircle className="w-3.5 h-3.5 text-emerald-500 shrink-0" />
                        Saved to Database
                    </p>
                </div>

                <div className="premium-card p-6 sm:p-8 group hover:scale-[1.02] transition-all duration-500">
                    <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] mb-2 truncate">Errors / Skipped</p>
                    <h3 className="text-3xl sm:text-4xl font-black text-rose-500 tracking-tighter truncate">
                        {status?.errorCount || 0}
                    </h3>
                    <p className="text-[9px] sm:text-[10px] text-slate-400 dark:text-slate-600 mt-4 flex items-center gap-2 font-black uppercase tracking-widest truncate">
                        <AlertCircle className="w-3.5 h-3.5 text-rose-500 shrink-0" />
                        Needs Review
                    </p>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 sm:gap-10">
                {/* Logic Panel */}
                <div className="premium-card flex flex-col h-full overflow-hidden">
                    <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-900/40">
                        <div className="flex items-center gap-3 sm:gap-4">
                            <div className="p-2.5 sm:p-3 bg-primary/10 rounded-2xl text-primary shrink-0">
                                <ShieldCheck className="w-5 h-5 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h3 className="text-base sm:text-lg font-black text-slate-800 dark:text-white tracking-tight truncate">Sync Information</h3>
                                <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest truncate">Integration details</p>
                            </div>
                        </div>
                    </div>
                    <div className="p-6 sm:p-10 space-y-8 sm:space-y-10 flex-1 relative">
                        <div className="absolute left-[2.75rem] sm:left-[3.25rem] top-10 sm:top-[4.5rem] bottom-10 w-0.5 bg-slate-100 dark:bg-slate-800" />

                        <div className="relative flex gap-4 sm:gap-6 group">
                            <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-2xl bg-white dark:bg-slate-800 text-primary flex items-center justify-center font-black text-xs shrink-0 z-10 border border-slate-100 dark:border-slate-700 shadow-sm transition-transform group-hover:scale-110">1</div>
                            <div className="space-y-1 min-w-0">
                                <h4 className="font-black text-sm text-slate-800 dark:text-white uppercase tracking-widest truncate">Fetch Data</h4>
                                <p className="text-xs text-slate-500 dark:text-slate-400 leading-relaxed font-bold">The system connects to the CRM and downloads the latest M-Pesa transactions.</p>
                            </div>
                        </div>

                        <div className="relative flex gap-4 sm:gap-6 group">
                            <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-2xl bg-white dark:bg-slate-800 text-primary flex items-center justify-center font-black text-xs shrink-0 z-10 border border-slate-100 dark:border-slate-700 shadow-sm transition-transform group-hover:scale-110">2</div>
                            <div className="space-y-1 min-w-0">
                                <h4 className="font-black text-sm text-slate-800 dark:text-white uppercase tracking-widest truncate">Check Duplicates</h4>
                                <p className="text-xs text-slate-500 dark:text-slate-400 leading-relaxed font-bold">Incoming transactions are checked against existing records to prevent double-entry.</p>
                            </div>
                        </div>

                        <div className="relative flex gap-4 sm:gap-6 group">
                            <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-2xl bg-white dark:bg-slate-800 text-primary flex items-center justify-center font-black text-xs shrink-0 z-10 border border-slate-100 dark:border-slate-700 shadow-sm transition-transform group-hover:scale-110">3</div>
                            <div className="space-y-1 min-w-0">
                                <h4 className="font-black text-sm text-slate-800 dark:text-white uppercase tracking-widest truncate">Save Records</h4>
                                <p className="text-xs text-slate-500 dark:text-slate-400 leading-relaxed font-bold">New, valid transactions are saved to the system database.</p>
                            </div>
                        </div>

                        <div className="pt-4 sm:pt-6">
                            <a
                                href="https://crm.youbroadband.co.ke/dashboard/billing/mpesa"
                                target="_blank"
                                rel="noreferrer"
                                className="inline-flex items-center justify-center gap-2 text-[10px] font-black text-primary hover:text-white transition-all bg-primary/5 hover:bg-primary px-6 py-4 rounded-2xl uppercase tracking-[0.2em] border border-primary/20 w-full sm:w-auto h-12 lg:h-14"
                            >
                                <ExternalLink className="w-3.5 h-3.5 shrink-0" />
                                <span className="whitespace-nowrap">Open CRM Dashboard</span>
                            </a>
                        </div>
                    </div>
                </div>

                {/* Session Result */}
                {result ? (
                    <div className="premium-card p-6 sm:p-10 animate-in slide-in-from-bottom-10 space-y-8 sm:space-y-10 border-emerald-500/20">
                        <div className="flex items-center gap-4 sm:gap-5">
                            <div className="p-3 sm:p-4 bg-emerald-500 rounded-2xl text-white shadow-xl shadow-emerald-500/20 animate-bounce shrink-0">
                                <CheckCircle className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h3 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight truncate">Sync Complete</h3>
                                <p className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-1 truncate">Time: {new Date().toLocaleTimeString()}</p>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                            <div className="p-5 sm:p-6 bg-emerald-500/5 dark:bg-emerald-500/10 rounded-3xl border border-emerald-500/10">
                                <p className="text-[9px] sm:text-[10px] font-black text-emerald-600 dark:text-emerald-400 uppercase tracking-widest mb-2 truncate">New Imports</p>
                                <p className="text-3xl sm:text-4xl font-black text-emerald-500 tracking-tighter truncate">{result.data?.imported || 0}</p>
                            </div>
                            <div className="p-5 sm:p-6 bg-slate-50/50 dark:bg-slate-900/50 rounded-3xl border border-slate-100 dark:border-slate-800">
                                <p className="text-[9px] sm:text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 truncate">No Change</p>
                                <p className="text-3xl sm:text-4xl font-black text-slate-500 dark:text-slate-400 tracking-tighter truncate">{result.data?.skipped || 0}</p>
                            </div>
                        </div>

                        {result.data?.errors?.length > 0 && (
                            <div className="space-y-4">
                                <p className="text-[10px] font-black text-rose-500 uppercase tracking-widest ml-1 truncate">Error Log</p>
                                <div className="space-y-3">
                                    {result.data.errors.slice(0, 3).map((err, i) => (
                                        <div key={i} className="p-4 bg-rose-500/5 dark:bg-rose-500/10 text-rose-500 rounded-2xl text-xs font-bold border border-rose-500/10 truncate">
                                            {err}
                                        </div>
                                    ))}
                                    {result.data.errors.length > 3 && (
                                        <p className="text-center text-slate-400 dark:text-slate-600 text-[10px] font-black uppercase tracking-widest mt-4">+{result.data.errors.length - 3} more errors</p>
                                    )}
                                </div>
                            </div>
                        )}

                        <div className="pt-6 border-t border-slate-100 dark:border-slate-800 shrink-0">
                            <button
                                onClick={() => setResult(null)}
                                className="w-full py-4 text-[10px] sm:text-[11px] font-black uppercase tracking-[0.3em] text-slate-400 hover:text-primary transition-all duration-300 h-12 sm:h-auto"
                            >
                                Close
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="flex flex-col items-center justify-center p-12 sm:p-20 bg-slate-50/50 dark:bg-slate-900/40 rounded-[2rem] sm:rounded-[2.5rem] border border-dashed border-slate-200 dark:border-slate-800/60 opacity-60 group">
                        <div className="w-16 h-16 sm:w-20 sm:h-20 bg-white dark:bg-slate-900 rounded-3xl shadow-sm flex items-center justify-center mb-6 sm:mb-8 border border-slate-100 dark:border-slate-800 group-hover:rotate-180 transition-transform duration-1000 shrink-0">
                            <RefreshCw className="w-8 h-8 text-slate-300 dark:text-slate-700 shrink-0" />
                        </div>
                        <p className="text-[10px] sm:text-[11px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-[0.25em] text-center leading-relaxed">
                            Ready to Sync.<br />Click 'Sync Now' to start.
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
};

export default CrmAutomation;
