import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts';

interface DataItem {
  name: string;
  valor: number;
}

interface Props {
  data: DataItem[];
  horizontal?: boolean;
}

export default function BarChartComponent({ data, horizontal = false }: Props) {
  const getColor = (value: number) => {
    return value >= 0 ? '#10b981' : '#ef4444';
  };

  const formatValue = (value: number) => {
    if (Math.abs(value) >= 1000000) {
      return `${(value / 1000000).toFixed(1)}M`;
    }
    if (Math.abs(value) >= 1000) {
      return `${(value / 1000).toFixed(1)}K`;
    }
    return value.toFixed(0);
  };

  if (horizontal) {
    return (
      <ResponsiveContainer width="100%" height={200}>
        <BarChart data={data} layout="vertical">
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis type="number" tickFormatter={formatValue} />
          <YAxis dataKey="name" type="category" width={120} />
          <Tooltip formatter={(value: number) => formatValue(value)} />
          <Bar dataKey="valor" radius={[0, 4, 4, 0]}>
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={getColor(entry.valor)} />
            ))}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    );
  }

  return (
    <ResponsiveContainer width="100%" height={300}>
      <BarChart data={data}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis tickFormatter={formatValue} />
        <Tooltip formatter={(value: number) => formatValue(value)} />
        <Bar dataKey="valor" radius={[4, 4, 0, 0]}>
          {data.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={getColor(entry.valor)} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}
