import type { CSSProperties } from 'react';
import { useRef } from 'react';
import { createPortal } from 'react-dom';
import { ChartNoAxesColumnIncreasing } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer } from 'recharts';
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 { TrendBadge } from '../shared/TrendBadge';
import { AI_BRAND_MAP } from '@/lib/brands';

interface EngineEntry {
    key: string;
    label: string;
    count: number;
    icon?: string;
    color?: string;
}

interface AIDiscoveryTrafficCardProps {
    totalVisits: number;
    totalWithEstimate?: number;
    trend: number;
    previousTotal?: number;
    trendLabel?: string;
    chartData: Array<Record<string, any>>;
    engineBreakdown: EngineEntry[];
    statusText: string;
    windowLabel?: string;
    estimatedHumanReach?: number;
    claudeCrawler?: number;
    claudeUserLike?: number;
    gptCrawler?: number;
    gptUserLike?: number;
    extrapolationMethodology?: string;
    extrapolationMultiplier?: number;
    extrapolationHumanReachRatio?: 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 AI_TOOLTIP_KEYS = ['gpt', 'claude', 'google', 'perplexity', 'bing', 'meta', 'bytedance', 'apple', 'amazon', 'xai', 'deepseek', 'mistral', 'cohere'] as const;

const TOOLTIP_PANEL: CSSProperties = {
    boxSizing: 'border-box',
    width: 118,
    background: 'rgba(255, 255, 255, 0.02)',
    border: '0.75px solid rgba(255, 255, 255, 0.1)',
    backdropFilter: 'blur(5px)',
    WebkitBackdropFilter: 'blur(5px)',
    borderRadius: 8,
    padding: '13px 9px 10px',
    pointerEvents: 'none',
};

const TOTAL_STYLE: CSSProperties = {
    margin: 0,
    fontSize: 12,
    lineHeight: '13px',
    letterSpacing: '-0.24px',
    color: '#ffffff',
};

const DIVIDER_STYLE: CSSProperties = {
    height: 1,
    margin: '7px -9px 0',
    background: 'rgba(255, 255, 255, 0.1)',
};

const ENGINE_ROW_STYLE: CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    gap: 6,
    marginTop: 6,
};

const ENGINE_LABEL_STYLE: CSSProperties = {
    flex: 1,
    fontSize: 9.98,
    lineHeight: 1,
    letterSpacing: '-0.1996px',
    color: '#ffffff',
};

const ENGINE_VALUE_STYLE: CSSProperties = {
    fontSize: 8.317,
    lineHeight: 1,
    letterSpacing: '-0.1663px',
    color: 'rgba(255, 255, 255, 0.5)',
    textAlign: 'right',
};

function ChartTooltip(props: any) {
    const { active, payload, coordinate, containerRef } = props;
    if (!active || !payload?.length || !coordinate) return null;

    const rect = containerRef?.current?.getBoundingClientRect();
    const absX = (rect?.left ?? 0) + (coordinate.x ?? 0);
    const absY = (rect?.top ?? 0) + (coordinate.y ?? 0);

    const dataPoint = payload[0]?.payload;
    const total = dataPoint?.total ?? 0;

    const engines = AI_TOOLTIP_KEYS.filter((key) => (dataPoint?.[key] || 0) > 0)
        .map((key) => ({
            key,
            value: dataPoint[key] as number,
            label: AI_BRAND_MAP[key]?.label || key,
            icon: AI_BRAND_MAP[key]?.icon,
        }))
        .sort((a, b) => b.value - a.value);

    if (typeof document === 'undefined') return null;

    return createPortal(
        <div
            style={{
                position: 'fixed',
                left: absX,
                top: absY,
                transform: 'translate(-50%, -100%) translateY(-12px)',
                zIndex: 9999,
                pointerEvents: 'none',
            }}
        >
            <div style={TOOLTIP_PANEL}>
                <p style={TOTAL_STYLE}>{total} visits</p>
                {engines.length > 0 && <div style={DIVIDER_STYLE} />}
                {engines.map((engine) => (
                    <div key={engine.key} style={ENGINE_ROW_STYLE}>
                        {engine.icon ? (
                            <img
                                src={engine.icon}
                                alt=""
                                loading="lazy"
                                decoding="async"
                                style={{
                                    width: 12,
                                    height: 12,
                                    objectFit: 'contain',
                                    flexShrink: 0,
                                    filter: engine.key === 'gpt' ? 'brightness(0) invert(1)' : undefined,
                                }}
                            />
                        ) : (
                            <div style={{ width: 12, height: 12, flexShrink: 0 }} />
                        )}
                        <span style={ENGINE_LABEL_STYLE}>{engine.label}</span>
                        <span style={ENGINE_VALUE_STYLE}>{engine.value}</span>
                    </div>
                ))}
            </div>
        </div>,
        document.body,
    );
}

export function AIDiscoveryTrafficCard({
    totalVisits,
    trend,
    chartData,
    engineBreakdown,
    statusText,
    className = '',
    delay = 0,
}: AIDiscoveryTrafficCardProps) {
    const chartContainerRef = useRef<HTMLDivElement | null>(null);
    const visibleEngineBreakdown = engineBreakdown.slice(0, 4);
    const chartMax = chartData.reduce((m, p) => Math.max(m, Number(p.total) || 0), 0);
    const isChartEmpty = chartData.length === 0 || chartMax === 0;
    const isLowTraffic = chartMax > 0 && chartMax <= 3;
    const isSinglePoint = chartData.length === 1;
    const displayData = isSinglePoint
        ? [{ ...chartData[0], total: 0, name: '' }, chartData[0]]
        : chartData;
    const xTickInterval = displayData.length <= 8 ? 0 : Math.max(0, Math.floor(displayData.length / 7) - 1);

    return (
        <GlassCard className={`p-5 h-[360px] flex flex-col ${className}`} delay={delay}>
            <div className="flex items-center gap-3 mb-3">
                <AnalyticsIconInfo
                    widgetLabel="AI Discovery Traffic"
                    content={<p>Measured AI crawler and AI-assistant visibility for your site in the selected window.</p>}
                >
                    <CardIcon icon={ChartNoAxesColumnIncreasing} />
                </AnalyticsIconInfo>
                <h3 className="text-[16px] font-medium text-white tracking-[-0.32px]">AI Discovery Traffic</h3>
            </div>

            <div className="mb-2 flex items-baseline gap-1.5">
                <span className="text-[28px] leading-none font-medium text-white tracking-[-0.56px] tabular-nums">
                    {formatCount(totalVisits)}
                </span>
                <span className="text-[13px] text-white/60 tracking-[-0.26px]">visits</span>
                {trend !== 0 ? <TrendBadge value={trend} /> : null}
            </div>

            <div ref={chartContainerRef} className="min-h-0 flex-1 w-full">
                {isChartEmpty ? (
                    <CardEmptyState
                        className="size-full"
                        minHeight={120}
                        title="Listening for AI activity"
                        subtitle="The chart fills in as soon as the first AI crawler or assistant reaches your site."
                    />
                ) : (
                    <ResponsiveContainer width="100%" height="100%">
                        <AreaChart data={displayData} margin={{ top: 5, right: 8, left: 0, bottom: 0 }}>
                            <defs>
                                <linearGradient id="ai-traffic-fill" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="0%" stopColor="#68f349" stopOpacity={0.2} />
                                    <stop offset="100%" stopColor="#68f349" stopOpacity={0} />
                                </linearGradient>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="rgba(255,255,255,0.05)" />
                            <XAxis
                                dataKey="name"
                                axisLine={false}
                                tickLine={false}
                                interval={xTickInterval}
                                minTickGap={12}
                                tick={{ fill: 'rgba(255,255,255,0.5)', fontSize: 10 }}
                            />
                            <YAxis
                                axisLine={false}
                                tickLine={false}
                                tick={{ fill: 'rgba(255,255,255,0.5)', fontSize: 10 }}
                                width={32}
                                domain={isLowTraffic ? [0, Math.max(3, chartMax + 1)] : undefined}
                                allowDecimals={!isLowTraffic}
                            />
                            <RechartsTooltip
                                content={<ChartTooltip containerRef={chartContainerRef} />}
                                cursor={{ stroke: 'rgba(255,255,255,0.1)' }}
                                wrapperStyle={{ outline: 'none' }}
                            />
                            <Area
                                type="monotone"
                                dataKey="total"
                                stroke="#68f349"
                                strokeWidth={2}
                                fill="url(#ai-traffic-fill)"
                                dot={(isLowTraffic || isSinglePoint) ? { r: 3, fill: '#68f349', stroke: '#0b1f08', strokeWidth: 2 } : false}
                                activeDot={{ r: 5, fill: '#68f349', stroke: '#0b1f08', strokeWidth: 2 }}
                                animationDuration={1200}
                                animationEasing="ease-out"
                            />
                        </AreaChart>
                    </ResponsiveContainer>
                )}
            </div>

            {visibleEngineBreakdown.length > 0 ? (
                <div className="mt-3 flex flex-wrap gap-1.5">
                    {visibleEngineBreakdown.map((engine) => (
                        <div
                            key={engine.key}
                            className="flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.03] px-2.5 py-1"
                        >
                            {engine.icon ? (
                                <img src={engine.icon} alt="" loading="lazy" decoding="async" className={`size-4 shrink-0 object-contain${engine.key === 'gpt' ? ' brightness-0 invert' : ''}`} />
                            ) : null}
                            <span className="text-[12px] tracking-[-0.24px] text-white">{engine.label}</span>
                            <span className="text-[12px] font-medium tabular-nums tracking-[-0.24px] text-white/55">
                                {engine.count}
                            </span>
                        </div>
                    ))}
                </div>
            ) : null}

            <div className="mt-3">
                <StatusPill text={statusText} variant="active" />
            </div>
        </GlassCard>
    );
}
