'use client';

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

const DOMAIN_CONFIG: Record<string, { color: string; name: string }> = {
  O: { color: '#3b82f6', name: 'Output' },
  P: { color: '#22c55e', name: 'People' },
  J: { color: '#f59e0b', name: 'Journey' },
  E: { color: '#8b5cf6', name: 'Environment' },
  V: { color: '#f43f5e', name: 'Value' },
};

interface DomainSentimentTrendProps {
  data: QuarterlyDomainSentimentPoint[];
}

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

  // Detect which domains have data
  const activeDomains = (Object.keys(DOMAIN_CONFIG) as Array<keyof typeof DOMAIN_CONFIG>).filter(
    d => data.some(p => (p as any)[d] !== undefined && (p as any)[d] !== null)
  );

  return (
    <ResponsiveContainer width="100%" height={280}>
      <LineChart data={data} 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={[0, 100]}
          tick={{ fill: '#6b7280', fontSize: 11 }}
          tickLine={false}
          axisLine={false}
          label={{ value: 'Positive %', angle: -90, position: 'insideLeft', style: { fill: '#6b7280', fontSize: 11 } }}
        />
        {activeDomains.map(d => (
          <Line
            key={d}
            type="monotone"
            dataKey={d}
            stroke={DOMAIN_CONFIG[d]?.color}
            strokeWidth={2}
            dot={{ fill: DOMAIN_CONFIG[d]?.color, r: 3, strokeWidth: 1, stroke: '#fff' }}
            name={DOMAIN_CONFIG[d]?.name}
            connectNulls
          />
        ))}
        <Tooltip
          contentStyle={{ borderRadius: '8px', border: '1px solid #e5e7eb' }}
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          formatter={(value: any, name: any) => [`${Number(value).toFixed(1)}%`, name ?? '']}
        />
        <Legend
          verticalAlign="bottom"
          iconType="line"
          wrapperStyle={{ fontSize: 11, paddingTop: 8 }}
        />
      </LineChart>
    </ResponsiveContainer>
  );
}
