import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { dashboardService, recurringService } from '../../services/api';
import useFormatters from '../../hooks/useFormatters';

const CalendarWidget = () => {
  const { t, i18n } = useTranslation();
  const { currency, date: formatDate } = useFormatters();
  
  // Refs para sincronizar altura
  const calendarRef = useRef(null);
  const transactionsRef = useRef(null);
  
  // Estado do calendário
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState(null);
  const [calendarData, setCalendarData] = useState(null);
  const [dayData, setDayData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [dayLoading, setDayLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(null);
  const [calendarHeight, setCalendarHeight] = useState(null);

  // Estado do modal de conciliação
  const [showReconcileModal, setShowReconcileModal] = useState(false);
  const [reconcileData, setReconcileData] = useState({
    instance: null,
    candidates: [],
    loading: false,
  });

  // Sincronizar altura do widget de transações com o calendário
  useEffect(() => {
    const updateHeight = () => {
      if (calendarRef.current) {
        const height = calendarRef.current.offsetHeight;
        setCalendarHeight(height);
      }
    };
    
    updateHeight();
    window.addEventListener('resize', updateHeight);
    
    // Observer para mudanças no conteúdo do calendário
    const observer = new ResizeObserver(updateHeight);
    if (calendarRef.current) {
      observer.observe(calendarRef.current);
    }
    
    return () => {
      window.removeEventListener('resize', updateHeight);
      observer.disconnect();
    };
  }, [loading, calendarData]);

  // Carregar dados do calendário
  const loadCalendar = useCallback(async () => {
    setLoading(true);
    try {
      const data = await dashboardService.getCalendar(
        currentDate.getFullYear(),
        currentDate.getMonth() + 1
      );
      setCalendarData(data);
    } catch (error) {
      console.error('Error loading calendar:', error);
    } finally {
      setLoading(false);
    }
  }, [currentDate]);

  // Carregar dados de um dia específico
  const loadDay = useCallback(async (date) => {
    setDayLoading(true);
    try {
      const data = await dashboardService.getCalendarDay(date);
      setDayData(data);
    } catch (error) {
      console.error('Error loading day:', error);
    } finally {
      setDayLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (selectedDate) {
      loadDay(selectedDate);
    } else {
      setDayData(null);
    }
  }, [selectedDate, loadDay]);

  // Navegação do calendário
  const prevMonth = () => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1));
    setSelectedDate(null);
  };

  const nextMonth = () => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1));
    setSelectedDate(null);
  };

  const goToToday = () => {
    const today = new Date();
    setCurrentDate(new Date(today.getFullYear(), today.getMonth(), 1));
    setSelectedDate(today.toISOString().split('T')[0]);
  };

  // Obter dados de uma data específica
  const getDateData = (dateStr) => {
    if (!calendarData?.by_date) return null;
    return calendarData.by_date.find(d => d.date === dateStr);
  };

  // Gerar dias do calendário
  const generateCalendarDays = () => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    
    const days = [];
    const startPadding = firstDay.getDay(); // 0 = domingo
    
    // Dias do mês anterior (padding)
    const prevMonth = new Date(year, month, 0);
    for (let i = startPadding - 1; i >= 0; i--) {
      days.push({
        day: prevMonth.getDate() - i,
        isCurrentMonth: false,
        date: null,
      });
    }
    
    // Dias do mês atual
    for (let i = 1; i <= lastDay.getDate(); i++) {
      const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
      days.push({
        day: i,
        isCurrentMonth: true,
        date: dateStr,
        data: getDateData(dateStr),
      });
    }
    
    // Dias do próximo mês (padding para completar 6 linhas)
    const endPadding = 42 - days.length;
    for (let i = 1; i <= endPadding; i++) {
      days.push({
        day: i,
        isCurrentMonth: false,
        date: null,
      });
    }
    
    return days;
  };

  // Pagar/Realizar instância recorrente - primeiro busca candidatas
  const handlePay = async (instance) => {
    setActionLoading(instance.id);
    try {
      // Buscar transações candidatas para conciliação
      const candidates = await recurringService.findCandidates(instance.id, 15);
      
      if (candidates && candidates.length > 0) {
        // Encontrou candidatas - mostrar modal para escolher
        setReconcileData({
          instance,
          candidates,
          loading: false,
        });
        setShowReconcileModal(true);
      } else {
        // Não encontrou - criar nova transação diretamente
        await recurringService.payInstance(instance.id);
        await loadCalendar();
        if (selectedDate) {
          await loadDay(selectedDate);
        }
      }
    } catch (error) {
      console.error('Error processing payment:', error);
    } finally {
      setActionLoading(null);
    }
  };

  // Conciliar instância com transação existente
  const handleReconcile = async (transactionId) => {
    if (!reconcileData.instance) return;
    
    setReconcileData(prev => ({ ...prev, loading: true }));
    try {
      await recurringService.reconcileInstance(reconcileData.instance.id, transactionId);
      setShowReconcileModal(false);
      setReconcileData({ instance: null, candidates: [], loading: false });
      await loadCalendar();
      if (selectedDate) {
        await loadDay(selectedDate);
      }
    } catch (error) {
      console.error('Error reconciling:', error);
    } finally {
      setReconcileData(prev => ({ ...prev, loading: false }));
    }
  };

  // Criar nova transação (quando usuário escolhe não conciliar)
  const handleCreateNew = async () => {
    if (!reconcileData.instance) return;
    
    setReconcileData(prev => ({ ...prev, loading: true }));
    try {
      await recurringService.payInstance(reconcileData.instance.id);
      setShowReconcileModal(false);
      setReconcileData({ instance: null, candidates: [], loading: false });
      await loadCalendar();
      if (selectedDate) {
        await loadDay(selectedDate);
      }
    } catch (error) {
      console.error('Error creating transaction:', error);
    } finally {
      setReconcileData(prev => ({ ...prev, loading: false }));
    }
  };

  // Skip instância recorrente
  const handleSkip = async (instanceId) => {
    setActionLoading(instanceId);
    try {
      await recurringService.skipInstance(instanceId);
      // Recarregar dados
      await loadCalendar();
      if (selectedDate) {
        await loadDay(selectedDate);
      }
    } catch (error) {
      console.error('Error skipping:', error);
    } finally {
      setActionLoading(null);
    }
  };

  const today = new Date().toISOString().split('T')[0];
  const days = generateCalendarDays();
  const weekDays = i18n.language === 'pt-BR' 
    ? ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb']
    : i18n.language === 'es'
    ? ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb']
    : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  const monthNames = i18n.language === 'pt-BR'
    ? ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
    : i18n.language === 'es'
    ? ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']
    : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  return (
    <div className="row g-4">
      {/* Calendário */}
      <div className="col-lg-5">
        <div ref={calendarRef} className="card border-0" style={{ background: '#0f172a' }}>
          <div className="card-header border-0 d-flex justify-content-between align-items-center py-3"
               style={{ background: 'transparent', borderBottom: '1px solid rgba(59, 130, 246, 0.2)' }}>
            <h6 className="text-white mb-0 d-flex align-items-center">
              <i className="bi bi-calendar3 me-2 text-primary"></i>
              {t('dashboard.calendar')}
            </h6>
            <button 
              className="btn btn-outline-primary btn-sm"
              onClick={goToToday}
              style={{ fontSize: '11px' }}
            >
              {t('common.today')}
            </button>
          </div>
          <div className="card-body pt-0">
            {/* Navegação do mês */}
            <div className="d-flex justify-content-between align-items-center mb-3">
              <button 
                className="btn btn-link text-slate-400 p-0"
                onClick={prevMonth}
              >
                <i className="bi bi-chevron-left"></i>
              </button>
              <span className="text-white fw-medium">
                {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
              </span>
              <button 
                className="btn btn-link text-slate-400 p-0"
                onClick={nextMonth}
              >
                <i className="bi bi-chevron-right"></i>
              </button>
            </div>

            {loading ? (
              <div className="text-center py-4">
                <div className="spinner-border spinner-border-sm text-primary" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
              </div>
            ) : (
              <>
                {/* Dias da semana */}
                <div className="calendar-grid mb-2">
                  {weekDays.map(day => (
                    <div key={day} className="text-center">
                      <small className="text-slate-500" style={{ fontSize: '10px' }}>{day}</small>
                    </div>
                  ))}
                </div>

                {/* Dias */}
                <div className="calendar-grid">
                  {days.map((day, index) => (
                    <div key={index} className="calendar-day">
                      {day.isCurrentMonth ? (
                        <button
                          className={`btn w-100 h-100 p-0 d-flex flex-column align-items-center justify-content-center rounded-2
                            ${day.date === selectedDate ? 'btn-primary' : 'btn-link'}
                            ${day.date === today && day.date !== selectedDate ? 'border border-primary' : ''}
                          `}
                          style={{ 
                            fontSize: '12px',
                            background: day.date === selectedDate ? undefined : 'transparent',
                            color: day.date === selectedDate ? 'white' : day.data ? '#fff' : '#64748b',
                          }}
                          onClick={() => setSelectedDate(day.date)}
                        >
                          <span>{day.day}</span>
                          {day.data && (
                            <div className="d-flex gap-1 mt-1">
                              {day.data.has_transactions && (
                                <span 
                                  className="rounded-circle"
                                  style={{ 
                                    width: '4px', 
                                    height: '4px', 
                                    background: '#3b82f6',
                                  }}
                                ></span>
                              )}
                              {day.data.has_recurring && (
                                <span 
                                  className="rounded-circle"
                                  style={{ 
                                    width: '4px', 
                                    height: '4px', 
                                    background: '#f59e0b',
                                  }}
                                ></span>
                              )}
                            </div>
                          )}
                        </button>
                      ) : (
                        <div 
                          className="w-100 h-100 d-flex align-items-center justify-content-center text-slate-700"
                          style={{ fontSize: '12px' }}
                        >
                          {day.day}
                        </div>
                      )}
                    </div>
                  ))}
                </div>

                {/* Legenda */}
                <div className="d-flex justify-content-center gap-3 mt-3 pt-2" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                  <small className="text-slate-500 d-flex align-items-center gap-1">
                    <span className="rounded-circle" style={{ width: '8px', height: '8px', background: '#3b82f6' }}></span>
                    {t('dashboard.transactions')}
                  </small>
                  <small className="text-slate-500 d-flex align-items-center gap-1">
                    <span className="rounded-circle" style={{ width: '8px', height: '8px', background: '#f59e0b' }}></span>
                    {t('dashboard.pendingRecurring')}
                  </small>
                </div>

                {/* Resumo do mês */}
                {calendarData?.summary && (
                  <div className="row mt-3 pt-2 g-2" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                    <div className="col-6">
                      <div className="text-center">
                        <small className="text-slate-500 d-block" style={{ fontSize: '10px' }}>
                          {t('dashboard.pendingRecurring')}
                        </small>
                        <span className="text-warning fw-bold small">
                          {calendarData.summary.pending_recurring}
                        </span>
                      </div>
                    </div>
                    <div className="col-6">
                      <div className="text-center">
                        <small className="text-slate-500 d-block" style={{ fontSize: '10px' }}>
                          {t('dashboard.pendingAmount')}
                        </small>
                        <span className="text-warning fw-bold small">
                          {currency(calendarData.summary.pending_recurring_amount || 0, 'EUR')}
                        </span>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>

      {/* Lista de transações do dia */}
      <div className="col-lg-7">
        <div 
          ref={transactionsRef}
          className="card border-0 d-flex flex-column" 
          style={{ 
            background: '#0f172a',
            height: calendarHeight ? `${calendarHeight}px` : 'auto',
          }}
        >
          <div className="card-header border-0 py-3 flex-shrink-0"
               style={{ background: 'transparent', borderBottom: '1px solid rgba(59, 130, 246, 0.2)' }}>
            <h6 className="text-white mb-0 d-flex align-items-center">
              <i className="bi bi-list-ul me-2 text-primary"></i>
              {selectedDate ? (
                dayData?.date_formatted || selectedDate
              ) : (
                t('dashboard.selectDate')
              )}
            </h6>
          </div>
          <div className="card-body py-2 flex-grow-1 overflow-auto" style={{ minHeight: 0 }}>
            {!selectedDate ? (
              <div className="text-center text-slate-400 py-5">
                <i className="bi bi-calendar-event fs-1 mb-2 d-block"></i>
                <p className="small mb-0">{t('dashboard.selectDateHint')}</p>
              </div>
            ) : dayLoading ? (
              <div className="text-center py-4">
                <div className="spinner-border spinner-border-sm text-primary" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
              </div>
            ) : !dayData?.items?.length ? (
              <div className="text-center text-slate-400 py-5">
                <i className="bi bi-calendar-x fs-1 mb-2 d-block"></i>
                <p className="small mb-0">{t('dashboard.noTransactionsDay')}</p>
              </div>
            ) : (
              <>
                {dayData.items.map((item, index) => (
                  <div 
                    key={`${item.type}-${item.id}`}
                    className="d-flex align-items-center py-2 px-3 rounded-2 mb-2"
                    style={{ 
                      background: item.type === 'recurring' 
                        ? 'rgba(245, 158, 11, 0.1)' 
                        : 'rgba(255,255,255,0.03)',
                      borderLeft: item.type === 'recurring' 
                        ? '3px solid #f59e0b'
                        : `3px solid ${item.transaction_type === 'credit' ? '#22c55e' : '#ef4444'}`
                    }}
                  >
                    {/* Ícone */}
                    <div 
                      className="rounded-circle d-flex align-items-center justify-content-center me-3"
                      style={{ 
                        width: '36px', 
                        height: '36px', 
                        background: item.type === 'recurring' 
                          ? 'rgba(245, 158, 11, 0.2)'
                          : item.category?.color 
                            ? `${item.category.color}20`
                            : 'rgba(59, 130, 246, 0.15)',
                        flexShrink: 0,
                      }}
                    >
                      {item.type === 'recurring' ? (
                        <i className="bi bi-arrow-repeat text-warning" style={{ fontSize: '14px' }}></i>
                      ) : item.is_transfer ? (
                        <i className="bi bi-arrow-left-right text-info" style={{ fontSize: '14px' }}></i>
                      ) : (
                        <i 
                          className={`bi ${item.category?.icon || 'bi-tag'}`}
                          style={{ 
                            fontSize: '14px',
                            color: item.category?.color || '#3b82f6'
                          }}
                        ></i>
                      )}
                    </div>

                    {/* Info */}
                    <div className="flex-grow-1 min-width-0">
                      <div className="d-flex align-items-center gap-2">
                        <span className="text-white small text-truncate" style={{ maxWidth: '200px' }}>
                          {item.description}
                        </span>
                        {item.type === 'recurring' && (
                          <span className="badge bg-warning text-dark" style={{ fontSize: '9px' }}>
                            #{item.occurrence_number}
                          </span>
                        )}
                      </div>
                      <div className="d-flex align-items-center gap-2">
                        <small className="text-slate-500" style={{ fontSize: '11px' }}>
                          {item.account?.name || '-'}
                        </small>
                        {item.category && (
                          <>
                            <span className="text-slate-600">•</span>
                            <small className="text-slate-500" style={{ fontSize: '11px' }}>
                              {item.category.name}
                            </small>
                          </>
                        )}
                      </div>
                    </div>

                    {/* Valor e ações */}
                    <div className="text-end ms-2">
                      <div className={`fw-bold ${item.transaction_type === 'credit' ? 'text-success' : 'text-danger'}`}>
                        {item.transaction_type === 'credit' ? '+' : '-'}
                        {currency(item.amount, item.account?.currency || 'EUR')}
                      </div>
                      
                      {/* Ações para recorrentes */}
                      {item.type === 'recurring' && (
                        <div className="d-flex gap-1 justify-content-end mt-1">
                          <button
                            className="btn btn-outline-success btn-sm py-0 px-1"
                            style={{ fontSize: '10px' }}
                            onClick={() => handlePay(item)}
                            disabled={actionLoading === item.id}
                            title={t('recurring.actions.pay')}
                          >
                            {actionLoading === item.id ? (
                              <span className="spinner-border spinner-border-sm" style={{ width: '10px', height: '10px' }}></span>
                            ) : (
                              <i className="bi bi-check-lg"></i>
                            )}
                          </button>
                          <button
                            className="btn btn-outline-secondary btn-sm py-0 px-1"
                            style={{ fontSize: '10px' }}
                            onClick={() => handleSkip(item.id)}
                            disabled={actionLoading === item.id}
                            title={t('recurring.actions.skip')}
                          >
                            <i className="bi bi-skip-forward"></i>
                          </button>
                        </div>
                      )}

                      {/* Status para transações */}
                      {item.type === 'transaction' && item.status !== 'completed' && (
                        <small className={`badge ${
                          item.status === 'pending' ? 'bg-warning' : 
                          item.status === 'scheduled' ? 'bg-info' : 'bg-secondary'
                        }`} style={{ fontSize: '9px' }}>
                          {t(`transactions.status.${item.status}`)}
                        </small>
                      )}
                    </div>
                  </div>
                ))}

                {/* Resumo do dia */}
                {dayData?.summary && (
                  <div className="row mt-3 pt-2 g-2" style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                    <div className="col-6">
                      <div className="text-center">
                        <small className="text-slate-500 d-block" style={{ fontSize: '10px' }}>
                          {t('dashboard.income')}
                        </small>
                        <span className="text-success fw-bold small">
                          +{currency(dayData.summary.total_credit || 0, 'EUR')}
                        </span>
                      </div>
                    </div>
                    <div className="col-6">
                      <div className="text-center">
                        <small className="text-slate-500 d-block" style={{ fontSize: '10px' }}>
                          {t('dashboard.expenses')}
                        </small>
                        <span className="text-danger fw-bold small">
                          -{currency(dayData.summary.total_debit || 0, 'EUR')}
                        </span>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>

      {/* Modal de Conciliação */}
      {showReconcileModal && reconcileData.instance && (
        <div className="modal show d-block" tabIndex="-1" style={{ backgroundColor: 'rgba(0,0,0,0.7)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content" style={{ background: '#1e293b', border: '1px solid rgba(59, 130, 246, 0.3)' }}>
              <div className="modal-header border-0">
                <h6 className="modal-title text-white">
                  <i className="bi bi-link-45deg me-2 text-primary"></i>
                  {t('recurring.reconcileOrCreate')}
                </h6>
                <button 
                  type="button" 
                  className="btn-close btn-close-white" 
                  onClick={() => {
                    setShowReconcileModal(false);
                    setReconcileData({ instance: null, candidates: [], loading: false });
                  }}
                  disabled={reconcileData.loading}
                ></button>
              </div>
              <div className="modal-body">
                {/* Info da instância */}
                <div className="alert alert-info py-2 mb-3" style={{ background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)' }}>
                  <div className="d-flex justify-content-between align-items-center">
                    <div>
                      <strong className="text-white">{reconcileData.instance.description}</strong>
                      <div className="small text-slate-400">
                        {t('recurring.dueDate')}: {formatDate(reconcileData.instance.due_date)}
                      </div>
                    </div>
                    <div className="text-end">
                      <span className={`fw-bold ${reconcileData.instance.transaction_type === 'credit' ? 'text-success' : 'text-danger'}`}>
                        {currency(reconcileData.instance.amount, reconcileData.instance.account?.currency || 'EUR')}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Aviso */}
                <div className="alert alert-warning py-2 mb-3" style={{ background: 'rgba(245, 158, 11, 0.1)', border: '1px solid rgba(245, 158, 11, 0.3)' }}>
                  <i className="bi bi-exclamation-triangle me-2"></i>
                  <small className="text-warning">{t('recurring.candidatesFound', { count: reconcileData.candidates.length })}</small>
                </div>

                {/* Lista de candidatas */}
                <div className="mb-3">
                  <small className="text-slate-400 d-block mb-2">{t('recurring.selectToReconcile')}:</small>
                  <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
                    {reconcileData.candidates.map(tx => (
                      <div 
                        key={tx.id}
                        className="d-flex align-items-center justify-content-between p-2 rounded mb-1"
                        style={{ 
                          background: 'rgba(255,255,255,0.05)',
                          cursor: reconcileData.loading ? 'not-allowed' : 'pointer',
                        }}
                        onClick={() => !reconcileData.loading && handleReconcile(tx.id)}
                      >
                        <div>
                          <div className="text-white small">{tx.description}</div>
                          <div className="text-slate-500" style={{ fontSize: '10px' }}>
                            {formatDate(tx.effective_date || tx.planned_date)} • {tx.account?.name}
                          </div>
                        </div>
                        <div className="text-end">
                          <span className={`fw-bold small ${tx.type === 'credit' ? 'text-success' : 'text-danger'}`}>
                            {currency(Math.abs(tx.amount || tx.planned_amount), tx.account?.currency || 'EUR')}
                          </span>
                          <div>
                            <i className="bi bi-link text-primary" style={{ fontSize: '12px' }}></i>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Separador */}
                <div className="text-center text-slate-500 my-3">
                  <small>— {t('common.or')} —</small>
                </div>

                {/* Botão criar nova */}
                <button
                  className="btn btn-outline-success w-100"
                  onClick={handleCreateNew}
                  disabled={reconcileData.loading}
                >
                  {reconcileData.loading ? (
                    <span className="spinner-border spinner-border-sm me-2"></span>
                  ) : (
                    <i className="bi bi-plus-circle me-2"></i>
                  )}
                  {t('recurring.createNewTransaction')}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* CSS para o grid do calendário */}
      <style>{`
        .calendar-grid {
          display: grid;
          grid-template-columns: repeat(7, 1fr);
          gap: 2px;
        }
        .calendar-day {
          aspect-ratio: 1;
          min-height: 32px;
        }
      `}</style>
    </div>
  );
};

export default CalendarWidget;
