import { useState } from 'react';
import { XAxis, YAxis, Tooltip, ResponsiveContainer, Area, AreaChart, ReferenceLine } from 'recharts';

interface Props {
  data: { date: string; price: number }[];
  rrp?: number;
}

export default function PriceHistoryChart({ data, rrp }: Props) {
  const [range, setRange] = useState<30 | 90 | 365>(30);

  const filtered = data.slice(-range);
  const prices = filtered.map(d => d.price);
  const uniquePrices = new Set(prices);
  const isFlat = uniquePrices.size <= 1;
  if (rrp && rrp > 0) prices.push(rrp);
  const min = Math.floor(Math.min(...prices) - 5);
  const max = Math.ceil(Math.max(...prices) + 5);

  const ranges = [
    { value: 30 as const, label: '30D' },
    { value: 90 as const, label: '90D' },
    { value: 365 as const, label: '1J' },
  ];

  if (filtered.length === 0) {
    return (
      <div>
        <h3 className="mb-4 text-sm font-bold uppercase tracking-widest text-text-muted">Prijsverloop</h3>
        <div className="flex h-[200px] items-center justify-center rounded-xl bg-bg-elevated/50">
          <p className="text-sm text-text-muted">Nog geen prijsgeschiedenis beschikbaar — wordt dagelijks bijgewerkt</p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <h3 className="text-sm font-bold uppercase tracking-widest text-text-muted">Prijsverloop</h3>
        <div className="flex gap-1 rounded-xl bg-bg-elevated p-1">
          {ranges.map(r => (
            <button
              key={r.value}
              onClick={() => setRange(r.value)}
              className={`rounded-lg px-3 py-1.5 text-xs font-bold transition-all ${
                range === r.value
                  ? 'bg-accent text-bg shadow-sm'
                  : 'text-text-muted hover:text-text'
              }`}
            >
              {r.label}
            </button>
          ))}
        </div>
      </div>

      {isFlat && (
        <p className="mb-3 text-xs text-text-muted">
          Stabiele prijs — geen verandering in de afgelopen {range === 365 ? 'jaar' : `${range} dagen`}
        </p>
      )}

      <div className="h-[250px] w-full">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={filtered} margin={{ top: 5, right: 5, bottom: 5, left: 5 }}>
            <defs>
              <linearGradient id="priceGrad" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#D69F7E" stopOpacity={0.2} />
                <stop offset="100%" stopColor="#D69F7E" stopOpacity={0} />
              </linearGradient>
            </defs>
            <XAxis
              dataKey="date"
              tick={{ fill: '#774936', fontSize: 11 }}
              tickFormatter={(v: string) => {
                const d = new Date(v);
                return `${d.getDate()}/${d.getMonth() + 1}`;
              }}
              axisLine={false}
              tickLine={false}
              interval="preserveStartEnd"
            />
            <YAxis
              domain={[min, max]}
              tick={{ fill: '#774936', fontSize: 11 }}
              tickFormatter={(v: number) => `€${v}`}
              axisLine={false}
              tickLine={false}
              width={50}
            />
            <Tooltip
              contentStyle={{
                background: '#0D0D12',
                border: '1px solid #774936',
                borderRadius: '12px',
                padding: '8px 12px',
                fontSize: '13px',
              }}
              labelFormatter={(v: string) => {
                const d = new Date(v);
                return d.toLocaleDateString('nl-NL', { day: 'numeric', month: 'long', year: 'numeric' });
              }}
              formatter={(value: number) => [`€${value.toFixed(2).replace('.', ',')}`, 'Prijs']}
            />
            {rrp && rrp > 0 && (
              <ReferenceLine
                y={rrp}
                stroke="#774936"
                strokeDasharray="5 5"
                label={{ value: 'Adviesprijs', position: 'right', fill: '#774936', fontSize: 11 }}
              />
            )}
            <Area
              type="monotone"
              dataKey="price"
              stroke="#D69F7E"
              strokeWidth={2}
              fill="url(#priceGrad)"
              dot={false}
              activeDot={{ r: 4, fill: '#D69F7E', stroke: '#050609', strokeWidth: 2 }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
