import { Globe } from 'lucide-react';
import {
  Bar,
  BarChart as RechartsBarChart,
  CartesianGrid,
  Cell,
  Legend,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

import { EmptyState } from '@/Components/ui/empty-state';
import { formatNumber } from '@/lib/format';


import { ChartContainer } from '../ui/charts/ChartContainer';
import { useChartColors } from '../ui/charts/useChartColors';

interface CountryData {
  country: string;
  clicks: number;
  impressions: number;
  ctr: number;
  position: number;
}

interface CountryMapProps {
  data: CountryData[];
  height?: number;
  showGrid?: boolean;
  showLegend?: boolean;
  showTooltip?: boolean;
  className?: string;
  'aria-label'?: string;
}

/**
 * CountryMap renders a horizontal Recharts BarChart (top 20 countries by clicks),
 * NOT a geographic choropleth or SVG world map. The name is kept for API compatibility.
 */
export function CountryMap({
  data,
  height = 400,
  showGrid = true,
  showLegend = false,
  showTooltip = true,
  className,
  'aria-label': ariaLabel,
}: CountryMapProps) {
  const colors = useChartColors();

  if (data.length === 0) {
    return (
      <div className="flex items-center justify-center" style={{ height }}>
        <EmptyState
          icon={Globe}
          title="No geographic data available"
          description="Run an analysis with geographic segmentation enabled to see traffic by country."
          size="sm"
        />
      </div>
    );
  }

  // Calculate color intensity based on clicks
  // Find min and max clicks for normalization
  const clicks = data.map((d) => d.clicks);
  const minClicks = Math.min(...clicks);
  const maxClicks = Math.max(...clicks);
  const range = maxClicks - minClicks || 1;

  // Get color intensity (0-4 index into colors array)
  const getColorIndex = (clicks: number): number => {
    if (maxClicks === minClicks) return 2; // mid color if all same
    const normalized = (clicks - minClicks) / range;
    return Math.floor(normalized * (colors.length - 1));
  };

  // Sort by clicks descending and take top entries for better visualization
  const topCountries = [...data].sort((a, b) => b.clicks - a.clicks).slice(0, 20);

  return (
    <ChartContainer
      height={height}
      className={className}
      aria-label={ariaLabel || 'Top countries by clicks bar chart'}
    >
      <RechartsBarChart
        data={topCountries}
        layout="vertical"
        margin={{ top: 5, right: 30, left: 100, bottom: 5 }}
      >
        {showGrid && <CartesianGrid strokeDasharray="3 3" opacity={0.3} />}
        <XAxis type="number" tick={{ fontSize: 12 }} />
        <YAxis dataKey="country" type="category" tick={{ fontSize: 12 }} />
        {showTooltip && (
          <Tooltip
            formatter={
              ((value: number | undefined, name: string) => {
                const v = value ?? 0;
                if (name === 'clicks') return [formatNumber(v), 'Clicks'];
                return [v, name];
              }) as Parameters<typeof Tooltip>[0]['formatter']
            }
            labelFormatter={(label: unknown) => `Country: ${String(label)}`}
          />
        )}
        {showLegend && <Legend />}
        <Bar dataKey="clicks" radius={[0, 4, 4, 0]}>
          {topCountries.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={colors[getColorIndex(entry.clicks)]} />
          ))}
        </Bar>
      </RechartsBarChart>
    </ChartContainer>
  );
}
