import React, { useState } from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  BarController,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Bar } 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,
  Title,
  Tooltip,
  Legend
);

const PaymentVariancesChart = ({ data, loading, onTransactionClick }) => {
  const { t, i18n } = useTranslation();
  const { currency } = useFormatters();
  const [showTable, setShowTable] = useState(false);
  
  // Helper para locale dinâmico
  const getLocale = () => i18n.language === 'pt-BR' ? 'pt-BR' : i18n.language === 'es' ? 'es-ES' : 'en-US';

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

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

  const chartData = {
    labels: data.by_month.map(d => {
      const [year, month] = d.month.split('-');
      const date = new Date(year, month - 1);
      return date.toLocaleDateString(getLocale(), { month: 'short', year: '2-digit' });
    }),
    datasets: [
      {
        label: t('dashboard.overpayment'),
        data: data.by_month.map(d => d.overpayment),
        backgroundColor: 'rgba(239, 68, 68, 0.8)',
        borderColor: 'rgb(239, 68, 68)',
        borderWidth: 1,
        borderRadius: 4,
      },
      {
        label: t('dashboard.underpayment'),
        data: data.by_month.map(d => -d.underpayment),
        backgroundColor: 'rgba(34, 197, 94, 0.8)',
        borderColor: 'rgb(34, 197, 94)',
        borderWidth: 1,
        borderRadius: 4,
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'top',
        labels: {
          color: '#94a3b8',
          usePointStyle: true,
          pointStyle: 'circle',
          padding: 15,
          font: { size: 11 },
        },
      },
      tooltip: {
        backgroundColor: 'rgba(30, 41, 59, 0.95)',
        titleColor: '#f1f5f9',
        bodyColor: '#cbd5e1',
        borderColor: '#475569',
        borderWidth: 1,
        padding: 12,
        cornerRadius: 8,
        callbacks: {
          label: (context) => {
            const value = Math.abs(context.parsed.y);
            const label = context.dataset.label || '';
            return `${label}: ${currency(value, 'BRL')}`;
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
          drawBorder: false,
        },
        ticks: {
          color: '#94a3b8',
          font: { size: 11 },
        },
      },
      y: {
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
          drawBorder: false,
        },
        ticks: {
          color: '#94a3b8',
          font: { size: 11 },
          callback: (value) => {
            const absValue = Math.abs(value);
            if (absValue >= 1000) {
              return (value / 1000).toFixed(1) + 'k';
            }
            return value;
          },
        },
      },
    },
  };

  // Top transações com variação
  const topVariances = data.transactions?.slice(0, 10) || [];

  return (
    <div>
      {/* Resumo */}
      <div className="row mb-3">
        <div className="col-4 text-center">
          <small className="text-slate-400 d-block">{t('dashboard.overpayment')}</small>
          <span className="text-danger fw-bold">
            +{currency(data.summary?.total_overpayment || 0, 'BRL')}
          </span>
          <small className="text-slate-500 d-block">
            {data.summary?.overpayment_count || 0} {t('dashboard.items')}
          </small>
        </div>
        <div className="col-4 text-center">
          <small className="text-slate-400 d-block">{t('dashboard.underpayment')}</small>
          <span className="text-success fw-bold">
            -{currency(data.summary?.total_underpayment || 0, 'BRL')}
          </span>
          <small className="text-slate-500 d-block">
            {data.summary?.underpayment_count || 0} {t('dashboard.items')}
          </small>
        </div>
        <div className="col-4 text-center">
          <small className="text-slate-400 d-block">{t('dashboard.netVariance')}</small>
          <span className={`fw-bold ${data.summary?.net_variance >= 0 ? 'text-danger' : 'text-success'}`}>
            {data.summary?.net_variance >= 0 ? '+' : ''}{currency(data.summary?.net_variance || 0, 'BRL')}
          </span>
        </div>
      </div>

      {/* Gráfico */}
      <div style={{ height: '200px' }}>
        <Bar data={chartData} options={options} />
      </div>

      {/* Toggle para tabela */}
      <div className="mt-3 text-center">
        <button 
          className="btn btn-link btn-sm text-slate-400"
          onClick={() => setShowTable(!showTable)}
        >
          {showTable ? (
            <><i className="bi bi-chevron-up me-1"></i>{t('dashboard.hideDetails')}</>
          ) : (
            <><i className="bi bi-chevron-down me-1"></i>{t('dashboard.showDetails')} ({topVariances.length})</>
          )}
        </button>
      </div>

      {/* Tabela de transações */}
      {showTable && topVariances.length > 0 && (
        <div className="mt-3 table-responsive" style={{ maxHeight: '300px', overflowY: 'auto' }}>
          <table className="table table-sm table-borderless mb-0" style={{ '--bs-table-bg': 'transparent' }}>
            <thead className="sticky-top" style={{ background: '#1e293b' }}>
              <tr>
                <th className="text-slate-400 small">{t('common.description')}</th>
                <th className="text-slate-400 small text-end">{t('dashboard.planned')}</th>
                <th className="text-slate-400 small text-end">{t('dashboard.actual')}</th>
                <th className="text-slate-400 small text-end">{t('dashboard.variance')}</th>
              </tr>
            </thead>
            <tbody>
              {topVariances.map((t) => (
                <tr 
                  key={t.id} 
                  className="cursor-pointer hover-bg-slate-700"
                  onClick={() => onTransactionClick?.(t.id)}
                  style={{ cursor: 'pointer' }}
                >
                  <td>
                    <span className="text-white small" title={t.description}>
                      {t.description.length > 35 ? t.description.substring(0, 35) + '...' : t.description}
                    </span>
                    <br />
                    <small className="text-slate-500">{t.effective_date}</small>
                  </td>
                  <td className="text-end text-slate-300 small">
                    {currency(t.planned_amount, 'BRL')}
                  </td>
                  <td className="text-end text-white small">
                    {currency(t.actual_amount, 'BRL')}
                  </td>
                  <td className="text-end small">
                    <span className={t.variance > 0 ? 'text-danger' : 'text-success'}>
                      {t.variance > 0 ? '+' : ''}{currency(t.variance, 'BRL')}
                    </span>
                    <br />
                    <small className={`${t.variance > 0 ? 'text-danger' : 'text-success'} opacity-75`}>
                      ({t.variance_percent > 0 ? '+' : ''}{t.variance_percent}%)
                    </small>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default PaymentVariancesChart;
