import { Smartphone } from 'lucide-react';
import {
  CartesianGrid,
  Legend,
  Line,
  LineChart as RechartsLineChart,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

import { formatNumber } from '@/lib/format';

import { ChartDataTable } from '../ui/ChartDataTable';
import { ChartContainer } from '../ui/charts/ChartContainer';
import { useChartColors } from '../ui/charts/useChartColors';
import { EmptyState } from '../ui/empty-state';

interface DeviceData {
  device: string;
  clicks: number;
  impressions: number;
  ctr: number;
  position: number;
}

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

export function DeviceChart({
  data,
  height = 300,
  showGrid = true,
  showLegend = true,
  showTooltip = true,
  className,
  'aria-label': ariaLabel,
}: DeviceChartProps) {
  const colors = useChartColors();

  if (data.length === 0) {
    return (
      <div style={{ height }}>
        <EmptyState
          icon={Smartphone}
          title="No device data available"
          description="Run an analysis with device segmentation enabled to see how your traffic breaks down by device type."
          size="sm"
        />
      </div>
    );
  }

  return (
    <div>
      <ChartContainer
        height={height}
        className={className}
        aria-label={ariaLabel || 'Device performance trend chart'}
      >
        <RechartsLineChart data={data}>
          {showGrid && <CartesianGrid strokeDasharray="3 3" opacity={0.3} />}
          <XAxis dataKey="device" tick={{ fontSize: 12 }} />
          <YAxis tick={{ fontSize: 12 }} />
          {showTooltip && (
            <Tooltip
              formatter={
                ((value: number | undefined, name: string) => {
                  const v = value ?? 0;
                  if (name === 'clicks') return [formatNumber(v), 'Clicks'];
                  if (name === 'impressions') return [formatNumber(v), 'Impressions'];
                  if (name === 'ctr') return [(v * 100).toFixed(2) + '%', 'CTR'];
                  if (name === 'position') return [v.toFixed(2), 'Avg Position'];
                  return [v, name];
                }) as Parameters<typeof Tooltip>[0]['formatter']
              }
              labelFormatter={(label: unknown) => `Device: ${String(label)}`}
            />
          )}
          {showLegend && <Legend />}
          <Line
            type="monotone"
            dataKey="clicks"
            stroke={colors[0]}
            strokeWidth={2}
            dot={{ r: 4 }}
            name="Clicks"
          />
          <Line
            type="monotone"
            dataKey="impressions"
            stroke={colors[1]}
            strokeWidth={2}
            dot={{ r: 4 }}
            name="Impressions"
          />
        </RechartsLineChart>
      </ChartContainer>

      {/* Accessible data table companion to the chart */}
      <ChartDataTable
        data={data as unknown as Array<Record<string, unknown>>}
        columns={[
          { key: 'device', label: 'Device' },
          { key: 'clicks', label: 'Clicks' },
          { key: 'impressions', label: 'Impressions' },
          { key: 'ctr', label: 'CTR' },
          { key: 'position', label: 'Avg Position' },
        ]}
        caption="Device performance data: Clicks, impressions, CTR, and average position by device type"
      />
    </div>
  );
}
