import React from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import type { TopicFrequency } from '../../utils/analysis.utils.ts';

type TopicFrequencyChartProps = {
  data: TopicFrequency[];
};

const TopicFrequencyChart = ({ data }: TopicFrequencyChartProps) => {
  // Truncate long topic names for display
  const chartData = data.map((item) => ({
    ...item,
    topicDisplay: item.topic.length > 40 ? `${item.topic.substring(0, 40)}...` : item.topic,
  }));

  return (
    <div className="h-96 w-full">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart
          layout="vertical"
          data={chartData}
          margin={{ top: 5, right: 30, left: 150, bottom: 5 }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis type="number" />
          <YAxis
            type="category"
            dataKey="topicDisplay"
            width={140}
            style={{ fontSize: '12px' }}
          />
          <Tooltip
            formatter={(value: number, name: string) => [value, name === 'proCount' ? 'PRO' : name === 'conCount' ? 'CON' : 'Total']}
            contentStyle={{ fontSize: '12px' }}
          />
          <Legend
            formatter={(value) => (value === 'proCount' ? 'PRO' : value === 'conCount' ? 'CON' : 'Total')}
          />
          <Bar dataKey="proCount" fill="#10b981" name="proCount" />
          <Bar dataKey="conCount" fill="#ef4444" name="conCount" />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
};

export default TopicFrequencyChart;

