'use client';

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

interface RatingTrendProps {
  data: RatingTrendPoint[];
  projection?: RatingTrendPoint[];
}

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

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

  if (projection) {
    for (const p of projection) {
      chartData.push({
        period: p.period,
        rating: undefined as unknown as number,
        reviews: p.review_count,
        projected: p.avg_rating,
      } as typeof chartData[number] & { projected?: number });
    }
  }

  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="period"
          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="rating"
          stroke="#3b82f6"
          strokeWidth={2.5}
          dot={{ fill: '#3b82f6', r: 4, strokeWidth: 2, stroke: '#fff' }}
          name="Avg Rating"
          connectNulls={false}
        />
        {projection && (
          <Line
            type="monotone"
            dataKey="projected"
            stroke="#3b82f6"
            strokeWidth={2}
            strokeDasharray="6 4"
            dot={false}
            name="Projected"
          />
        )}
        <Tooltip
          contentStyle={{ borderRadius: '8px', border: '1px solid #e5e7eb' }}
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          formatter={(value: any, name: any) => {
            if (value === undefined || value === null) return ['-', name];
            return [`${Number(value).toFixed(2)} / 5`, name === 'Projected' ? 'Projected' : 'Rating'];
          }}
        />
      </LineChart>
    </ResponsiveContainer>
  );
}
