'use client';

import {
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ReferenceLine,
} from 'recharts';
import type { QuarterlyRatingPoint } from '../types';

interface QuarterlyRatingChartProps {
  data: QuarterlyRatingPoint[];
}

export default function QuarterlyRatingChart({ data }: QuarterlyRatingChartProps) {
  if (data.length === 0) {
    return (
      <div className="flex items-center justify-center h-64 text-gray-400">
        No quarterly data
      </div>
    );
  }

  const chartData = data.map(p => ({
    quarter: p.quarter,
    avg_rating: p.avg_rating,
    review_count: p.review_count,
  }));

  return (
    <ResponsiveContainer width="100%" height={280}>
      <LineChart data={chartData} margin={{ top: 10, right: 20, left: 0, bottom: 5 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />
        <XAxis
          dataKey="quarter"
          tick={{ fill: '#6b7280', fontSize: 11 }}
          tickLine={false}
          axisLine={{ stroke: '#e5e7eb' }}
        />
        <YAxis
          domain={[1, 5]}
          ticks={[1, 2, 3, 4, 5]}
          tick={{ fill: '#6b7280', fontSize: 11 }}
          tickLine={false}
          axisLine={false}
        />
        <ReferenceLine y={4} stroke="#22c55e" strokeDasharray="5 5" strokeOpacity={0.5} />
        <Line
          type="monotone"
          dataKey="avg_rating"
          stroke="#3b82f6"
          strokeWidth={2.5}
          dot={(props: any) => {
            const { cx, cy, payload } = props;
            const r = Math.max(3, Math.min(8, Math.sqrt(payload.review_count) * 1.5));
            return <circle key={`dot-${props.index}`} cx={cx} cy={cy} r={r} fill="#3b82f6" stroke="#fff" strokeWidth={2} />;
          }}
          name="Avg Rating"
        />
        <Tooltip
          contentStyle={{ borderRadius: '8px', border: '1px solid #e5e7eb' }}
          formatter={(value: any) => [`${Number(value).toFixed(2)} / 5`, 'Rating']}
          labelFormatter={(label: string) => label}
        />
      </LineChart>
    </ResponsiveContainer>
  );
}
