import React, { useEffect, useRef } from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  BarController,
  LineElement,
  LineController,
  PointElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js';
import { Chart } from 'react-chartjs-2';
import { useTranslation } from 'react-i18next';
import useFormatters from '../../hooks/useFormatters';

// Registrar componentes do Chart.js
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  BarController,
  LineElement,
  LineController,
  PointElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

const CashflowChart = ({ data, loading, scale = 'monthly', primaryCurrency = 'EUR' }) => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  const chartRef = useRef(null);

  if (loading) {
    return (
      <div className="d-flex justify-content-center align-items-center" style={{ height: '350px' }}>
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="d-flex justify-content-center align-items-center text-slate-400" style={{ height: '350px' }}>
        <div className="text-center">
          <i className="bi bi-bar-chart fs-1 mb-2"></i>
          <p>{t('dashboard.noDataAvailable')}</p>
        </div>
      </div>
    );
  }

  const labels = data.map(d => d.month_label);
  
  const chartData = {
    labels,
    datasets: [
      {
        type: 'bar',
        label: t('dashboard.income'),
        data: data.map(d => d.income),
        backgroundColor: 'rgba(34, 197, 94, 0.8)',
        borderColor: 'rgb(34, 197, 94)',
        borderWidth: 1,
        borderRadius: 4,
        order: 2,
      },
      {
        type: 'bar',
        label: t('dashboard.expenses'),
        data: data.map(d => d.expense),
        backgroundColor: 'rgba(239, 68, 68, 0.8)',
        borderColor: 'rgb(239, 68, 68)',
        borderWidth: 1,
        borderRadius: 4,
        order: 2,
      },
      {
        type: 'line',
        label: t('dashboard.cumulativeBalance'),
        data: data.map(d => d.cumulative_balance),
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        borderWidth: 2,
        fill: true,
        tension: 0.3,
        pointRadius: 4,
        pointHoverRadius: 6,
        pointBackgroundColor: 'rgb(59, 130, 246)',
        yAxisID: 'y1',
        order: 1,
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: {
      mode: 'index',
      intersect: false,
    },
    plugins: {
      legend: {
        position: 'top',
        labels: {
          color: '#94a3b8',
          usePointStyle: true,
          pointStyle: 'circle',
          padding: 20,
          font: {
            size: 12,
          },
        },
      },
      tooltip: {
        backgroundColor: 'rgba(30, 41, 59, 0.95)',
        titleColor: '#f1f5f9',
        bodyColor: '#cbd5e1',
        borderColor: '#475569',
        borderWidth: 1,
        padding: 12,
        cornerRadius: 8,
        displayColors: true,
        callbacks: {
          label: (context) => {
            const value = context.parsed.y;
            const label = context.dataset.label || '';
            return `${label}: ${currency(value, primaryCurrency)}`;
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
          drawBorder: false,
        },
        ticks: {
          color: '#94a3b8',
          font: {
            size: 11,
          },
        },
      },
      y: {
        type: 'linear',
        display: true,
        position: 'left',
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
          drawBorder: false,
        },
        ticks: {
          color: '#94a3b8',
          font: {
            size: 11,
          },
          callback: (value) => {
            if (Math.abs(value) >= 1000000) {
              return (value / 1000000).toFixed(1) + 'M';
            } else if (Math.abs(value) >= 1000) {
              return (value / 1000).toFixed(0) + 'k';
            }
            return value;
          },
        },
        title: {
          display: true,
          text: t('dashboard.monthlyValues'),
          color: '#94a3b8',
        },
      },
      y1: {
        type: 'linear',
        display: true,
        position: 'right',
        grid: {
          drawOnChartArea: false,
        },
        ticks: {
          color: 'rgb(59, 130, 246)',
          font: {
            size: 11,
          },
          callback: (value) => {
            if (Math.abs(value) >= 1000000) {
              return (value / 1000000).toFixed(1) + 'M';
            } else if (Math.abs(value) >= 1000) {
              return (value / 1000).toFixed(0) + 'k';
            }
            return value;
          },
        },
        title: {
          display: true,
          text: t('dashboard.cumulativeBalance'),
          color: 'rgb(59, 130, 246)',
        },
      },
    },
  };

  return (
    <div style={{ height: '350px' }}>
      <Chart ref={chartRef} type="bar" data={chartData} options={options} />
    </div>
  );
};

export default CashflowChart;
