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

export default function TransferDetection() {
  const { t } = useTranslation();
  const { currency, date } = useFormatters();
  
  const [transfers, setTransfers] = 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(3);
  
  // Estados para seleção em lote
  const [selectedTransfers, setSelectedTransfers] = useState(new Set());
  
  // Estados para modais
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showBatchConfirmModal, setShowBatchConfirmModal] = useState(false);
  const [selectedTransfer, setSelectedTransfer] = useState(null);

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

  const loadTransfers = useCallback(async () => {
    try {
      setLoading(true);
      setSelectedTransfers(new Set()); // Limpar seleção ao recarregar
      const response = await transferDetectionService.getAll(toleranceDays);
      setTransfers(response.data || []);
    } catch (error) {
      console.error('Erro ao carregar transferências:', error);
      showToast(t('transfers.loadError'), 'danger');
    } finally {
      setLoading(false);
    }
  }, [t, toleranceDays]);

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

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

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

  const handleConfirmClick = (transfer, index) => {
    setSelectedTransfer({ ...transfer, index });
    setShowConfirmModal(true);
  };

  const handleDeleteClick = (transfer, index) => {
    setSelectedTransfer({ ...transfer, index });
    setShowDeleteModal(true);
  };

  const confirmTransfer = async () => {
    if (!selectedTransfer) return;
    
    try {
      setProcessing(selectedTransfer.index);
      await transferDetectionService.confirm(selectedTransfer.debit.id, selectedTransfer.credit.id);
      showToast(t('transfers.confirmed'), 'success');
      loadTransfers();
    } catch (error) {
      console.error('Erro ao confirmar:', error);
      showToast(error.response?.data?.message || t('transfers.confirmError'), 'danger');
    } finally {
      setProcessing(null);
      setShowConfirmModal(false);
      setSelectedTransfer(null);
    }
  };

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

  const deleteBoth = async () => {
    if (!selectedTransfer) return;
    
    try {
      setProcessing(selectedTransfer.index);
      await transferDetectionService.deleteBoth(selectedTransfer.debit.id, selectedTransfer.credit.id);
      showToast(t('transfers.deleted'), 'success');
      loadTransfers();
    } catch (error) {
      console.error('Erro ao excluir:', error);
      showToast(error.response?.data?.message || t('transfers.deleteError'), 'danger');
    } finally {
      setProcessing(null);
      setShowDeleteModal(false);
      setSelectedTransfer(null);
    }
  };

  const handleIgnore = async (transfer, index) => {
    try {
      setProcessing(index);
      await transferDetectionService.ignore(transfer.debit.id, transfer.credit.id);
      showToast(t('transfers.ignored'), 'success');
      loadTransfers();
    } catch (error) {
      console.error('Erro ao ignorar:', error);
      showToast(error.response?.data?.message || t('transfers.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-arrow-left-right me-2"></i>
            {t('transfers.title')}
          </h1>
          <p className="text-slate-400 mb-0">
            {t('transfers.subtitle')}
          </p>
        </div>
        <div className="d-flex gap-2 align-items-center">
          <label className="text-slate-400 me-2">{t('transfers.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="0">0 {t('transfers.days')}</option>
            <option value="1">1 {t('transfers.day')}</option>
            <option value="3">3 {t('transfers.days')}</option>
            <option value="5">5 {t('transfers.days')}</option>
            <option value="7">7 {t('transfers.days')}</option>
          </select>
          <button 
            className="btn btn-outline-light btn-sm"
            onClick={loadTransfers}
            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">{transfers.length}</h3>
              <small className="text-slate-400">{t('transfers.potentialTransfers')}</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">{selectedTransfers.size}</h3>
              <small className="text-slate-400">{t('transfers.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">
              {transfers.length > 0 && (
                <>
                  <button
                    className="btn btn-outline-info btn-sm"
                    onClick={toggleSelectAll}
                    disabled={loading}
                  >
                    <i className={`bi ${selectedTransfers.size === transfers.length ? 'bi-check-square' : 'bi-square'} me-1`}></i>
                    {selectedTransfers.size === transfers.length ? t('transfers.deselectAll') : t('transfers.selectAll')}
                  </button>
                  <button
                    className="btn btn-success btn-sm"
                    onClick={() => setShowBatchConfirmModal(true)}
                    disabled={selectedTransfers.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('transfers.confirmSelected')} ({selectedTransfers.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('transfers.loading')}</p>
        </div>
      )}

      {/* Empty State */}
      {!loading && transfers.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('transfers.noTransfers')}</h4>
          <p className="text-slate-400">{t('transfers.noTransfersDesc')}</p>
        </div>
      )}

      {/* Lista de Transferências */}
      {!loading && transfers.length > 0 && (
        <div className="row g-3">
          {transfers.map((transfer, index) => (
            <div key={`${transfer.debit.id}-${transfer.credit.id}`} className="col-12">
              <div 
                className="card" 
                style={{ 
                  backgroundColor: selectedTransfers.has(index) ? '#2d3a4f' : '#1e293b', 
                  border: selectedTransfers.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={selectedTransfers.has(index)}
                        onChange={() => toggleSelect(index)}
                        style={{ cursor: 'pointer' }}
                      />
                    </div>
                    <span className={`badge bg-${getConfidenceColor(transfer.confidence?.level)}`}>
                      <i className="bi bi-speedometer2 me-1"></i>
                      {transfer.confidence?.percentage || 50}%
                    </span>
                    <span className="text-white fw-medium">
                      {currency(Math.abs(transfer.amount))}
                    </span>
                    {transfer.days_diff === 0 ? (
                      <span className="badge bg-success">{t('transfers.sameDay')}</span>
                    ) : (
                      <span className="badge bg-secondary">
                        {transfer.days_diff} {transfer.days_diff === 1 ? t('transfers.day') : t('transfers.days')} {t('transfers.apart')}
                      </span>
                    )}
                  </div>
                  <div className="d-flex gap-2">
                    <button
                      className="btn btn-sm btn-success"
                      onClick={() => handleConfirmClick(transfer, index)}
                      disabled={processing === index}
                      title={t('transfers.confirmTransfer')}
                    >
                      {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('transfers.confirm')}
                    </button>
                    <button
                      className="btn btn-sm btn-outline-secondary"
                      onClick={() => handleIgnore(transfer, index)}
                      disabled={processing === index}
                      title={t('transfers.ignoreTransfer')}
                    >
                      <i className="bi bi-eye-slash"></i>
                    </button>
                    <button
                      className="btn btn-sm btn-outline-danger"
                      onClick={() => handleDeleteClick(transfer, index)}
                      disabled={processing === index}
                      title={t('transfers.deleteBoth')}
                    >
                      <i className="bi bi-trash"></i>
                    </button>
                  </div>
                </div>
                <div className="card-body" onClick={() => toggleSelect(index)} style={{ cursor: 'pointer' }}>
                  <div className="row">
                    {/* Débito */}
                    <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('transfers.debit')}
                          </span>
                          <small className="text-slate-500">ID: {transfer.debit.id}</small>
                        </div>
                        <div className="text-white fw-medium mb-1">
                          {transfer.debit.description || t('transfers.noDescription')}
                        </div>
                        <div className="d-flex justify-content-between align-items-center">
                          <span className="text-slate-400">
                            <i className="bi bi-wallet2 me-1"></i>
                            {transfer.debit.account_name}
                          </span>
                          <span className="text-slate-400">
                            <i className="bi bi-calendar3 me-1"></i>
                            {date(transfer.debit.date)}
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Seta */}
                    <div className="col-md-2 d-flex align-items-center justify-content-center">
                      <i className="bi bi-arrow-right display-6 text-primary"></i>
                    </div>

                    {/* Crédito */}
                    <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('transfers.credit')}
                          </span>
                          <small className="text-slate-500">ID: {transfer.credit.id}</small>
                        </div>
                        <div className="text-white fw-medium mb-1">
                          {transfer.credit.description || t('transfers.noDescription')}
                        </div>
                        <div className="d-flex justify-content-between align-items-center">
                          <span className="text-slate-400">
                            <i className="bi bi-wallet2 me-1"></i>
                            {transfer.credit.account_name}
                          </span>
                          <span className="text-slate-400">
                            <i className="bi bi-calendar3 me-1"></i>
                            {date(transfer.credit.date)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

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

      {/* Modal Confirmar Transferência Individual */}
      <Modal
        show={showConfirmModal}
        onHide={() => setShowConfirmModal(false)}
        title={t('transfers.confirmTitle')}
      >
        <p className="text-slate-300">{t('transfers.confirmMessage')}</p>
        {selectedTransfer && (
          <div className="alert alert-info">
            <strong>{t('transfers.debit')}:</strong> {selectedTransfer.debit.account_name} → <strong>{t('transfers.credit')}:</strong> {selectedTransfer.credit.account_name}
            <br />
            <strong>{t('transfers.amount')}:</strong> {currency(Math.abs(selectedTransfer.amount))}
          </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={confirmTransfer}>
            <i className="bi bi-check-lg me-1"></i>
            {t('transfers.confirm')}
          </button>
        </div>
      </Modal>

      {/* Modal Confirmar em Lote */}
      <Modal
        show={showBatchConfirmModal}
        onHide={() => setShowBatchConfirmModal(false)}
        title={t('transfers.batchConfirmTitle')}
      >
        <p className="text-slate-300">{t('transfers.batchConfirmMessage', { count: selectedTransfers.size })}</p>
        <div className="alert alert-info">
          <i className="bi bi-info-circle me-2"></i>
          {t('transfers.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('transfers.confirmSelected')} ({selectedTransfers.size})
          </button>
        </div>
      </Modal>

      {/* Modal Excluir Ambas */}
      <Modal
        show={showDeleteModal}
        onHide={() => setShowDeleteModal(false)}
        title={t('transfers.deleteTitle')}
      >
        <p className="text-slate-300">{t('transfers.deleteMessage')}</p>
        <div className="alert alert-danger">
          <i className="bi bi-exclamation-triangle me-2"></i>
          {t('transfers.deleteWarning')}
        </div>
        <div className="d-flex justify-content-end gap-2 mt-3">
          <button className="btn btn-secondary" onClick={() => setShowDeleteModal(false)}>
            {t('common.cancel')}
          </button>
          <button className="btn btn-danger" onClick={deleteBoth}>
            <i className="bi bi-trash me-1"></i>
            {t('transfers.deleteBoth')}
          </button>
        </div>
      </Modal>
    </div>
  );
}
