import React, { useState, useMemo } from 'react';
import { motion } from 'framer-motion';
import { useMockStore } from '../data/mockStore';
import {
    Trophy, TrendingUp, DollarSign, Target, Crown, ShieldOff,
    Users, CheckCircle2, Clock, BarChart2, MapPin
} from 'lucide-react';
import { SpotlightCard } from '../components/SpotlightCard';
import AnimatedNumber from '../components/AnimatedNumber';
import { usePermissions } from '../hooks/usePermissions';

// ── Rank badge helper ────────────────────────────────────────────────────────
const rankBadge = (i) =>
    i === 0 ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-500/20 dark:text-yellow-300' :
    i === 1 ? 'bg-zinc-100 text-zinc-700 dark:bg-white/10 dark:text-zinc-300' :
    i === 2 ? 'bg-orange-100 text-orange-700 dark:bg-orange-500/20 dark:text-orange-300' :
              'text-zinc-500';

// ── Podium tier styling (gold / silver / bronze) ───────────────────────────────
// Solid metal bars with dark, clearly-legible rank numerals. Height encodes rank:
// 1st is tallest, then 2nd, then 3rd.
const PODIUM_TIERS = {
    1: {
        heightPx: 200,
        border: 'border-yellow-400',
        avatarRing: 'border-yellow-400',
        bar: 'bg-gradient-to-b from-yellow-300 to-yellow-500',
        numeral: 'text-yellow-900/80',
        text: 'text-yellow-600 dark:text-yellow-400',
        glow: 'bg-yellow-500',
    },
    2: {
        heightPx: 144,
        border: 'border-zinc-300',
        avatarRing: 'border-zinc-300',
        bar: 'bg-gradient-to-b from-zinc-200 to-zinc-400',
        numeral: 'text-zinc-700/80',
        text: 'text-zinc-500 dark:text-zinc-300',
        glow: 'bg-zinc-400',
    },
    3: {
        heightPx: 100,
        border: 'border-orange-400',
        avatarRing: 'border-orange-400',
        bar: 'bg-gradient-to-b from-orange-300 to-orange-500',
        numeral: 'text-orange-900/80',
        text: 'text-orange-600 dark:text-orange-400',
        glow: 'bg-orange-500',
    },
};

// ── Podium step (single column) ───────────────────────────────────────────────
// Bars grow from a shared baseline at a constant speed, so the shortest (bronze)
// finishes first, then silver, and the tallest (gold) lands last.
const PodiumStep = ({ agent, rank, metricKey, numberFormat = {} }) => {
    const tier = PODIUM_TIERS[rank];
    return (
        <div className="flex flex-col items-center z-10 mx-2 md:mx-4">
            <div className="mb-4 text-center">
                <div className="relative inline-block">
                    <div className={`w-16 h-16 md:w-20 md:h-20 rounded-full border-4 ${tier.avatarRing} flex items-center justify-center bg-zinc-900/5 dark:bg-zinc-800 shadow-xl overflow-hidden mb-2 relative z-10`}>
                        <span className="text-xl font-bold text-zinc-700 dark:text-zinc-300">
                            {agent.name.split(' ').map(n => n[0]).join('')}
                        </span>
                    </div>
                    {rank === 1 && <Crown size={24} className="absolute -top-4 -right-2 text-yellow-400 fill-yellow-400 animate-bounce" />}
                    <div className={`absolute inset-0 rounded-full blur-xl opacity-40 ${tier.glow}`} />
                </div>
                <h3 className="font-bold text-sm md:text-base text-zinc-900 dark:text-white truncate max-w-[100px]">{agent.name}</h3>
                <p className={`font-mono font-bold text-sm md:text-lg ${tier.text}`}>
                    <AnimatedNumber value={agent[metricKey]} duration={1.4} {...numberFormat} />
                </p>
            </div>
            <motion.div
                initial={{ height: 0 }}
                animate={{ height: tier.heightPx }}
                transition={{ duration: tier.heightPx / 100, ease: 'easeOut' }}
                className={`w-24 md:w-32 rounded-t-lg ${tier.bar} border-t border-x ${tier.border} shadow-lg relative overflow-hidden hover:brightness-110`}
            >
                <div className="absolute inset-x-0 top-0 h-[2px] bg-white/50" />
                <div className={`w-full h-full flex items-end justify-center pb-4 text-5xl font-black ${tier.numeral} select-none`}>{rank}</div>
            </motion.div>
        </div>
    );
};

// ── Podium (shared) ──────────────────────────────────────────────────────────
const TopPodium = ({ data, metricKey, numberFormat = {} }) => {
    if (data.length < 3) return null;
    const [first, second, third] = data;
    return (
        // Fixed min-height reserves the full podium space so the shared baseline
        // never shifts while the bars animate — they grow upward from the floor.
        <div className="flex items-end justify-center mb-12 pt-8 min-h-[380px]">
            <PodiumStep agent={second} rank={2} metricKey={metricKey} numberFormat={numberFormat} />
            <PodiumStep agent={first}  rank={1} metricKey={metricKey} numberFormat={numberFormat} />
            <PodiumStep agent={third}  rank={3} metricKey={metricKey} numberFormat={numberFormat} />
        </div>
    );
};

// ── Tab pill ─────────────────────────────────────────────────────────────────
const TabBtn = ({ active, onClick, icon: Icon, label, accent }) => (
    <button
        onClick={onClick}
        className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all border ${
            active
                ? accent
                : 'border-transparent text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white'
        }`}
    >
        <Icon size={15} /> {label}
    </button>
);

// ── Filter pill row ───────────────────────────────────────────────────────────
const FilterPills = ({ options, value, onChange }) => (
    <div className="bg-zinc-100 dark:bg-zinc-900/50 p-1 rounded-xl flex border border-zinc-200 dark:border-white/5">
        {options.map(o => (
            <button
                key={o.id}
                onClick={() => onChange(o.id)}
                className={`flex items-center gap-1.5 px-4 py-1.5 rounded-lg text-xs font-bold uppercase tracking-wider transition-all ${
                    value === o.id
                        ? 'bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white shadow-sm'
                        : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white'
                }`}
            >
                {o.icon && <o.icon size={11} />} {o.label}
            </button>
        ))}
    </div>
);

// ════════════════════════════════════════════════════════════════════════════
// MAIN PAGE
// ════════════════════════════════════════════════════════════════════════════
const LeaderboardPage = () => {
    const { users, salesHistory, canvasserHistory } = useMockStore();
    const { can } = usePermissions();

    // Tab: 'sales' | 'canvasser'
    const [tab, setTab] = useState('sales');

    // ── Sales filters ────────────────────────────────────────────────────────
    const [timeframe, setTimeframe] = useState('all');
    const [metric, setMetric]       = useState('revenue');

    // ── Canvasser filters ────────────────────────────────────────────────────
    const [cvTimeframe, setCvTimeframe] = useState('all');
    const [cvMetric, setCvMetric]       = useState('verified');

    // ── Agents ───────────────────────────────────────────────────────────────
    const agents = useMemo(() => users.filter(u => u.role === 'FIELD_AGENT'), [users]);

    // ── Date windows ─────────────────────────────────────────────────────────
    // Returns null for 'all' (no date filter), or a Date boundary for week/month.
    const getWindow = (tf) => {
        if (tf === 'all') return null;
        const now = new Date();
        if (tf === 'week') {
            const d = new Date(now);
            d.setDate(d.getDate() - d.getDay());
            d.setHours(0, 0, 0, 0);
            return d;
        }
        return new Date(now.getFullYear(), now.getMonth(), 1);
    };

    // ── Sales leaderboard data ───────────────────────────────────────────────
    const salesData = useMemo(() => {
        const since = getWindow(timeframe);
        return agents.map(agent => {
            const txs = salesHistory.filter(tx => {
                if (tx.agentId !== agent.id) return false;
                if (since === null) return true; // 'all time' — no date filter
                return new Date(tx.date) >= since;
            });
            const revenue   = txs.filter(t => t.status === 'closed_won').reduce((s, t) => s + t.amount, 0);
            const volume    = txs.filter(t => t.status === 'closed_won').length;
            const won       = txs.filter(t => t.status === 'closed_won').length;
            const lost      = txs.filter(t => t.status === 'closed_lost').length;
            const winRate   = (won + lost) > 0 ? (won / (won + lost)) * 100 : 0;
            return { ...agent, revenue, volume, winRate, totalDeals: won + lost };
        }).sort((a, b) => b[metric] - a[metric]);
    }, [agents, salesHistory, timeframe, metric]);

    // ── Canvasser leaderboard data ───────────────────────────────────────────
    // Single source of truth: canvasserHistory records, filtered by date window.
    //   verified   = records with status 'verified' OR 'converted' (converted is also verified)
    //   unverified = records with status 'unverified' (pending review)
    //   converted  = records with status 'converted' (became paying client)
    //   total      = all door-knock records in the window
    //   convRate   = converted / verified — share of verified leads that closed
    const canvasserData = useMemo(() => {
        const since = getWindow(cvTimeframe);
        return agents.map(agent => {
            const records = (canvasserHistory || []).filter(r => {
                if (r.agentId !== agent.id) return false;
                if (!since) return true;
                return new Date(r.date) >= since;
            });

            const verified   = records.filter(r => r.status === 'verified' || r.status === 'converted').length;
            const unverified = records.filter(r => r.status === 'unverified').length;
            const converted  = records.filter(r => r.status === 'converted').length;
            const total      = records.length;
            const convRate   = verified > 0 ? (converted / verified) * 100 : 0;

            return { ...agent, verified, unverified, converted, total, convRate };
        }).sort((a, b) => b[cvMetric] - a[cvMetric]);
    }, [agents, canvasserHistory, cvTimeframe, cvMetric]);

    // ── Permission guard ─────────────────────────────────────────────────────
    if (!can('leaderboard', 'view')) {
        return (
            <div className="min-h-full flex items-center justify-center p-8">
                <div className="text-center space-y-4 max-w-md">
                    <div className="mx-auto w-16 h-16 rounded-2xl bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center">
                        <ShieldOff size={28} className="text-zinc-400" />
                    </div>
                    <h2 className="text-xl font-bold text-zinc-900 dark:text-white">Access Restricted</h2>
                    <p className="text-sm text-zinc-500">You don't have permission to view the Leaderboard. Contact your org admin for access.</p>
                </div>
            </div>
        );
    }

    // ── Render ───────────────────────────────────────────────────────────────
    return (
        <div className="min-h-full p-8 max-w-7xl mx-auto space-y-8 pb-20">

            {/* ── Page header ── */}
            <header className="flex flex-col md:flex-row md:items-end justify-between gap-4">
                <div>
                    <h1 className="text-4xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-zinc-900 to-zinc-600 dark:from-white dark:to-white/60 mb-2 tracking-tight">
                        {tab === 'sales' ? 'Sales Leaderboard' : 'Canvasser Leaderboard'}
                    </h1>
                    <p className="text-zinc-500 dark:text-zinc-400 font-light">
                        {tab === 'sales'
                            ? 'Real-time performance rankings for the sales team.'
                            : 'Verified door-knock lead rankings for canvassers.'}
                    </p>
                </div>

                {/* ── Tab switcher ── */}
                <div className="flex items-center gap-2 bg-zinc-100 dark:bg-zinc-900/60 border border-zinc-200 dark:border-white/5 rounded-2xl p-1.5">
                    <TabBtn
                        active={tab === 'sales'}
                        onClick={() => setTab('sales')}
                        icon={DollarSign}
                        label="Sales"
                        accent="bg-white dark:bg-zinc-800 border-zinc-200 dark:border-white/10 text-blue-600 dark:text-blue-400 shadow-sm"
                    />
                    <TabBtn
                        active={tab === 'canvasser'}
                        onClick={() => setTab('canvasser')}
                        icon={MapPin}
                        label="Canvasser"
                        accent="bg-white dark:bg-zinc-800 border-zinc-200 dark:border-white/10 text-emerald-600 dark:text-emerald-400 shadow-sm"
                    />
                </div>
            </header>

            {/* ════════════════════════════════════════════════
                SALES TAB
            ════════════════════════════════════════════════ */}
            {tab === 'sales' && (
                <>
                    {/* Controls */}
                    <div className="flex flex-col sm:flex-row gap-3 flex-wrap">
                        <FilterPills
                            value={timeframe}
                            onChange={setTimeframe}
                            options={[
                                { id: 'all',   label: 'All Time'   },
                                { id: 'month', label: 'This Month' },
                                { id: 'week',  label: 'This Week'  },
                            ]}
                        />
                        <FilterPills
                            value={metric}
                            onChange={setMetric}
                            options={[
                                { id: 'revenue', icon: DollarSign,  label: 'Revenue'  },
                                { id: 'volume',  icon: Target,       label: 'Volume'   },
                                { id: 'winRate', icon: TrendingUp,   label: 'Win Rate' },
                            ]}
                        />
                    </div>

                    {/* Podium */}
                    <div className="relative">
                        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[300px] bg-blue-500/10 dark:bg-blue-900/20 blur-[100px] rounded-full pointer-events-none" />
                        <TopPodium
                            data={salesData}
                            metricKey={metric}
                            numberFormat={{
                                revenue: { prefix: '$', useLocaleString: true },
                                volume:  { suffix: ' Deals' },
                                winRate: { suffix: '%', decimals: 1 },
                            }[metric]}
                        />
                    </div>

                    {/* Full table */}
                    <SpotlightCard className="overflow-hidden">
                        <div className="p-6">
                            <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-4 flex items-center">
                                <Trophy size={18} className="mr-2 text-zinc-400" /> Full Rankings
                            </h3>
                            <div className="overflow-x-auto">
                                <table className="w-full text-left border-collapse">
                                    <thead>
                                        <tr className="text-xs font-bold text-zinc-400 uppercase tracking-wider border-b border-zinc-200 dark:border-white/5">
                                            <th className="pb-3 pl-4">Rank</th>
                                            <th className="pb-3">Agent</th>
                                            <th className={`pb-3 text-right ${metric === 'revenue' ? 'text-blue-500' : ''}`}>Revenue</th>
                                            <th className={`pb-3 text-right ${metric === 'volume'  ? 'text-blue-500' : ''}`}>Volume</th>
                                            <th className={`pb-3 text-right ${metric === 'winRate' ? 'text-blue-500' : ''}`}>Win Rate</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-zinc-100 dark:divide-white/5">
                                        {salesData.map((agent, i) => (
                                            <tr key={agent.id} className="group hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors">
                                                <td className="py-4 pl-4">
                                                    <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${rankBadge(i)}`}>{i + 1}</div>
                                                </td>
                                                <td className="py-4">
                                                    <div className="flex items-center gap-3">
                                                        <div className="w-8 h-8 rounded-full bg-zinc-200 dark:bg-zinc-700 flex items-center justify-center text-xs font-bold text-zinc-500 dark:text-zinc-400">
                                                            {agent.name.charAt(0)}
                                                        </div>
                                                        <div>
                                                            <div className="font-semibold text-zinc-900 dark:text-white">{agent.name}</div>
                                                            <div className="text-xs text-zinc-500">{agent.email}</div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className={`py-4 text-right font-mono font-medium ${metric === 'revenue' ? 'text-blue-600 dark:text-blue-400 font-bold' : 'text-zinc-500 dark:text-zinc-400'}`}>
                                                    <AnimatedNumber value={agent.revenue} prefix="$" useLocaleString duration={1.2} delay={i * 0.05} />
                                                </td>
                                                <td className={`py-4 text-right font-mono font-medium ${metric === 'volume' ? 'text-blue-600 dark:text-blue-400 font-bold' : 'text-zinc-500 dark:text-zinc-400'}`}>
                                                    <AnimatedNumber value={agent.volume} duration={1.2} delay={i * 0.05} /> Deals
                                                </td>
                                                <td className={`py-4 text-right font-mono font-medium ${metric === 'winRate' ? 'text-blue-600 dark:text-blue-400 font-bold' : 'text-zinc-500 dark:text-zinc-400'}`}>
                                                    <AnimatedNumber value={agent.winRate} decimals={1} duration={1.2} delay={i * 0.05} />%
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </SpotlightCard>
                </>
            )}

            {/* ════════════════════════════════════════════════
                CANVASSER TAB
            ════════════════════════════════════════════════ */}
            {tab === 'canvasser' && (
                <>
                    {/* Controls */}
                    <div className="flex flex-col sm:flex-row gap-3 flex-wrap">
                        <FilterPills
                            value={cvTimeframe}
                            onChange={setCvTimeframe}
                            options={[
                                { id: 'all',   label: 'All Time'   },
                                { id: 'month', label: 'This Month' },
                                { id: 'week',  label: 'This Week'  },
                            ]}
                        />
                        <FilterPills
                            value={cvMetric}
                            onChange={setCvMetric}
                            options={[
                                { id: 'verified',  icon: CheckCircle2, label: 'Verified'     },
                                { id: 'total',     icon: Users,         label: 'Door Knocks'  },
                                { id: 'convRate',  icon: BarChart2,     label: 'Conv. Rate'   },
                            ]}
                        />
                    </div>

                    {/* Podium */}
                    <div className="relative">
                        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[300px] bg-emerald-500/10 dark:bg-emerald-900/20 blur-[100px] rounded-full pointer-events-none" />
                        <TopPodium
                            data={canvasserData}
                            metricKey={cvMetric}
                            numberFormat={{
                                verified: {},
                                total:    {},
                                convRate: { suffix: '%', decimals: 1 },
                            }[cvMetric]}
                        />
                    </div>

                    {/* Stat summary cards */}
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                        {[
                            { label: 'Total Verified',      value: canvasserData.reduce((s, a) => s + a.verified,   0), color: 'text-emerald-500', icon: CheckCircle2 },
                            { label: 'Unverified (Pending)',value: canvasserData.reduce((s, a) => s + a.unverified, 0), color: 'text-amber-500',   icon: Clock        },
                            { label: 'Converted to Client', value: canvasserData.reduce((s, a) => s + a.converted,  0), color: 'text-blue-500',    icon: TrendingUp   },
                            { label: 'Total Door Knocks',   value: canvasserData.reduce((s, a) => s + a.total,      0), color: 'text-violet-500',  icon: MapPin       },
                        ].map(c => (
                            <SpotlightCard key={c.label} className="p-4">
                                <div className="flex items-center gap-2 mb-2">
                                    <c.icon size={14} className={c.color} />
                                    <span className="text-[11px] font-mono font-bold text-zinc-500 uppercase tracking-widest">{c.label}</span>
                                </div>
                                <p className={`text-2xl font-black font-mono ${c.color}`}>
                                    <AnimatedNumber value={c.value} duration={1.2} />
                                </p>
                            </SpotlightCard>
                        ))}
                    </div>

                    {/* Full table */}
                    <SpotlightCard className="overflow-hidden">
                        <div className="p-6">
                            <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-4 flex items-center gap-2">
                                <MapPin size={18} className="text-emerald-400" /> Canvasser Rankings
                            </h3>
                            <div className="overflow-x-auto">
                                <table className="w-full text-left border-collapse">
                                    <thead>
                                        <tr className="text-xs font-bold text-zinc-400 uppercase tracking-wider border-b border-zinc-200 dark:border-white/5">
                                            <th className="pb-3 pl-4">Rank</th>
                                            <th className="pb-3">Canvasser</th>
                                            <th className={`pb-3 text-right ${cvMetric === 'verified'  ? 'text-emerald-500' : ''}`}>Verified</th>
                                            <th className="pb-3 text-right text-amber-400">Unverified</th>
                                            <th className="pb-3 text-right">Converted</th>
                                            <th className={`pb-3 text-right ${cvMetric === 'convRate'  ? 'text-emerald-500' : ''}`}>Conv. Rate</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-zinc-100 dark:divide-white/5">
                                        {canvasserData.map((agent, i) => (
                                            <tr key={agent.id} className="group hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors">
                                                <td className="py-4 pl-4">
                                                    <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${rankBadge(i)}`}>{i + 1}</div>
                                                </td>
                                                <td className="py-4">
                                                    <div className="flex items-center gap-3">
                                                        <div className="w-8 h-8 rounded-full bg-emerald-500/15 flex items-center justify-center text-xs font-bold text-emerald-600 dark:text-emerald-400">
                                                            {agent.name.charAt(0)}
                                                        </div>
                                                        <div>
                                                            <div className="font-semibold text-zinc-900 dark:text-white">{agent.name}</div>
                                                            <div className="text-xs text-zinc-500">{agent.email}</div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className={`py-4 text-right font-mono font-medium ${cvMetric === 'verified' ? 'text-emerald-600 dark:text-emerald-400 font-bold' : 'text-zinc-500 dark:text-zinc-400'}`}>
                                                    <AnimatedNumber value={agent.verified} duration={1.2} delay={i * 0.05} />
                                                </td>
                                                <td className="py-4 text-right font-mono font-medium text-amber-500 dark:text-amber-400">
                                                    <AnimatedNumber value={agent.unverified} duration={1.2} delay={i * 0.05} />
                                                </td>
                                                <td className="py-4 text-right font-mono font-medium text-blue-500 dark:text-blue-400">
                                                    <AnimatedNumber value={agent.converted} duration={1.2} delay={i * 0.05} />
                                                </td>
                                                <td className={`py-4 text-right font-mono font-medium ${cvMetric === 'convRate' ? 'text-emerald-600 dark:text-emerald-400 font-bold' : 'text-zinc-500 dark:text-zinc-400'}`}>
                                                    <AnimatedNumber value={agent.convRate} decimals={1} duration={1.2} delay={i * 0.05} />%
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </SpotlightCard>
                </>
            )}

            <span className="attribution-ghost">igotsar.matyas | LynkedUpPro - Turns out roofing CRMs don't build themselves. Who knew?</span>
        </div>
    );
};

export default LeaderboardPage;
