import React, { useState, useEffect, useCallback } from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  LineElement,
  PointElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import { useTranslation } from 'react-i18next';
import useFormatters from '../../hooks/useFormatters';
import { reportService } from '../../services/api';

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

const BalanceProjectionChart = () => {
  const { t } = useTranslation();
  const { currency } = useFormatters();
  
  const [months, setMonths] = useState(3);
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
  const [isExpanded, setIsExpanded] = useState(false);

  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await reportService.getProjectionChart({ months });
      setData(response);
      
      // Auto-expand if we have data points in mobile
      if (isMobile && response?.data?.length > 0) {
        setIsExpanded(true);
      }
    } catch (err) {
      console.error('Error loading projection chart:', err);
      setError(t('common.error'));
    } finally {
      setLoading(false);
    }
  }, [months, t, isMobile]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  useEffect(() => {
    const handleResize = () => {
      const mobile = window.innerWidth < 768;
      setIsMobile(mobile);
      if (!mobile) {
        setIsExpanded(false);
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const periodOptions = [
    { value: 1, label: t('reports.projectionChart.1month') || '1 mês' },
    { value: 2, label: t('reports.projectionChart.2months') || '2 meses' },
    { value: 3, label: t('reports.projectionChart.3months') || '3 meses' },
    { value: 6, label: t('reports.projectionChart.6months') || '6 meses' },
    { value: 12, label: t('reports.projectionChart.12months') || '12 meses' },
  ];

  const chartData = {
    labels: data?.data?.map(d => d.label) || [],
    datasets: [
      {
        label: t('reports.projectionChart.projectedBalance') || 'Saldo Projetado',
        data: data?.data?.map(d => d.balance) || [],
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: (context) => {
          const chart = context.chart;
          const { ctx, chartArea } = chart;
          if (!chartArea) return 'rgba(59, 130, 246, 0.2)';
          
          const gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
          gradient.addColorStop(0, 'rgba(59, 130, 246, 0.0)');
          gradient.addColorStop(1, 'rgba(59, 130, 246, 0.3)');
          return gradient;
        },
        borderWidth: 2,
        fill: true,
        tension: 0.3,
        pointRadius: (context) => {
          // Mostrar ponto maior no dia atual
          const point = data?.data?.[context.dataIndex];
          return point?.isToday ? 6 : 2;
        },
        pointHoverRadius: 6,
        pointBackgroundColor: (context) => {
          const point = data?.data?.[context.dataIndex];
          if (point?.isToday) return 'rgb(234, 179, 8)';
          return point?.balance < 0 ? 'rgb(239, 68, 68)' : 'rgb(59, 130, 246)';
        },
        pointBorderColor: (context) => {
          const point = data?.data?.[context.dataIndex];
          if (point?.isToday) return 'rgb(234, 179, 8)';
          return point?.balance < 0 ? 'rgb(239, 68, 68)' : 'rgb(59, 130, 246)';
        },
        segment: {
          borderColor: ctx => {
            const value = ctx.p1.parsed.y;
            return value < 0 ? 'rgba(239, 68, 68, 0.8)' : 'rgb(59, 130, 246)';
          },
        },
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: {
      mode: 'index',
      intersect: false,
    },
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        backgroundColor: 'rgba(15, 23, 42, 0.9)',
        titleColor: '#f1f5f9',
        bodyColor: '#f1f5f9',
        borderColor: 'rgba(148, 163, 184, 0.2)',
        borderWidth: 1,
        padding: 12,
        callbacks: {
          title: (items) => {
            const point = data?.data?.[items[0].dataIndex];
            return point?.date || items[0].label;
          },
          label: (context) => {
            const point = data?.data?.[context.dataIndex];
            let label = ` ${t('reports.projectionChart.balance') || 'Saldo'}: ${currency(context.parsed.y, data?.currency || 'EUR')}`;
            if (point?.isToday) {
              label += ` (${t('common.today') || 'Hoje'})`;
            }
            return label;
          },
        },
      },
    },
    scales: {
      x: {
        ticks: {
          color: '#94a3b8',
          maxRotation: 45,
          minRotation: 45,
        },
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
        },
      },
      y: {
        ticks: {
          color: '#94a3b8',
          callback: (value) => currency(value, data?.currency || 'EUR'),
        },
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
        },
      },
    },
  };

  if (loading) {
    return (
      <div className="card border-0 shadow-sm bg-slate-800">
        <div className="card-body">
          <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>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="card border-0 shadow-sm bg-slate-800">
        <div className="card-body">
          <div className="d-flex justify-content-center align-items-center text-danger" style={{ height: '350px' }}>
            <div className="text-center">
              <i className="bi bi-exclamation-triangle fs-1 mb-2"></i>
              <p>{error}</p>
              <button className="btn btn-sm btn-outline-primary" onClick={loadData}>
                {t('common.retry') || 'Tentar novamente'}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const summary = data?.summary;
  const changeClass = summary?.change >= 0 ? 'text-success' : 'text-danger';
  const changeIcon = summary?.change >= 0 ? 'bi-arrow-up' : 'bi-arrow-down';

  return (
    <div className="card border-0 shadow-sm bg-slate-800" style={{ height: isMobile ? 'auto' : undefined }}>
      <div className="card-header bg-transparent border-bottom border-slate-700">
        <div className="d-flex justify-content-between align-items-center mb-2">
          <div className="flex-grow-1">
            <h5 className="card-title text-light mb-1">
              <i className="bi bi-graph-up-arrow me-2 text-primary"></i>
              {t('reports.projectionChart.title') || 'Projeção de Saldo'}
            </h5>
            <small className="text-slate-400">
              {t('reports.projectionChart.subtitle') || 'Evolução prevista do seu saldo'}
            </small>
          </div>
          {isMobile && (
            <button
              className="btn btn-sm btn-outline-light ms-2"
              onClick={() => setIsExpanded(!isExpanded)}
              aria-label={isExpanded ? "Colapsar" : "Expandir"}
            >
              <i className={`bi bi-chevron-${isExpanded ? 'up' : 'down'}`}></i>
            </button>
          )}
        </div>
        {(!isMobile || isExpanded) && (
          <div className={isMobile ? "d-flex flex-wrap gap-2" : "d-flex justify-content-end"}>
            {periodOptions.map(opt => (
              <button
                key={opt.value}
                className={`btn btn-sm ${months === opt.value ? 'btn-primary' : 'btn-outline-secondary'} ${isMobile ? 'flex-fill' : ''}`}
                onClick={() => setMonths(opt.value)}
                style={isMobile ? { minWidth: 'calc(33.333% - 0.5rem)' } : undefined}
              >
                {opt.label}
              </button>
            ))}
          </div>
        )}
      </div>
      <div className="card-body" style={{ display: isMobile && !isExpanded ? 'none' : 'block', padding: isMobile ? '1rem' : undefined }}>
        {/* Summary Stats */}
        {summary && (
          <>
            {/* Alert if overdue transactions included */}
            {summary.overdue_count > 0 && (
              <div className={`alert alert-warning d-flex align-items-center ${isMobile ? 'mb-2 p-2' : 'mb-3'}`} role="alert" style={isMobile ? { fontSize: '0.75rem' } : undefined}>
                <i className={`bi bi-exclamation-circle-fill ${isMobile ? 'me-1' : 'me-2'}`} style={isMobile ? { fontSize: '0.9rem' } : undefined}></i>
                <div>
                  <strong>{t('reports.projectionChart.overdueIncluded') || 'Atenção'}:</strong>{' '}
                  {summary.overdue_count} {t('reports.projectionChart.overdueTransactions') || 'transação(ões) em atraso'}{' '}
                  {!isMobile && (t('reports.projectionChart.includedInProjection') || 'já incluída(s) no saldo atual.')}{' '}
                  <span className={summary.overdue_impact < 0 ? 'text-danger fw-bold' : 'text-success fw-bold'}>
                    ({summary.overdue_impact >= 0 ? '+' : ''}{currency(summary.overdue_impact, data?.currency)})
                  </span>
                </div>
              </div>
            )}
            
            <div className="row g-2 mb-3">
            <div className="col-6 col-md-3">
              <div className={`${isMobile ? 'p-2' : 'p-3'} rounded bg-slate-700`}>
                <small className={`text-slate-400 d-block ${isMobile ? 'mb-0' : ''}`} style={isMobile ? { fontSize: '0.7rem' } : undefined}>
                  {t('reports.projectionChart.currentBalance') || 'Saldo Atual'}
                </small>
                <span className={`${isMobile ? 'fs-6' : 'fs-5'} fw-bold text-light d-block`} style={isMobile ? { fontSize: '0.9rem' } : undefined}>
                  {currency(summary.current_balance, data?.currency)}
                </span>
              </div>
            </div>
            <div className="col-6 col-md-3">
              <div className={`${isMobile ? 'p-2' : 'p-3'} rounded bg-slate-700`}>
                <small className={`text-slate-400 d-block ${isMobile ? 'mb-0' : ''}`} style={isMobile ? { fontSize: '0.7rem' } : undefined}>
                  {t('reports.projectionChart.finalBalance') || 'Saldo Final'}
                </small>
                <span className={`${isMobile ? 'fs-6' : 'fs-5'} fw-bold ${summary.final_balance >= 0 ? 'text-success' : 'text-danger'} d-block`} style={isMobile ? { fontSize: '0.9rem' } : undefined}>
                  {currency(summary.final_balance, data?.currency)}
                </span>
              </div>
            </div>
            <div className="col-6 col-md-3">
              <div className={`${isMobile ? 'p-2' : 'p-3'} rounded bg-slate-700`}>
                <small className={`text-slate-400 d-block ${isMobile ? 'mb-0' : ''}`} style={isMobile ? { fontSize: '0.7rem' } : undefined}>
                  {t('reports.projectionChart.minBalance') || 'Saldo Mínimo'}
                </small>
                <span className={`${isMobile ? 'fs-6' : 'fs-5'} fw-bold ${summary.min_balance >= 0 ? 'text-warning' : 'text-danger'} d-block`} style={isMobile ? { fontSize: '0.9rem' } : undefined}>
                  {currency(summary.min_balance, data?.currency)}
                </span>
              </div>
            </div>
            <div className="col-6 col-md-3">
              <div className={`${isMobile ? 'p-2' : 'p-3'} rounded bg-slate-700`}>
                <small className={`text-slate-400 d-block ${isMobile ? 'mb-0' : ''}`} style={isMobile ? { fontSize: '0.7rem' } : undefined}>
                  {t('reports.projectionChart.change') || 'Variação'}
                </small>
                <span className={`${isMobile ? 'fs-6' : 'fs-5'} fw-bold ${changeClass} d-block`} style={isMobile ? { fontSize: '0.9rem' } : undefined}>
                  <i className={`bi ${changeIcon} me-1`}></i>
                  {currency(Math.abs(summary.change), data?.currency)}
                  {!isMobile && <small className="ms-1">({summary.change_percent}%)</small>}
                </span>
              </div>
            </div>
          </div>
          </>
        )}

        {/* Alert if negative balance predicted */}
        {summary?.negative_month && (
          <div className={`alert alert-danger d-flex align-items-center ${isMobile ? 'mb-3 p-2' : 'mb-4'}`} role="alert" style={isMobile ? { fontSize: '0.75rem' } : undefined}>
            <i className={`bi bi-exclamation-triangle-fill ${isMobile ? 'me-1 fs-6' : 'me-2 fs-5'}`}></i>
            <div>
              <strong>{t('reports.projectionChart.warning') || 'Atenção!'}</strong>{' '}
              {isMobile ? 'Saldo negativo em' : (t('reports.projectionChart.negativeAlert') || 'Previsão de saldo negativo em')}{' '}
              <strong>{summary.negative_month}</strong>
            </div>
          </div>
        )}

        {/* Chart */}
        <div style={{ height: isMobile ? '250px' : '350px' }}>
          <Line data={chartData} options={options} />
        </div>

        {/* Period Info */}
        {data?.period && (
          <div className="text-center mt-3">
            <small className="text-slate-400">
              {t('reports.projectionChart.period') || 'Período'}:{' '}
              <span className="text-light">{data.period.start}</span>
              {' → '}
              <span className="text-light">{data.period.end}</span>
              {' | '}
              {data.period.total_points} {t('reports.projectionChart.dataPoints') || 'pontos de dados'}
            </small>
          </div>
        )}
      </div>
    </div>
  );
};

export default BalanceProjectionChart;
