import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { refundDetectionService } from '../services/api';
import useFormatters from '../hooks/useFormatters';
import Toast from '../components/Toast';
import Modal from '../components/Modal';

export default function RefundDetection() {
  const { t } = useTranslation();
  const { currency, date } = useFormatters();
  
  const [refunds, setRefunds] = useState([]);
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(null);
  const [processingBatch, setProcessingBatch] = useState(false);
  const [toast, setToast] = useState({ show: false, message: '', type: 'success' });
  const [toleranceDays, setToleranceDays] = useState(7);
  
  // Estados para seleção em lote
  const [selectedRefunds, setSelectedRefunds] = useState(new Set());
  
  // Estados para modais
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showBatchConfirmModal, setShowBatchConfirmModal] = useState(false);
  const [selectedRefund, setSelectedRefund] = useState(null);

  const showToast = (message, type = 'success') => {
    setToast({ show: true, message, type });
  };

  const loadRefunds = useCallback(async () => {
    try {
      setLoading(true);
      setSelectedRefunds(new Set());
      const response = await refundDetectionService.getAll(toleranceDays);
      setRefunds(response.data || []);
    } catch (error) {
      console.error('Erro ao carregar reembolsos:', error);
      showToast(t('refunds.loadError'), 'danger');
    } finally {
      setLoading(false);
    }
  }, [t, toleranceDays]);

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

  // Funções de seleção em lote
  const toggleSelectAll = () => {
    if (selectedRefunds.size === refunds.length) {
      setSelectedRefunds(new Set());
    } else {
      setSelectedRefunds(new Set(refunds.map((_, index) => index)));
    }
  };

  const toggleSelect = (index) => {
    const newSelected = new Set(selectedRefunds);
    if (newSelected.has(index)) {
      newSelected.delete(index);
    } else {
      newSelected.add(index);
    }
    setSelectedRefunds(newSelected);
  };

  const handleConfirmClick = (refund, index) => {
    setSelectedRefund({ ...refund, index });
    setShowConfirmModal(true);
  };

  const confirmRefund = async () => {
    if (!selectedRefund) return;
    
    try {
      setProcessing(selectedRefund.index);
      await refundDetectionService.confirm(selectedRefund.debit.id, selectedRefund.credit.id);
      showToast(t('refunds.confirmed'), 'success');
      loadRefunds();
    } catch (error) {
      console.error('Erro ao confirmar:', error);
      showToast(error.response?.data?.message || t('refunds.confirmError'), 'danger');
    } finally {
      setProcessing(null);
      setShowConfirmModal(false);
      setSelectedRefund(null);
    }
  };

  // Confirmar todas selecionadas em lote
  const confirmBatch = async () => {
    if (selectedRefunds.size === 0) return;
    
    try {
      setProcessingBatch(true);
      const refundsToConfirm = Array.from(selectedRefunds).map(index => refunds[index]);
      const result = await refundDetectionService.confirmBatch(refundsToConfirm);
      showToast(t('refunds.batchConfirmed', { count: result.confirmed_count }), 'success');
      loadRefunds();
    } catch (error) {
      console.error('Erro ao confirmar em lote:', error);
      showToast(error.response?.data?.message || t('refunds.confirmError'), 'danger');
    } finally {
      setProcessingBatch(false);
      setShowBatchConfirmModal(false);
    }
  };

  const handleIgnore = async (refund, index) => {
    try {
      setProcessing(index);
      await refundDetectionService.ignore(refund.debit.id, refund.credit.id);
      showToast(t('refunds.ignored'), 'success');
      loadRefunds();
    } catch (error) {
      console.error('Erro ao ignorar:', error);
      showToast(error.response?.data?.message || t('refunds.ignoreError'), 'danger');
    } finally {
      setProcessing(null);
    }
  };

  const getConfidenceColor = (level) => {
    switch (level) {
      case 'high': return 'success';
      case 'medium': return 'warning';
      default: return 'secondary';
    }
  };

  return (
    <div className="container-fluid">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h1 className="h3 text-white mb-1">
            <i className="bi bi-receipt-cutoff me-2"></i>
            {t('refunds.title')}
          </h1>
          <p className="text-slate-400 mb-0">
            {t('refunds.subtitle')}
          </p>
        </div>
        <div className="d-flex gap-2 align-items-center">
          <label className="text-slate-400 me-2">{t('refunds.toleranceDays')}:</label>
          <select 
            className="form-select form-select-sm" 
            style={{ width: 'auto', backgroundColor: '#1e293b', color: 'white', border: '1px solid #334155' }}
            value={toleranceDays}
            onChange={(e) => setToleranceDays(parseInt(e.target.value))}
          >
            <option value="1">1 {t('refunds.day')}</option>
            <option value="3">3 {t('refunds.days')}</option>
            <option value="7">7 {t('refunds.days')}</option>
            <option value="14">14 {t('refunds.days')}</option>
            <option value="30">30 {t('refunds.days')}</option>
          </select>
          <button 
            className="btn btn-outline-light btn-sm"
            onClick={loadRefunds}
            disabled={loading}
          >
            <i className={`bi bi-arrow-clockwise ${loading ? 'spin' : ''}`}></i>
          </button>
        </div>
      </div>

      {/* Stats e Ações em Lote */}
      <div className="row mb-4">
        <div className="col-md-4">
          <div className="card bg-dark border-secondary">
            <div className="card-body text-center">
              <h3 className="text-warning mb-0">{refunds.length}</h3>
              <small className="text-slate-400">{t('refunds.potentialRefunds')}</small>
            </div>
          </div>
        </div>
        <div className="col-md-4">
          <div className="card bg-dark border-secondary">
            <div className="card-body text-center">
              <h3 className="text-info mb-0">{selectedRefunds.size}</h3>
              <small className="text-slate-400">{t('refunds.selected')}</small>
            </div>
          </div>
        </div>
        <div className="col-md-4">
          <div className="card bg-dark border-secondary">
            <div className="card-body d-flex align-items-center justify-content-center gap-2">
              {refunds.length > 0 && (
                <>
                  <button
                    className="btn btn-outline-info btn-sm"
                    onClick={toggleSelectAll}
                    disabled={loading}
                  >
                    <i className={`bi ${selectedRefunds.size === refunds.length ? 'bi-check-square' : 'bi-square'} me-1`}></i>
                    {selectedRefunds.size === refunds.length ? t('refunds.deselectAll') : t('refunds.selectAll')}
                  </button>
                  <button
                    className="btn btn-success btn-sm"
                    onClick={() => setShowBatchConfirmModal(true)}
                    disabled={selectedRefunds.size === 0 || processingBatch}
                  >
                    {processingBatch ? (
                      <span className="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                    ) : (
                      <i className="bi bi-check-all me-1"></i>
                    )}
                    {t('refunds.confirmSelected')} ({selectedRefunds.size})
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Loading */}
      {loading && (
        <div className="text-center py-5">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
          <p className="text-slate-400 mt-2">{t('refunds.loading')}</p>
        </div>
      )}

      {/* Empty State */}
      {!loading && refunds.length === 0 && (
        <div className="text-center py-5">
          <i className="bi bi-check-circle display-1 text-success"></i>
          <h4 className="text-white mt-3">{t('refunds.noRefunds')}</h4>
          <p className="text-slate-400">{t('refunds.noRefundsDesc')}</p>
        </div>
      )}

      {/* Lista de Reembolsos */}
      {!loading && refunds.length > 0 && (
        <div className="row g-3">
          {refunds.map((refund, index) => (
            <div key={`${refund.debit.id}-${refund.credit.id}`} className="col-12">
              <div 
                className="card" 
                style={{ 
                  backgroundColor: selectedRefunds.has(index) ? '#2d3a4f' : '#1e293b', 
                  border: selectedRefunds.has(index) ? '2px solid #0ea5e9' : '1px solid #334155' 
                }}
              >
                <div className="card-header d-flex justify-content-between align-items-center" style={{ borderBottom: '1px solid #334155' }}>
                  <div className="d-flex align-items-center gap-3">
                    {/* Checkbox para seleção */}
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="checkbox"
                        checked={selectedRefunds.has(index)}
                        onChange={() => toggleSelect(index)}
                        style={{ cursor: 'pointer' }}
                      />
                    </div>
                    <span className={`badge bg-${getConfidenceColor(refund.confidence?.level)}`}>
                      <i className="bi bi-speedometer2 me-1"></i>
                      {refund.confidence?.percentage || 50}%
                    </span>
                    <span className="text-white fw-medium">
                      {currency(Math.abs(refund.amount))}
                    </span>
                    {refund.days_diff === 0 ? (
                      <span className="badge bg-success">{t('refunds.sameDay')}</span>
                    ) : (
                      <span className="badge bg-secondary">
                        {refund.days_diff} {refund.days_diff === 1 ? t('refunds.day') : t('refunds.days')} {t('refunds.apart')}
                      </span>
                    )}
                    <span className="badge bg-info">
                      <i className="bi bi-wallet2 me-1"></i>
                      {refund.debit.account_name}
                    </span>
                  </div>
                  <div className="d-flex gap-2">
                    <button
                      className="btn btn-sm btn-success"
                      onClick={() => handleConfirmClick(refund, index)}
                      disabled={processing === index}
                      title={t('refunds.confirmRefund')}
                    >
                      {processing === index ? (
                        <span className="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                      ) : (
                        <i className="bi bi-check-lg me-1"></i>
                      )}
                      {t('refunds.confirm')}
                    </button>
                    <button
                      className="btn btn-sm btn-outline-secondary"
                      onClick={() => handleIgnore(refund, index)}
                      disabled={processing === index}
                      title={t('refunds.ignoreRefund')}
                    >
                      <i className="bi bi-eye-slash"></i>
                    </button>
                  </div>
                </div>
                <div className="card-body" onClick={() => toggleSelect(index)} style={{ cursor: 'pointer' }}>
                  <div className="row">
                    {/* Gasto Original */}
                    <div className="col-md-5">
                      <div className="border rounded p-3" style={{ borderColor: '#dc3545 !important', backgroundColor: 'rgba(220, 53, 69, 0.1)' }}>
                        <div className="d-flex justify-content-between align-items-start mb-2">
                          <span className="badge bg-danger">
                            <i className="bi bi-arrow-down-circle me-1"></i>
                            {t('refunds.expense')}
                          </span>
                          <small className="text-slate-500">ID: {refund.debit.id}</small>
                        </div>
                        <div className="text-white fw-medium mb-1">
                          {refund.debit.description || t('refunds.noDescription')}
                        </div>
                        <div className="d-flex justify-content-between align-items-center">
                          <span className="text-danger fw-bold">
                            {currency(refund.debit.amount)}
                          </span>
                          <span className="text-slate-400">
                            <i className="bi bi-calendar3 me-1"></i>
                            {date(refund.debit.date)}
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Seta Cancelamento */}
                    <div className="col-md-2 d-flex flex-column align-items-center justify-content-center">
                      <i className="bi bi-x-circle display-6 text-warning mb-1"></i>
                      <small className="text-warning">{t('refunds.cancelsOut')}</small>
                    </div>

                    {/* Reembolso */}
                    <div className="col-md-5">
                      <div className="border rounded p-3" style={{ borderColor: '#198754 !important', backgroundColor: 'rgba(25, 135, 84, 0.1)' }}>
                        <div className="d-flex justify-content-between align-items-start mb-2">
                          <span className="badge bg-success">
                            <i className="bi bi-arrow-up-circle me-1"></i>
                            {t('refunds.refund')}
                          </span>
                          <small className="text-slate-500">ID: {refund.credit.id}</small>
                        </div>
                        <div className="text-white fw-medium mb-1">
                          {refund.credit.description || t('refunds.noDescription')}
                        </div>
                        <div className="d-flex justify-content-between align-items-center">
                          <span className="text-success fw-bold">
                            +{currency(Math.abs(refund.credit.amount))}
                          </span>
                          <span className="text-slate-400">
                            <i className="bi bi-calendar3 me-1"></i>
                            {date(refund.credit.date)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  {/* Motivos da Confiança */}
                  {refund.confidence?.reasons && refund.confidence.reasons.length > 0 && (
                    <div className="mt-3 pt-3" style={{ borderTop: '1px solid #334155' }}>
                      <small className="text-slate-400">
                        <i className="bi bi-lightbulb me-1"></i>
                        {t('refunds.reasons')}: {refund.confidence.reasons.map(r => t(`refunds.reasonLabels.${r}`, r)).join(', ')}
                      </small>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Toast */}
      <Toast
        show={toast.show}
        message={toast.message}
        type={toast.type}
        onClose={() => setToast({ ...toast, show: false })}
      />

      {/* Modal Confirmar Reembolso Individual */}
      <Modal
        show={showConfirmModal}
        onHide={() => setShowConfirmModal(false)}
        title={t('refunds.confirmTitle')}
      >
        <p className="text-slate-300">{t('refunds.confirmMessage')}</p>
        {selectedRefund && (
          <div className="alert alert-info">
            <strong>{t('refunds.expense')}:</strong> {selectedRefund.debit.description}
            <br />
            <strong>{t('refunds.refund')}:</strong> {selectedRefund.credit.description}
            <br />
            <strong>{t('refunds.amount')}:</strong> {currency(Math.abs(selectedRefund.amount))}
          </div>
        )}
        <div className="alert alert-secondary">
          <i className="bi bi-info-circle me-2"></i>
          {t('refunds.confirmInfo')}
        </div>
        <div className="d-flex justify-content-end gap-2 mt-3">
          <button className="btn btn-secondary" onClick={() => setShowConfirmModal(false)}>
            {t('common.cancel')}
          </button>
          <button className="btn btn-success" onClick={confirmRefund}>
            <i className="bi bi-check-lg me-1"></i>
            {t('refunds.confirm')}
          </button>
        </div>
      </Modal>

      {/* Modal Confirmar em Lote */}
      <Modal
        show={showBatchConfirmModal}
        onHide={() => setShowBatchConfirmModal(false)}
        title={t('refunds.batchConfirmTitle')}
      >
        <p className="text-slate-300">{t('refunds.batchConfirmMessage', { count: selectedRefunds.size })}</p>
        <div className="alert alert-info">
          <i className="bi bi-info-circle me-2"></i>
          {t('refunds.batchConfirmInfo')}
        </div>
        <div className="d-flex justify-content-end gap-2 mt-3">
          <button className="btn btn-secondary" onClick={() => setShowBatchConfirmModal(false)}>
            {t('common.cancel')}
          </button>
          <button className="btn btn-success" onClick={confirmBatch} disabled={processingBatch}>
            {processingBatch ? (
              <span className="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
            ) : (
              <i className="bi bi-check-all me-1"></i>
            )}
            {t('refunds.confirmSelected')} ({selectedRefunds.size})
          </button>
        </div>
      </Modal>
    </div>
  );
}
