import { Users } from 'lucide-react';
import { motion } from 'framer-motion';
import { GlassCard } from '../shared/GlassCard';
import { AnalyticsIconInfo } from '../shared/AnalyticsIconInfo';
import { CardIcon } from '../shared/CardIcon';
import { CardEmptyState } from '../shared/CardEmptyState';
import { StatusPill } from '../shared/StatusPill';
import { AI_BRAND_MAP } from '@/lib/brands';

interface AIReferredGroup {
    source: string;
    count: number;
}

interface AIReferredVisitsCardProps {
    groups: AIReferredGroup[];
    statusText?: string;
    className?: string;
    delay?: number;
}

function getBrandKeyFromSource(source: string) {
    const s = source.toLowerCase();
    if (s.includes('chatgpt') || s.includes('openai')) return 'gpt';
    if (s.includes('claude')) return 'claude';
    if (s.includes('perplexity')) return 'perplexity';
    if (s.includes('google')) return 'google';
    if (s.includes('gemini')) return 'gemini';
    if (s.includes('copilot')) return 'gpt';
    if (s.includes('grok') || s.includes('xai')) return 'xai';
    return null;
}

function getIcon(source: string) {
    const brandKey = getBrandKeyFromSource(source);
    return brandKey ? AI_BRAND_MAP[brandKey]?.icon : null;
}

function getDisplayCount(_source: string, count: number) {
    const safeCount = Number.isFinite(count) ? count : 0;
    return Math.round(safeCount);
}

export function AIReferredVisitsCard({ groups, statusText, className = '', delay = 0 }: AIReferredVisitsCardProps) {
    const hasAiVisits = groups.some((g) => getBrandKeyFromSource(g.source));

    return (
        <GlassCard className={`p-5 h-[360px] flex flex-col ${className}`} delay={delay}>
            <div className="flex items-center gap-3 mb-5">
                <AnalyticsIconInfo
                    widgetLabel="AI Referred Human Visits"
                    content={<p>Human visitors that arrived from AI assistants, grouped by the source that referred them.</p>}
                >
                    <CardIcon icon={Users} />
                </AnalyticsIconInfo>
                <h3 className="text-[16px] font-medium text-white tracking-[-0.32px]">AI Referred Human Visits</h3>
            </div>

            <div className="mb-3 grid grid-cols-[1fr_auto] gap-x-3 px-1">
                <span className="text-[12px] font-medium tracking-[-0.24px] text-white/50">Referred By</span>
                <span className="text-[12px] font-medium tracking-[-0.24px] text-white/50">Visits</span>
            </div>

            <div className="flex-1 min-h-0 overflow-y-auto glass-scrollbar -mr-1 pr-1">
                <div className="space-y-2">
                    {groups.length > 0 ? (
                        groups.map((group, i) => {
                            const iconSrc = getIcon(group.source);
                            const isAiReferred = Boolean(getBrandKeyFromSource(group.source));
                            const displayCount = getDisplayCount(group.source, group.count);

                            return (
                                <motion.div
                                    key={`${group.source}:${i}`}
                                    initial={{ opacity: 0, x: -10 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    transition={{ duration: 0.3, delay: delay + 0.1 + i * 0.08 }}
                                    className="grid grid-cols-[1fr_auto] items-center gap-x-3 rounded-lg border border-white/[0.08] bg-white/[0.03] px-2.5 sm:px-3 py-1.5"
                                >
                                    <div className="flex items-center gap-2 overflow-hidden">
                                        {iconSrc ? (
                                            <img src={iconSrc} alt="" loading="lazy" decoding="async" className={`size-4 shrink-0 object-contain${group.source.toLowerCase().includes('chatgpt') ? ' brightness-0 invert' : ''}`} />
                                        ) : (
                                            <div className="size-4 shrink-0 rounded-full bg-white/10 flex items-center justify-center text-[8px] text-white/40">?</div>
                                        )}
                                        <span className={`truncate text-[12px] tracking-[-0.24px] ${isAiReferred ? 'text-white font-medium' : 'text-white/70'}`}>
                                            {group.source}
                                        </span>
                                    </div>
                                    <span className="text-[12px] font-medium tabular-nums tracking-[-0.24px] text-white/85 whitespace-nowrap">
                                        {displayCount}
                                    </span>
                                </motion.div>
                            );
                        })
                    ) : (
                        <CardEmptyState
                            minHeight={200}
                            title="Awaiting AI referrals"
                            subtitle="Visitors arriving from ChatGPT, Claude, Perplexity and other AI assistants will appear here."
                        />
                    )}
                </div>
            </div>

            {statusText || hasAiVisits ? (
                <div className="mt-4">
                    <StatusPill text={statusText || 'AI-Direct Attribution Active'} variant={hasAiVisits ? 'info' : 'success'} />
                </div>
            ) : null}
        </GlassCard>
    );
}
