import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { useTheme } from '../context/ThemeContext';
import { useMockStore } from '../data/mockStore';
import { usePermissions } from '../hooks/usePermissions';
import PermissionGate from '../components/PermissionGate';
import {
    Plus, Search, MapPin, Phone, Zap, FileText,
    Clock, User, ChevronRight, Filter, Lock,
    DoorOpen, MessageSquare,
} from 'lucide-react';

// ---------------------------------------------------------------------------
// Urgency badge
// ---------------------------------------------------------------------------
const URGENCY_CONFIG = {
    standard:  { label: 'Standard',  bg: 'bg-zinc-200 dark:bg-zinc-700',       text: 'text-zinc-600 dark:text-zinc-300' },
    high:      { label: 'High',      bg: 'bg-amber-100 dark:bg-amber-500/20',  text: 'text-amber-700 dark:text-amber-400' },
    emergency: { label: 'Emergency', bg: 'bg-red-100 dark:bg-red-500/20',      text: 'text-red-700 dark:text-red-400' },
};

const STATUS_CONFIG = {
    New:        { bg: 'bg-blue-100 dark:bg-blue-500/20',   text: 'text-blue-700 dark:text-blue-400' },
    Contacted:  { bg: 'bg-purple-100 dark:bg-purple-500/20', text: 'text-purple-700 dark:text-purple-400' },
    Appointed:  { bg: 'bg-emerald-100 dark:bg-emerald-500/20', text: 'text-emerald-700 dark:text-emerald-400' },
    Closed:     { bg: 'bg-zinc-100 dark:bg-zinc-700', text: 'text-zinc-500 dark:text-zinc-400' },
};

function UrgencyBadge({ urgency }) {
    const cfg = URGENCY_CONFIG[urgency] ?? URGENCY_CONFIG.standard;
    return (
        <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${cfg.bg} ${cfg.text}`}>
            {cfg.label}
        </span>
    );
}

function StatusBadge({ status }) {
    const cfg = STATUS_CONFIG[status] ?? STATUS_CONFIG.New;
    return (
        <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${cfg.bg} ${cfg.text}`}>
            {status}
        </span>
    );
}

// ---------------------------------------------------------------------------
// Relative time formatter
// ---------------------------------------------------------------------------
function timeAgo(isoString) {
    const diff = Math.floor((Date.now() - new Date(isoString)) / 1000);
    if (diff < 60) return 'just now';
    if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
    return `${Math.floor(diff / 86400)}d ago`;
}

// ---------------------------------------------------------------------------
// Lead Card
// ---------------------------------------------------------------------------
function LeadCard({ lead, index }) {
    const { theme } = useTheme();
    const isDark = theme === 'dark';
    const primaryPhone = lead.phones?.find(p => p.isPrimary) ?? lead.phones?.[0];

    return (
        <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ type: 'spring', stiffness: 280, damping: 28, delay: index * 0.04 }}
            className={`rounded-2xl border p-4 flex items-start gap-4 cursor-pointer transition-shadow duration-200 group
                ${isDark
                    ? 'bg-zinc-900/70 backdrop-blur-xl border-white/[0.08] hover:border-white/20 shadow-[0_4px_16px_rgba(0,0,0,0.3)]'
                    : 'bg-white border-zinc-200/60 shadow-sm hover:shadow-md'
                }`}
        >
            {/* Avatar */}
            <div
                className="w-10 h-10 rounded-xl flex items-center justify-center text-sm font-black uppercase text-white shrink-0"
                style={{ backgroundColor: '#3B82F6' }}
            >
                {(lead.firstName?.[0] ?? '?')}{(lead.lastName?.[0] ?? '')}
            </div>

            {/* Main info */}
            <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-semibold text-sm text-zinc-900 dark:text-white">
                        {lead.firstName} {lead.lastName}
                    </span>
                    <UrgencyBadge urgency={lead.urgency} />
                    <StatusBadge status={lead.status} />
                    {lead.isQuickCapture && (
                        <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-zinc-100 dark:bg-zinc-800 text-zinc-400">
                            <Zap size={8} />
                            Quick
                        </span>
                    )}
                </div>

                <div className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1">
                    {(lead.address || lead.city) && (
                        <span className="flex items-center gap-1 text-xs text-zinc-500 dark:text-zinc-400">
                            <MapPin size={10} className="shrink-0" />
                            {[lead.address, lead.city, lead.state].filter(Boolean).join(', ')}
                        </span>
                    )}
                    {primaryPhone?.number && (
                        <span className="flex items-center gap-1 text-xs text-zinc-500 dark:text-zinc-400">
                            <Phone size={10} className="shrink-0" />
                            {primaryPhone.number}
                        </span>
                    )}
                    {lead.leadSource && (
                        <span className="flex items-center gap-1 text-xs text-zinc-500 dark:text-zinc-400">
                            <FileText size={10} className="shrink-0" />
                            {lead.leadSource}
                        </span>
                    )}
                    {lead.canvasserName && (
                        <span className="flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400">
                            <DoorOpen size={10} className="shrink-0" />
                            {lead.canvasserName}
                        </span>
                    )}
                    {lead.referralNote && (
                        <span className="flex items-center gap-1 text-xs text-purple-600 dark:text-purple-400 max-w-[200px] truncate">
                            <MessageSquare size={10} className="shrink-0" />
                            {lead.referralNote}
                        </span>
                    )}
                </div>
            </div>

            {/* Right side */}
            <div className="flex flex-col items-end gap-1.5 shrink-0">
                <span className="flex items-center gap-1 text-[11px] text-zinc-400 dark:text-zinc-500">
                    <Clock size={10} />
                    {timeAgo(lead.createdAt)}
                </span>
                {lead.createdByName && (
                    <span className="flex items-center gap-1 text-[11px] text-zinc-400 dark:text-zinc-500">
                        <User size={10} />
                        {lead.createdByName.split(' ')[0]}
                    </span>
                )}
                <ChevronRight
                    size={14}
                    className="text-zinc-300 dark:text-zinc-600 group-hover:text-zinc-500 dark:group-hover:text-zinc-400 transition-colors mt-auto"
                />
            </div>
        </motion.div>
    );
}

// ---------------------------------------------------------------------------
// Empty state
// ---------------------------------------------------------------------------
function EmptyState({ isDark, onNewLead }) {
    return (
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ type: 'spring', stiffness: 280, damping: 28 }}
            className={`rounded-2xl border-2 border-dashed px-8 py-16 flex flex-col items-center justify-center gap-4 text-center
                ${isDark ? 'border-zinc-800' : 'border-zinc-200'}`}
        >
            <div className={`w-14 h-14 rounded-2xl flex items-center justify-center
                ${isDark ? 'bg-zinc-800' : 'bg-zinc-100'}`}
            >
                <FileText size={24} className="text-zinc-400" />
            </div>
            <div>
                <p className="font-['Barlow_Condensed'] font-black uppercase tracking-widest text-xl text-zinc-900 dark:text-white">
                    No Leads Yet
                </p>
                <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                    Capture your first lead at the door or from the office.
                </p>
            </div>
            <button
                type="button"
                onClick={onNewLead}
                className="flex items-center gap-2 px-5 py-2.5 rounded-xl font-bold text-sm uppercase tracking-widest text-white transition-all active:scale-[0.97] hover:opacity-90"
                style={{ backgroundColor: '#3B82F6' }}
            >
                <Plus size={14} />
                New Lead
            </button>
        </motion.div>
    );
}

// ---------------------------------------------------------------------------
// Main Page
// ---------------------------------------------------------------------------
export default function LeadsListPage() {
    const { theme } = useTheme();
    const { leads } = useMockStore();
    const { can } = usePermissions();
    const navigate = useNavigate();
    const isDark = theme === 'dark';

    const [search, setSearch] = useState('');

    const filtered = leads.filter(lead => {
        if (!search.trim()) return true;
        const q = search.toLowerCase();
        return (
            `${lead.firstName} ${lead.lastName}`.toLowerCase().includes(q) ||
            lead.address?.toLowerCase().includes(q) ||
            lead.city?.toLowerCase().includes(q) ||
            lead.leadSource?.toLowerCase().includes(q) ||
            lead.status?.toLowerCase().includes(q)
        );
    });

    return (
        <div className={`min-h-screen transition-colors duration-300 ${isDark ? 'bg-[#09090b]' : 'bg-zinc-100/80'}`}>
            <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 lg:py-10">

                {/* --- Header --- */}
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="font-['Barlow_Condensed'] font-black uppercase tracking-widest text-4xl leading-none text-zinc-900 dark:text-white">
                            Leads
                        </h1>
                        <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                            {leads.length} total lead{leads.length !== 1 ? 's' : ''}
                        </p>
                    </div>
                    {can('leads', 'log') ? (
                        <button
                            type="button"
                            onClick={() => navigate('/emp/fa/leads/new')}
                            className="flex items-center gap-2 px-4 py-2.5 rounded-xl font-bold text-sm uppercase tracking-widest text-white transition-all active:scale-[0.97] hover:opacity-90 shrink-0"
                            style={{ backgroundColor: '#3B82F6' }}
                        >
                            <Plus size={14} />
                            New Lead
                        </button>
                    ) : (
                        <div className="flex items-center gap-2 px-4 py-2.5 rounded-xl font-bold text-sm uppercase tracking-widest text-zinc-400 bg-zinc-200 dark:bg-zinc-800 cursor-not-allowed shrink-0" title="You don't have permission to create leads">
                            <Lock size={14} />
                            New Lead
                        </div>
                    )}
                </div>

                {/* --- Search bar --- */}
                {leads.length > 0 && (
                    <div className={`flex items-center rounded-xl border mb-4
                        bg-white dark:bg-zinc-800/60
                        border-zinc-200 dark:border-zinc-700
                        focus-within:border-blue-400 dark:focus-within:border-blue-500
                        focus-within:ring-2 focus-within:ring-blue-100 dark:focus-within:ring-blue-500/20
                        transition-all duration-150`}
                    >
                        <Search size={14} className="ml-4 shrink-0 text-zinc-400 pointer-events-none" />
                        <input
                            type="text"
                            value={search}
                            onChange={e => setSearch(e.target.value)}
                            placeholder="Search by name, address, source…"
                            className="flex-1 py-3 pl-3 pr-4 text-sm outline-none bg-transparent
                                text-zinc-800 dark:text-white placeholder-zinc-400 dark:placeholder-zinc-500"
                        />
                    </div>
                )}

                {/* --- List --- */}
                {leads.length === 0 ? (
                    <EmptyState isDark={isDark} onNewLead={() => navigate('/emp/fa/leads/new')} />
                ) : filtered.length === 0 ? (
                    <div className="text-center py-12 text-sm text-zinc-400 dark:text-zinc-500">
                        No leads match "{search}"
                    </div>
                ) : (
                    <div className="space-y-3">
                        <AnimatePresence>
                            {filtered.map((lead, i) => (
                                <LeadCard key={lead.id} lead={lead} index={i} />
                            ))}
                        </AnimatePresence>
                    </div>
                )}
            </div>
        </div>
    );
}
