'use client';

import { SEO_PERF_30D, formatNumber } from '@/lib/mock-data';
import { motion } from 'framer-motion';
import { useMemo, useState } from 'react';
import {
  Area,
  AreaChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

type Metric = 'impressions' | 'clicks' | 'position';

const TABS: { key: Metric; label: string }[] = [
  { key: 'impressions', label: 'Impressions' },
  { key: 'clicks', label: 'Clics' },
  { key: 'position', label: 'Position moy.' },
];

interface TooltipPayload {
  value: number;
}

function CustomTooltip({
  active,
  payload,
  label,
  metric,
}: { active?: boolean; payload?: TooltipPayload[]; label?: string; metric: Metric }) {
  if (!active || !payload?.length) return null;
  const val = payload[0].value as number;
  const formatted = metric === 'position' ? `#${val}` : formatNumber(val);
  return (
    <div className="bg-bg-card border border-border rounded-xl px-3 py-2 text-[12px] shadow-xl">
      <p className="text-text-dim mb-0.5">{label}</p>
      <p className="text-text font-semibold font-mono">{formatted}</p>
    </div>
  );
}

export function PerfChart() {
  const [metric, setMetric] = useState<Metric>('impressions');

  const stats = useMemo(() => {
    const vals = SEO_PERF_30D.map((d) => d[metric]);
    const total = vals.reduce((a, b) => a + b, 0);
    const avg = total / vals.length;
    const peak = Math.max(...vals);
    return { total, avg, peak };
  }, [metric]);

  const isPosition = metric === 'position';
  const gradientId = 'perf-gradient';

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4, ease: 'easeOut', delay: 0.15 }}
      className="bg-bg-card border border-border rounded-2xl p-5 flex flex-col gap-4"
    >
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h2 className="text-[14px] font-semibold tracking-tight">
            Performance SEO — 30 derniers jours
          </h2>
        </div>
        <div className="flex gap-1 p-1 bg-bg rounded-lg border border-border">
          {TABS.map((tab) => (
            <button
              type="button"
              key={tab.key}
              onClick={() => setMetric(tab.key)}
              className={`px-3 py-1.5 rounded-md text-[12px] transition-all font-medium ${
                metric === tab.key
                  ? 'bg-accent/20 text-accent-light border border-accent/30'
                  : 'text-text-dim hover:text-text'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Résumé stats */}
      <div className="grid grid-cols-3 gap-3">
        {[
          {
            label: 'Total',
            val: isPosition ? `#${stats.peak.toFixed(1)}` : formatNumber(stats.total),
          },
          {
            label: 'Moyenne',
            val: isPosition ? `#${stats.avg.toFixed(1)}` : formatNumber(stats.avg),
          },
          {
            label: 'Pic',
            val: isPosition
              ? `#${Math.min(...SEO_PERF_30D.map((d) => d.position)).toFixed(1)}`
              : formatNumber(stats.peak),
          },
        ].map((s) => (
          <div key={s.label} className="bg-bg rounded-xl border border-border p-3">
            <p className="text-[11px] text-text-dim uppercase tracking-wider mb-0.5">{s.label}</p>
            <p className="text-[15px] font-semibold font-mono">{s.val}</p>
          </div>
        ))}
      </div>

      <div className="h-48">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={SEO_PERF_30D} margin={{ top: 4, right: 4, left: -20, bottom: 0 }}>
            <defs>
              <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#6366f1" stopOpacity={0.35} />
                <stop offset="100%" stopColor="#6366f1" stopOpacity={0.0} />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="rgba(99,102,241,0.07)" vertical={false} />
            <XAxis
              dataKey="date"
              tick={{ fontSize: 10, fill: '#44445a' }}
              axisLine={false}
              tickLine={false}
              interval={4}
            />
            <YAxis
              tick={{ fontSize: 10, fill: '#44445a' }}
              axisLine={false}
              tickLine={false}
              reversed={isPosition}
              tickFormatter={(v: number) => (isPosition ? `#${v}` : formatNumber(v))}
            />
            <Tooltip
              content={(props) => (
                <CustomTooltip
                  active={props.active}
                  payload={props.payload as TooltipPayload[] | undefined}
                  label={props.label as string | undefined}
                  metric={metric}
                />
              )}
            />
            <Area
              type="monotone"
              dataKey={metric}
              stroke="#6366f1"
              strokeWidth={2}
              fill={`url(#${gradientId})`}
              dot={false}
              activeDot={{ r: 4, fill: '#818cf8', stroke: '#6366f1', strokeWidth: 2 }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </motion.div>
  );
}
