import React, { useState, useMemo, memo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Download, ChevronDown, ChevronUp, Phone, MapPin, Globe, Search } from 'lucide-react';

const Dashboard = memo(({ stats, groupedData, onExport }) => {
    const [expandedNiche, setExpandedNiche] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');

    const toggleNiche = (niche) => {
        if (expandedNiche === niche) {
            setExpandedNiche(null);
        } else {
            setExpandedNiche(niche);
        }
    };

    const filteredNiches = useMemo(() => {
        return Object.keys(groupedData).filter(niche =>
            niche.toLowerCase().includes(searchTerm.toLowerCase())
        ).sort();
    }, [groupedData, searchTerm]);

    return (
        <div className="animate-fade-in">
            {/* Header / Stats */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '1.5rem', marginBottom: '3rem' }}>
                <StatCard title="Total de Negócios" value={stats.total} delay={0} />
                <StatCard title="Leads (Sem Site + Tel)" value={stats.noWebsite} delay={0.1} highlight />
                <StatCard title="Nichos Encontrados" value={stats.niches} delay={0.2} />
            </div>

            {/* Actions */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem', flexWrap: 'wrap', gap: '1rem' }}>
                <div style={{ position: 'relative', width: '300px' }}>
                    <Search size={18} style={{ position: 'absolute', left: '1rem', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-secondary)' }} />
                    <input
                        type="text"
                        placeholder="Buscar nicho..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        style={{
                            width: '100%',
                            padding: '0.75rem 1rem 0.75rem 2.5rem',
                            background: 'var(--surface-color)',
                            border: '1px solid var(--border-color)',
                            borderRadius: 'var(--radius-md)',
                            color: 'white',
                            outline: 'none'
                        }}
                    />
                </div>
                <button className="btn-primary" onClick={onExport} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <Download size={18} />
                    Exportar para WhatsApp Bulk
                </button>
            </div>

            {/* Niches List */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                {filteredNiches.map((niche, index) => (
                    <NicheGroup
                        key={niche}
                        niche={niche}
                        businesses={groupedData[niche]}
                        isExpanded={expandedNiche === niche}
                        onToggle={() => toggleNiche(niche)}
                        index={index}
                    />
                ))}
            </div>
        </div>
    );
});

Dashboard.displayName = 'Dashboard';

const StatCard = memo(({ title, value, delay, highlight }) => (
    <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay, duration: 0.5 }}
        className="glass-panel"
        style={{
            padding: '1.5rem',
            borderLeft: highlight ? '4px solid var(--accent-secondary)' : '1px solid var(--glass-border)'
        }}
    >
        <h3 style={{ color: 'var(--text-secondary)', fontSize: '0.875rem', marginBottom: '0.5rem' }}>{title}</h3>
        <p style={{ fontSize: '2rem', fontWeight: 700, color: highlight ? 'var(--accent-secondary)' : 'var(--text-primary)' }}>{value}</p>
    </motion.div>
));

StatCard.displayName = 'StatCard';

const NicheGroup = memo(({ niche, businesses, isExpanded, onToggle, index }) => {
    return (
        <motion.div
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: index * 0.05 }}
            className="glass-panel"
            style={{ overflow: 'hidden' }}
        >
            <div
                onClick={onToggle}
                style={{
                    padding: '1.5rem',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    cursor: 'pointer',
                    background: isExpanded ? 'rgba(255,255,255,0.03)' : 'transparent'
                }}
            >
                <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                    <div style={{
                        width: '40px',
                        height: '40px',
                        borderRadius: '10px',
                        background: 'var(--surface-hover)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontWeight: 'bold',
                        color: 'var(--accent-primary)'
                    }}>
                        {niche.charAt(0).toUpperCase()}
                    </div>
                    <div>
                        <h3 style={{ fontSize: '1.1rem', fontWeight: 600 }}>{niche}</h3>
                        <span style={{ fontSize: '0.875rem', color: 'var(--text-secondary)' }}>{businesses.length} leads potenciais</span>
                    </div>
                </div>
                {isExpanded ? <ChevronUp color="var(--text-secondary)" /> : <ChevronDown color="var(--text-secondary)" />}
            </div>

            <AnimatePresence>
                {isExpanded && (
                    <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.3 }}
                    >
                        <div style={{ padding: '0 1.5rem 1.5rem 1.5rem' }}>
                            <div style={{
                                display: 'grid',
                                gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
                                gap: '1rem',
                                marginTop: '1rem'
                            }}>
                                {businesses.map((biz) => (
                                    <BusinessCard key={biz.id} business={biz} />
                                ))}
                            </div>
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>
        </motion.div>
    );
});

NicheGroup.displayName = 'NicheGroup';

const BusinessCard = memo(({ business }) => (
    <div style={{
        background: 'var(--surface-color)',
        padding: '1rem',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--border-color)'
    }}>
        <h4 style={{ fontWeight: 600, marginBottom: '0.5rem', color: 'white' }}>{business.title}</h4>

        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
            {business.phone && (
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', color: 'var(--text-secondary)', fontSize: '0.875rem' }}>
                    <Phone size={14} color="var(--accent-secondary)" />
                    <span>{business.phone}</span>
                </div>
            )}

            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '0.5rem', color: 'var(--text-secondary)', fontSize: '0.875rem' }}>
                <MapPin size={14} style={{ marginTop: '2px', flexShrink: 0 }} />
                <span style={{ lineHeight: '1.3' }}>{business.street || business.address || 'Endereço não disponível'}</span>
            </div>

            {/* Debugging/Info: Show that it has no website explicitly if needed, but the list is filtered */}
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', color: '#ef4444', fontSize: '0.75rem', marginTop: '0.25rem' }}>
                <Globe size={12} />
                <span>Sem Website</span>
            </div>
        </div>
    </div>
));

BusinessCard.displayName = 'BusinessCard';

export default Dashboard;
