import { Bot } 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 CrawlerLog {
    timestamp: string;
    agent: string;
    action: string;
    ip: string;
    visits?: number;
}

interface CrawlerLogsCardProps {
    logs: CrawlerLog[];
    isActive: boolean;
    totalCrawlerCount?: number;
    className?: string;
    delay?: number;
}

function formatCount(n: number): string {
    if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`;
    if (n >= 10_000) return `${(n / 1000).toFixed(0)}k`;
    if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
    return `${Math.round(n)}`;
}

const BOT_KEY_MAP: Record<string, string> = {
    gptbot: 'gpt',
    'chatgpt-user': 'gpt',
    claudebot: 'claude',
    'claude-web': 'claude',
    googleother: 'google',
    googlebot: 'google',
    'google-extended': 'google',
    perplexitybot: 'perplexity',
    bingbot: 'bing',
    semrushbot: 'semrush',
    ahrefsbot: 'ahrefs',
};

function getBotBrandKey(agent: string) {
    return BOT_KEY_MAP[agent.toLowerCase()] ?? agent.toLowerCase();
}

function getBotIcon(agent: string) {
    return AI_BRAND_MAP[getBotBrandKey(agent)]?.icon;
}

function getBotLabel(agent: string) {
    const key = getBotBrandKey(agent);
    return AI_BRAND_MAP[key]?.label ?? agent;
}

export function CrawlerLogsCard({ logs, isActive, totalCrawlerCount = 0, className = '', delay = 0 }: CrawlerLogsCardProps) {
    return (
        <GlassCard className={`p-5 h-[360px] flex flex-col ${className}`} delay={delay}>
            <div className="flex items-center gap-3 mb-5">
                <AnalyticsIconInfo
                    widgetLabel="Crawler Logs"
                    content={
                        <p>
                            Recent requests from known AI and SEO bots hitting your site. Use this to confirm crawlers are reaching the URLs you care about.
                        </p>
                    }
                >
                    <CardIcon icon={Bot} />
                </AnalyticsIconInfo>
                <div className="flex flex-1 items-center justify-between gap-3 min-w-0">
                    <h3 className="text-[16px] font-medium text-white tracking-[-0.32px]">Crawler Logs</h3>
                    {totalCrawlerCount > 0 ? (
                        <span className="text-[16px] font-medium tracking-[-0.32px] text-white/80 whitespace-nowrap tabular-nums">
                            {formatCount(totalCrawlerCount)}
                        </span>
                    ) : null}
                </div>
            </div>

            <div className="mb-3 grid grid-cols-[minmax(0,1fr)_52px] sm:grid-cols-[minmax(0,1fr)_minmax(0,1.6fr)_52px] items-center gap-x-3 px-3 text-[11px] font-medium uppercase tracking-[0.06em] text-white/50">
                <span>Bot</span>
                <span className="hidden sm:block">URL</span>
                <span className="text-right">Visits</span>
            </div>

            <div className="flex-1 min-h-0 overflow-y-auto glass-scrollbar -mr-1 pr-1">
                <div className="space-y-2">
                    {logs.length === 0 ? (
                        <CardEmptyState
                            minHeight={200}
                            title="Listening for AI crawlers"
                            subtitle="Bot activity will appear here as soon as the first AI crawler reaches your site."
                        />
                    ) : (
                        logs.map((log, i) => {
                            const brandKey = getBotBrandKey(log.agent);
                            const iconSrc = getBotIcon(log.agent);
                            return (
                                <motion.div
                                    key={i}
                                    initial={{ opacity: 0, x: -10 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    transition={{ duration: 0.3, delay: Math.min(delay + 0.1 + i * 0.08, delay + 0.5) }}
                                    className="grid grid-cols-[minmax(0,1fr)_52px] sm:grid-cols-[minmax(0,1fr)_minmax(0,1.6fr)_52px] items-center gap-x-3 rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5"
                                >
                                    <div className="flex items-center gap-2 overflow-hidden">
                                        {iconSrc ? (
                                            <img src={iconSrc} alt="" className={`size-4 shrink-0 object-contain${brandKey === 'gpt' ? ' brightness-0 invert' : ''}`} />
                                        ) : null}
                                        <span className="truncate text-[12px] text-white tracking-[-0.24px]">{getBotLabel(log.agent)}</span>
                                    </div>
                                    <span className="hidden sm:block truncate text-[12px] text-white tracking-[-0.24px]" title={log.action}>{log.action}</span>
                                    <span className="text-right text-[12px] font-medium tabular-nums text-white/85 whitespace-nowrap tracking-[-0.24px]">{formatCount(log.visits ?? 1)}</span>
                                </motion.div>
                            );
                        })
                    )}
                </div>
            </div>

            {isActive ? (
                <div className="mt-4">
                    <StatusPill text="System Active" variant="active" />
                </div>
            ) : null}
        </GlassCard>
    );
}
