import { LayoutGrid } from 'lucide-react';

import { Suspense, useMemo } from 'react';

import { LazyLineChart } from '@/Components/ui/charts';
import { EmptyState } from '@/Components/ui/empty-state';

interface SiteWithStats {
  id: number;
  name: string;
  domain: string;
  traffic_change_percent: number;
  pending_recommendations: number;
  last_analysis_date: string | null;
  attention_flags: {
    declining_traffic: boolean;
    stale_analysis: boolean;
    has_pending_recommendations: boolean;
  };
  latest_clicks: number;
  latest_impressions: number;
}

interface CrossSiteTrafficChartProps {
  timeSeriesData: Record<string, unknown>[];
  sites: SiteWithStats[];
}

// Loading fallback for chart
const ChartLoader = () => (
  <div className="flex h-[300px] items-center justify-center">
    <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
  </div>
);

export default function CrossSiteTrafficChart({
  timeSeriesData,
  sites,
}: CrossSiteTrafficChartProps) {
  // Extract yKeys dynamically from the first data point (all keys except "date")
  const yKeys = useMemo(() => {
    if (timeSeriesData.length === 0) return [];

    const firstDataPoint = timeSeriesData[0];
    return Object.keys(firstDataPoint).filter((key) => key !== 'date');
  }, [timeSeriesData]);

  // Create a mapping from site_X_clicks to site names for the legend
  const dataWithLabels = useMemo(() => {
    if (timeSeriesData.length === 0) return [];

    // Create a mapping from site_X_clicks to friendly site names
    const siteMapping = sites.reduce(
      (acc, site) => {
        acc[`site_${site.id}_clicks`] = site.name;
        return acc;
      },
      {} as Record<string, string>,
    );

    // Transform the data to use friendly names as keys
    return timeSeriesData.map((dataPoint) => {
      const transformed: Record<string, unknown> = { date: dataPoint.date };

      yKeys.forEach((key) => {
        const friendlyName = siteMapping[key] || key;
        transformed[friendlyName] = dataPoint[key];
      });

      return transformed;
    });
  }, [timeSeriesData, sites, yKeys]);

  // Get friendly names for yKeys
  const friendlyYKeys = useMemo(() => {
    const siteMapping = sites.reduce(
      (acc, site) => {
        acc[`site_${site.id}_clicks`] = site.name;
        return acc;
      },
      {} as Record<string, string>,
    );

    return yKeys.map((key) => siteMapping[key] || key);
  }, [yKeys, sites]);

  if (sites.length === 0) {
    return (
      <div className="flex h-[300px] items-center justify-center">
        <EmptyState
          icon={LayoutGrid}
          title="No sites available"
          description="Add sites to see traffic trends across your portfolio"
          size="sm"
        />
      </div>
    );
  }

  return (
    <Suspense fallback={<ChartLoader />}>
      <LazyLineChart
        data={dataWithLabels}
        xKey="date"
        yKeys={friendlyYKeys}
        showLegend
        aria-label="Line chart showing traffic trends across all sites over time"
      />
    </Suspense>
  );
}
