import { useState } from 'react';
import { motion } from 'framer-motion';
import { Card } from '@/components/ui/Card';
import { cn } from '@/lib/cn';

interface DataPoint {
  date: string;
  mmr: number;
}

interface MMRHistoryChartProps {
  data: DataPoint[];
}

const ranges = ['1W', '1M', '3M', 'ALL'] as const;

export function MMRHistoryChart({ data }: MMRHistoryChartProps) {
  const [range, setRange] = useState<(typeof ranges)[number]>('1M');

  const filteredData = filterByRange(data, range);
  if (filteredData.length === 0) return null;

  const mmrs = filteredData.map((d) => d.mmr);
  const minMmr = Math.min(...mmrs) - 50;
  const maxMmr = Math.max(...mmrs) + 50;
  const mmrRange = maxMmr - minMmr || 1;

  const width = 600;
  const height = 200;
  const padding = { top: 10, bottom: 30, left: 50, right: 10 };
  const chartW = width - padding.left - padding.right;
  const chartH = height - padding.top - padding.bottom;

  const points = filteredData.map((d, i) => ({
    x: padding.left + (i / Math.max(filteredData.length - 1, 1)) * chartW,
    y: padding.top + chartH - ((d.mmr - minMmr) / mmrRange) * chartH,
  }));

  const line = points.map((p) => `${p.x},${p.y}`).join(' ');
  const area = `${padding.left},${padding.top + chartH} ${line} ${padding.left + chartW},${padding.top + chartH}`;

  const yTicks = 4;
  const yStep = mmrRange / yTicks;

  return (
    <Card>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-medium text-text-secondary uppercase tracking-wider">MMR History</h3>
        <div className="flex gap-1">
          {ranges.map((r) => (
            <button
              key={r}
              onClick={() => setRange(r)}
              className={cn(
                'relative px-3 py-1 text-xs font-medium rounded-md transition-colors',
                range === r ? 'text-amber-500' : 'text-text-muted hover:text-text-secondary'
              )}
            >
              {range === r && (
                <motion.div
                  layoutId="mmr-range"
                  className="absolute inset-0 bg-amber-500/10 rounded-md"
                  transition={{ type: 'spring', stiffness: 400, damping: 30 }}
                />
              )}
              <span className="relative z-10">{r}</span>
            </button>
          ))}
        </div>
      </div>

      <svg viewBox={`0 0 ${width} ${height}`} className="w-full" preserveAspectRatio="xMidYMid meet">
        <defs>
          <linearGradient id="mmr-area-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="rgba(245,158,11,0.2)" />
            <stop offset="100%" stopColor="rgba(245,158,11,0)" />
          </linearGradient>
        </defs>

        {Array.from({ length: yTicks + 1 }, (_, i) => {
          const mmrVal = Math.round(minMmr + yStep * i);
          const y = padding.top + chartH - (i / yTicks) * chartH;
          return (
            <g key={i}>
              <line x1={padding.left} y1={y} x2={padding.left + chartW} y2={y} stroke="rgba(255,255,255,0.05)" />
              <text x={padding.left - 8} y={y + 4} textAnchor="end" className="fill-text-muted text-[10px]">
                {mmrVal}
              </text>
            </g>
          );
        })}

        <motion.polygon
          points={area}
          fill="url(#mmr-area-grad)"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6 }}
        />

        <motion.polyline
          points={line}
          fill="none"
          stroke="#F59E0B"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          initial={{ pathLength: 0 }}
          animate={{ pathLength: 1 }}
          transition={{ duration: 1, ease: 'easeOut' }}
        />

        {points.length > 0 && (
          <circle
            cx={points[points.length - 1].x}
            cy={points[points.length - 1].y}
            r="4"
            fill="#F59E0B"
            stroke="#0A0A0F"
            strokeWidth="2"
          />
        )}
      </svg>
    </Card>
  );
}

function filterByRange(data: DataPoint[], range: string): DataPoint[] {
  if (range === 'ALL' || data.length === 0) return data;
  const now = new Date();
  const cutoff = new Date();
  if (range === '1W') cutoff.setDate(now.getDate() - 7);
  else if (range === '1M') cutoff.setMonth(now.getMonth() - 1);
  else if (range === '3M') cutoff.setMonth(now.getMonth() - 3);
  return data.filter((d) => new Date(d.date) >= cutoff);
}
