import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { accountService, liabilityAccountService } from '../services/api';
import { useToast } from '../components/Toast';
import { ConfirmModal } from '../components/Modal';
import IconSelector from '../components/IconSelector';
import CurrencySelector from '../components/CurrencySelector';
import { useFormatters } from '../hooks';

const Accounts = () => {
  const { t } = useTranslation();
  const toast = useToast();
  const navigate = useNavigate();
  const { currency: formatCurrencyHook } = useFormatters();
  const [accounts, setAccounts] = useState([]);
  const [liabilityAccounts, setLiabilityAccounts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showAdjustModal, setShowAdjustModal] = useState(false);
  const [adjustAccount, setAdjustAccount] = useState(null);
  const [targetBalance, setTargetBalance] = useState('');
  const [adjusting, setAdjusting] = useState(false);
  const [selectedAccount, setSelectedAccount] = useState(null);
  const [saving, setSaving] = useState(false);
  const [recalculating, setRecalculating] = useState(false);
  const [filter, setFilter] = useState({ type: '', is_active: '' });

  const [formData, setFormData] = useState({
    name: '',
    type: 'checking',
    bank_name: '',
    account_number: '',
    initial_balance: '0',
    credit_limit: '',
    currency: 'BRL',
    color: '#1E40AF',
    icon: 'bi-bank',
    description: '',
    is_active: true,
    include_in_total: true,
  });

  const accountTypes = accountService.types;
  const accountIcons = accountService.icons;

  useEffect(() => {
    loadAccounts();
  }, [filter]);

  const loadAccounts = async () => {
    try {
      setLoading(true);
      
      // Recalcular saldos automaticamente antes de carregar
      await accountService.recalculateAllBalances();
      
      const params = {};
      if (filter.type) params.type = filter.type;
      if (filter.is_active !== '') params.is_active = filter.is_active;
      
      // Carregar contas normais e passivas em paralelo
      const [accountsResponse, liabilityResponse] = await Promise.all([
        accountService.getAll(params),
        liabilityAccountService.getAll({ is_active: filter.is_active || undefined })
      ]);
      
      if (accountsResponse.success) {
        setAccounts(accountsResponse.data);
      }
      if (liabilityResponse.success) {
        setLiabilityAccounts(liabilityResponse.data);
      }
    } catch (error) {
      toast.error(t('accounts.loadError'));
    } finally {
      setLoading(false);
    }
  };

  const handleOpenModal = (account = null) => {
    if (account) {
      setSelectedAccount(account);
      setFormData({
        name: account.name || '',
        type: account.type || 'checking',
        bank_name: account.bank_name || '',
        account_number: account.account_number || '',
        initial_balance: account.initial_balance?.toString() || '0',
        credit_limit: account.credit_limit?.toString() || '',
        currency: account.currency || 'BRL',
        color: account.color || '#1E40AF',
        icon: account.icon || 'bi-bank',
        description: account.description || '',
        is_active: account.is_active ?? true,
        include_in_total: account.include_in_total ?? true,
      });
    } else {
      setSelectedAccount(null);
      setFormData({
        name: '',
        type: 'checking',
        bank_name: '',
        account_number: '',
        initial_balance: '0',
        credit_limit: '',
        currency: 'BRL',
        color: '#1E40AF',
        icon: 'bi-bank',
        description: '',
        is_active: true,
        include_in_total: true,
      });
    }
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setSelectedAccount(null);
  };

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }));

    // Auto-selecionar ícone baseado no tipo
    if (name === 'type' && accountIcons[value]) {
      setFormData(prev => ({
        ...prev,
        icon: accountIcons[value],
      }));
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!formData.name.trim()) {
      toast.error(t('validation.required'));
      return;
    }

    setSaving(true);
    try {
      const data = {
        ...formData,
        initial_balance: parseFloat(formData.initial_balance) || 0,
        credit_limit: formData.credit_limit ? parseFloat(formData.credit_limit) : null,
      };

      let response;
      if (selectedAccount) {
        response = await accountService.update(selectedAccount.id, data);
      } else {
        response = await accountService.create(data);
      }

      if (response.success) {
        toast.success(selectedAccount ? t('accounts.updateSuccess') : t('accounts.createSuccess'));
        handleCloseModal();
        loadAccounts();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || t('accounts.createError'));
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteClick = (account) => {
    setSelectedAccount(account);
    setShowDeleteModal(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedAccount) return;

    setSaving(true);
    try {
      const response = await accountService.delete(selectedAccount.id);
      if (response.success) {
        toast.success(t('accounts.deleteSuccess'));
        setShowDeleteModal(false);
        setSelectedAccount(null);
        loadAccounts();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || t('accounts.deleteError'));
    } finally {
      setSaving(false);
    }
  };

  const formatCurrency = (value, currency = 'BRL') => {
    return formatCurrencyHook(value, currency);
  };

  const handleRecalculateBalances = async () => {
    setRecalculating(true);
    try {
      const response = await accountService.recalculateAllBalances();
      if (response.success) {
        const updated = response.data.filter(acc => acc.difference !== 0);
        if (updated.length > 0) {
          toast.success(t('accounts.recalculateSuccess', { count: updated.length }));
        } else {
          toast.info(t('accounts.balancesUpToDate'));
        }
        loadAccounts();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || t('accounts.recalculateError'));
    } finally {
      setRecalculating(false);
    }
  };

  // Abrir modal de ajuste de saldo
  const openAdjustModal = (account) => {
    setAdjustAccount(account);
    setTargetBalance(account.current_balance?.toString() || '0');
    setShowAdjustModal(true);
  };

  // Ajustar saldo da conta
  const handleAdjustBalance = async () => {
    if (!adjustAccount || targetBalance === '') return;
    
    setAdjusting(true);
    try {
      const response = await accountService.adjustBalance(adjustAccount.id, parseFloat(targetBalance));
      if (response.success) {
        toast.success(t('accounts.adjustSuccess'));
        setShowAdjustModal(false);
        loadAccounts();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || t('accounts.adjustError'));
    } finally {
      setAdjusting(false);
    }
  };

  // Calcula totais agrupados por moeda (incluindo passivos como valor negativo)
  const getTotalsByCurrency = () => {
    const totals = {};
    
    // Contas normais
    accounts
      .filter(acc => acc.is_active && acc.include_in_total)
      .forEach(acc => {
        const currency = acc.currency || 'BRL';
        if (!totals[currency]) {
          totals[currency] = 0;
        }
        totals[currency] += parseFloat(acc.current_balance || 0);
      });
    
    // Passivos (como valor negativo - saldo devedor)
    liabilityAccounts
      .filter(acc => acc.is_active && acc.status === 'active')
      .forEach(acc => {
        const currency = acc.currency || 'EUR';
        if (!totals[currency]) {
          totals[currency] = 0;
        }
        // Subtrair o saldo devedor (remaining_balance)
        totals[currency] -= parseFloat(acc.remaining_balance || 0);
      });
    
    return totals;
  };

  // Total de contas ativas (normais + passivas)
  const getTotalActiveAccounts = () => {
    const normalActive = accounts.filter(a => a.is_active).length;
    const liabilityActive = liabilityAccounts.filter(a => a.is_active).length;
    return normalActive + liabilityActive;
  };

  // Total de todas as contas
  const getTotalAccounts = () => {
    return accounts.length + liabilityAccounts.length;
  };

  return (
    <div>
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h2 className="text-white mb-1">
            <i className="bi bi-wallet2 me-2 text-primary"></i>
            {t('nav.accounts')}
          </h2>
          <p className="text-slate-400 mb-0">{t('accounts.title')}</p>
        </div>
        <div className="d-flex gap-2">
          <button 
            className="btn btn-outline-secondary" 
            onClick={handleRecalculateBalances}
            disabled={recalculating}
            title={t('accounts.recalculateBalances')}
          >
            {recalculating ? (
              <span className="spinner-border spinner-border-sm me-2" role="status"></span>
            ) : (
              <i className="bi bi-arrow-repeat me-2"></i>
            )}
            {t('accounts.recalculate')}
          </button>
          <button className="btn btn-primary" onClick={() => handleOpenModal()}>
            <i className="bi bi-plus-lg me-2"></i>
            {t('accounts.newAccount')}
          </button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="row mb-4">
        {/* Total por Moeda */}
        <div className="col-md-6">
          <div className="card border-0 h-100" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <div className="d-flex align-items-start">
                <div className="rounded-circle bg-primary bg-opacity-25 p-3 me-3">
                  <i className="bi bi-wallet2 text-primary fs-4"></i>
                </div>
                <div className="flex-grow-1">
                  <p className="text-slate-400 mb-2 small">{t('dashboard.totalBalance')}</p>
                  {Object.keys(getTotalsByCurrency()).length > 0 ? (
                    <div className="d-flex flex-wrap gap-3">
                      {Object.entries(getTotalsByCurrency()).map(([currency, total]) => (
                        <div key={currency} className="text-center">
                          <h4 className={`mb-0 ${total >= 0 ? 'text-success' : 'text-danger'}`}>
                            {formatCurrency(total, currency)}
                          </h4>
                          <small className="text-slate-500">{currency}</small>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <h4 className="mb-0 text-slate-500">-</h4>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
        
        {/* Contas Ativas e Total */}
        <div className="col-md-3">
          <div className="card border-0 h-100" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <div className="d-flex align-items-center">
                <div className="rounded-circle bg-success bg-opacity-25 p-3 me-3">
                  <i className="bi bi-check-circle text-success fs-4"></i>
                </div>
                <div>
                  <p className="text-slate-400 mb-0 small">{t('common.active')}</p>
                  <h3 className="mb-0 text-white">
                    {getTotalActiveAccounts()}
                  </h3>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0 h-100" style={{ background: '#1e293b' }}>
            <div className="card-body">
              <div className="d-flex align-items-center">
                <div className="rounded-circle bg-info bg-opacity-25 p-3 me-3">
                  <i className="bi bi-credit-card text-info fs-4"></i>
                </div>
                <div>
                  <p className="text-slate-400 mb-0 small">{t('common.total')}</p>
                  <h3 className="mb-0 text-white">{getTotalAccounts()}</h3>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="card border-0 mb-4" style={{ background: '#1e293b' }}>
        <div className="card-body">
          <div className="row g-3">
            <div className="col-md-4">
              <label className="form-label text-slate-400 small">{t('accounts.filterByType')}</label>
              <select 
                className="form-select bg-dark text-white border-secondary"
                value={filter.type}
                onChange={(e) => setFilter(prev => ({ ...prev, type: e.target.value }))}
              >
                <option value="">{t('common.all')}</option>
                {Object.entries(accountTypes).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
            </div>
            <div className="col-md-4">
              <label className="form-label text-slate-400 small">{t('common.status')}</label>
              <select 
                className="form-select bg-dark text-white border-secondary"
                value={filter.is_active}
                onChange={(e) => setFilter(prev => ({ ...prev, is_active: e.target.value }))}
              >
                <option value="">{t('common.all')}</option>
                <option value="1">{t('common.active')}</option>
                <option value="0">{t('common.inactive')}</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* Accounts List */}
      <div className="card border-0" style={{ background: '#1e293b' }}>
        <div className="card-body p-0">
          {loading ? (
            <div className="text-center py-5">
              <div className="spinner-border text-primary" role="status">
                <span className="visually-hidden">{t('common.loading')}</span>
              </div>
            </div>
          ) : accounts.length === 0 ? (
            <div className="text-center py-5">
              <i className="bi bi-wallet2 display-1 text-slate-600"></i>
              <p className="text-slate-400 mt-3">{t('accounts.noAccounts')}</p>
              <button className="btn btn-primary" onClick={() => handleOpenModal()}>
                <i className="bi bi-plus-lg me-2"></i>
                {t('accounts.newAccount')}
              </button>
            </div>
          ) : (
            <div className="table-responsive">
              <table className="table table-hover mb-0" style={{ '--bs-table-bg': 'transparent', backgroundColor: 'transparent' }}>
                <thead style={{ backgroundColor: 'transparent' }}>
                  <tr style={{ borderBottom: '1px solid #334155', backgroundColor: 'transparent' }}>
                    <th className="text-slate-400 fw-normal py-3 ps-4" style={{ backgroundColor: 'transparent' }}>{t('accounts.accountName')}</th>
                    <th className="text-slate-400 fw-normal py-3" style={{ backgroundColor: 'transparent' }}>{t('common.type')}</th>
                    <th className="text-slate-400 fw-normal py-3" style={{ backgroundColor: 'transparent' }}>{t('accounts.bankName')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-end" style={{ backgroundColor: 'transparent' }}>{t('accounts.currentBalance')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-center" style={{ backgroundColor: 'transparent' }}>{t('common.status')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-end pe-4" style={{ backgroundColor: 'transparent' }}>{t('common.actions')}</th>
                  </tr>
                </thead>
                <tbody style={{ backgroundColor: 'transparent' }}>
                  {accounts.map((account) => (
                    <tr key={account.id} style={{ borderBottom: '1px solid #334155', backgroundColor: 'transparent' }}>
                      <td className="py-3 ps-4" style={{ backgroundColor: 'transparent' }}>
                        <div className="d-flex align-items-center">
                          <div 
                            className="rounded-circle d-flex align-items-center justify-content-center me-3"
                            style={{ 
                              width: '40px', 
                              height: '40px', 
                              backgroundColor: account.color + '25',
                            }}
                          >
                            <i className={`bi ${account.icon}`} style={{ color: account.color }}></i>
                          </div>
                          <div>
                            <div className="text-white fw-medium">{account.name}</div>
                            {account.account_number && (
                              <small className="text-slate-400">Nº {account.account_number}</small>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="py-3" style={{ backgroundColor: 'transparent' }}>
                        <span className="badge" style={{ backgroundColor: '#334155' }}>
                          {accountTypes[account.type] || account.type}
                        </span>
                      </td>
                      <td className="py-3 text-slate-300" style={{ backgroundColor: 'transparent' }}>{account.bank_name || '-'}</td>
                      <td className={`py-3 text-end fw-medium ${parseFloat(account.current_balance) >= 0 ? 'text-success' : 'text-danger'}`} style={{ backgroundColor: 'transparent' }}>
                        {formatCurrency(account.current_balance, account.currency)}
                      </td>
                      <td className="py-3 text-center" style={{ backgroundColor: 'transparent' }}>
                        {account.is_active ? (
                          <span className="badge bg-success bg-opacity-25 text-success">{t('common.active')}</span>
                        ) : (
                          <span className="badge bg-secondary bg-opacity-25 text-secondary">{t('common.inactive')}</span>
                        )}
                      </td>
                      <td className="py-3 text-end pe-4" style={{ backgroundColor: 'transparent' }}>
                        <button 
                          className="btn btn-link text-success p-1 me-1"
                          onClick={() => openAdjustModal(account)}
                          title={t('accounts.adjustBalance')}
                        >
                          <i className="bi bi-sliders"></i>
                        </button>
                        <button 
                          className="btn btn-link text-info p-1 me-1"
                          onClick={() => handleOpenModal(account)}
                          title={t('common.edit')}
                        >
                          <i className="bi bi-pencil"></i>
                        </button>
                        <button 
                          className="btn btn-link text-danger p-1"
                          onClick={() => handleDeleteClick(account)}
                          title={t('common.delete')}
                        >
                          <i className="bi bi-trash"></i>
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* Liability Accounts Section */}
      {liabilityAccounts.length > 0 && (filter.type === '' || filter.type === 'liability') && (
        <div className="card border-0 mt-4" style={{ background: '#1e293b' }}>
          <div className="card-header border-0 d-flex justify-content-between align-items-center" style={{ background: '#1e293b', borderBottom: '1px solid #334155' }}>
            <h5 className="mb-0 text-white">
              <i className="bi bi-file-earmark-text me-2 text-danger"></i>
              {t('liabilities.title')}
            </h5>
            <button 
              className="btn btn-sm btn-outline-light"
              onClick={() => navigate('/liabilities')}
            >
              <i className="bi bi-box-arrow-up-right me-1"></i>
              {t('common.details')}
            </button>
          </div>
          <div className="card-body p-0">
            <div className="table-responsive">
              <table className="table table-hover mb-0" style={{ '--bs-table-bg': 'transparent', backgroundColor: 'transparent' }}>
                <thead style={{ backgroundColor: 'transparent' }}>
                  <tr style={{ borderBottom: '1px solid #334155', backgroundColor: 'transparent' }}>
                    <th className="text-slate-400 fw-normal py-3 ps-4" style={{ backgroundColor: 'transparent' }}>{t('liabilities.contractName')}</th>
                    <th className="text-slate-400 fw-normal py-3" style={{ backgroundColor: 'transparent' }}>{t('liabilities.creditor')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-end" style={{ backgroundColor: 'transparent' }}>{t('liabilities.principal')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-end" style={{ backgroundColor: 'transparent' }}>{t('liabilities.remaining')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-center" style={{ backgroundColor: 'transparent' }}>{t('liabilities.progress')}</th>
                    <th className="text-slate-400 fw-normal py-3 text-center" style={{ backgroundColor: 'transparent' }}>{t('common.status')}</th>
                  </tr>
                </thead>
                <tbody style={{ backgroundColor: 'transparent' }}>
                  {liabilityAccounts.map((liability) => (
                    <tr 
                      key={`liability-${liability.id}`} 
                      style={{ borderBottom: '1px solid #334155', backgroundColor: 'transparent', cursor: 'pointer' }}
                      onClick={() => navigate('/liabilities')}
                    >
                      <td className="py-3 ps-4" style={{ backgroundColor: 'transparent' }}>
                        <div className="d-flex align-items-center">
                          <div 
                            className="rounded-circle d-flex align-items-center justify-content-center me-3"
                            style={{ 
                              width: '40px', 
                              height: '40px', 
                              backgroundColor: (liability.color || '#DC2626') + '25',
                            }}
                          >
                            <i className={`bi ${liability.icon || 'bi-file-earmark-text'}`} style={{ color: liability.color || '#DC2626' }}></i>
                          </div>
                          <div>
                            <div className="text-white fw-medium">{liability.name}</div>
                            {liability.contract_number && (
                              <small className="text-slate-400">Nº {liability.contract_number}</small>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="py-3 text-slate-300" style={{ backgroundColor: 'transparent' }}>{liability.creditor || '-'}</td>
                      <td className="py-3 text-end text-slate-300" style={{ backgroundColor: 'transparent' }}>
                        {formatCurrency(liability.principal_amount, liability.currency)}
                      </td>
                      <td className="py-3 text-end fw-medium text-danger" style={{ backgroundColor: 'transparent' }}>
                        -{formatCurrency(liability.remaining_balance, liability.currency)}
                      </td>
                      <td className="py-3 text-center" style={{ backgroundColor: 'transparent' }}>
                        <div className="d-flex align-items-center justify-content-center gap-2">
                          <div className="progress" style={{ width: '80px', height: '6px', backgroundColor: '#334155' }}>
                            <div 
                              className="progress-bar bg-success" 
                              style={{ width: `${liability.progress_percentage || 0}%` }}
                            ></div>
                          </div>
                          <small className="text-slate-400">{liability.progress_percentage || 0}%</small>
                        </div>
                      </td>
                      <td className="py-3 text-center" style={{ backgroundColor: 'transparent' }}>
                        {liability.status === 'active' ? (
                          <span className="badge bg-primary bg-opacity-25 text-primary">{t('common.active')}</span>
                        ) : liability.status === 'paid_off' ? (
                          <span className="badge bg-success bg-opacity-25 text-success">{t('liabilities.paid')}</span>
                        ) : (
                          <span className="badge bg-secondary bg-opacity-25 text-secondary">{liability.status}</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* Modal de Criar/Editar */}
      {showModal && (
        <div className="modal show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.7)' }}>
          <div className="modal-dialog modal-lg modal-dialog-centered">
            <div className="modal-content" style={{ background: '#1e293b' }}>
              <div className="modal-header border-bottom" style={{ borderColor: '#334155 !important' }}>
                <h5 className="modal-title text-white">
                  <i className={`bi ${selectedAccount ? 'bi-pencil' : 'bi-plus-circle'} me-2`}></i>
                  {selectedAccount ? t('accounts.editAccount') : t('accounts.newAccount')}
                </h5>
                <button type="button" className="btn-close btn-close-white" onClick={handleCloseModal}></button>
              </div>
              <form onSubmit={handleSubmit}>
                <div className="modal-body">
                  <div className="row g-3">
                    {/* Nome */}
                    <div className="col-md-8">
                      <label className="form-label text-slate-300">{t('accounts.accountName')} *</label>
                      <input
                        type="text"
                        className="form-control bg-dark text-white border-secondary"
                        name="name"
                        value={formData.name}
                        onChange={handleChange}
                        placeholder="Ex: Conta Principal, Cartão Nubank..."
                        required
                      />
                    </div>

                    {/* Tipo */}
                    <div className="col-md-4">
                      <label className="form-label text-slate-300">{t('common.type')} *</label>
                      <select
                        className="form-select bg-dark text-white border-secondary"
                        name="type"
                        value={formData.type}
                        onChange={handleChange}
                        required
                      >
                        {Object.entries(accountTypes).map(([key, label]) => (
                          <option key={key} value={key}>{label}</option>
                        ))}
                      </select>
                    </div>

                    {/* Banco */}
                    <div className="col-md-6">
                      <label className="form-label text-slate-300">{t('accounts.bankName')}</label>
                      <input
                        type="text"
                        className="form-control bg-dark text-white border-secondary"
                        name="bank_name"
                        value={formData.bank_name}
                        onChange={handleChange}
                        placeholder="Ex: Banco do Brasil, Nubank..."
                      />
                    </div>

                    {/* Número da Conta */}
                    <div className="col-md-6">
                      <label className="form-label text-slate-300">{t('accounts.accountNumber')}</label>
                      <input
                        type="text"
                        className="form-control bg-dark text-white border-secondary"
                        name="account_number"
                        value={formData.account_number}
                        onChange={handleChange}
                        placeholder="Ex: 12345-6"
                      />
                    </div>

                    {/* Saldo Inicial */}
                    <div className="col-md-4">
                      <label className="form-label text-slate-300">{t('accounts.initialBalance')}</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark text-white border-secondary"
                        name="initial_balance"
                        value={formData.initial_balance}
                        onChange={handleChange}
                      />
                    </div>

                    {/* Limite de Crédito (para cartões) */}
                    {(formData.type === 'credit_card' || formData.type === 'liability') && (
                      <div className="col-md-4">
                        <label className="form-label text-slate-300">{t('accounts.creditLimit')}</label>
                        <input
                          type="number"
                          step="0.01"
                          className="form-control bg-dark text-white border-secondary"
                          name="credit_limit"
                          value={formData.credit_limit}
                          onChange={handleChange}
                        />
                      </div>
                    )}

                    {/* Moeda */}
                    <div className="col-md-4">
                      <label className="form-label text-slate-300">{t('accounts.currency')}</label>
                      <CurrencySelector
                        value={formData.currency}
                        onChange={(currency) => setFormData(prev => ({ ...prev, currency }))}
                      />
                    </div>

                    {/* Cor */}
                    <div className="col-md-3">
                      <label className="form-label text-slate-300">{t('common.color')}</label>
                      <input
                        type="color"
                        className="form-control form-control-color bg-dark border-secondary w-100"
                        name="color"
                        value={formData.color}
                        onChange={handleChange}
                      />
                    </div>

                    {/* Ícone */}
                    <div className="col-md-5">
                      <label className="form-label text-slate-300">{t('common.icon')}</label>
                      <IconSelector
                        value={formData.icon}
                        onChange={(icon) => setFormData(prev => ({ ...prev, icon }))}
                        type="account"
                      />
                    </div>

                    {/* Descrição */}
                    <div className="col-12">
                      <label className="form-label text-slate-300">{t('common.description')}</label>
                      <textarea
                        className="form-control bg-dark text-white border-secondary"
                        name="description"
                        value={formData.description}
                        onChange={handleChange}
                        rows="2"
                        placeholder={t('accounts.descriptionPlaceholder')}
                      ></textarea>
                    </div>

                    {/* Checkboxes */}
                    <div className="col-md-6">
                      <div className="form-check">
                        <input
                          type="checkbox"
                          className="form-check-input"
                          id="is_active"
                          name="is_active"
                          checked={formData.is_active}
                          onChange={handleChange}
                        />
                        <label className="form-check-label text-slate-300" htmlFor="is_active">
                          {t('common.active')}
                        </label>
                      </div>
                    </div>
                    <div className="col-md-6">
                      <div className="form-check">
                        <input
                          type="checkbox"
                          className="form-check-input"
                          id="include_in_total"
                          name="include_in_total"
                          checked={formData.include_in_total}
                          onChange={handleChange}
                        />
                        <label className="form-check-label text-slate-300" htmlFor="include_in_total">
                          {t('accounts.includeInTotal')}
                        </label>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="modal-footer border-top" style={{ borderColor: '#334155 !important' }}>
                  <button type="button" className="btn btn-outline-light" onClick={handleCloseModal}>
                    {t('common.cancel')}
                  </button>
                  <button type="submit" className="btn btn-primary" disabled={saving}>
                    {saving ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2"></span>
                        {t('common.loading')}
                      </>
                    ) : (
                      <>
                        <i className="bi bi-check-lg me-2"></i>
                        {selectedAccount ? t('common.save') : t('common.create')}
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Modal de Ajuste de Saldo */}
      {showAdjustModal && adjustAccount && (
        <div className="modal show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content" style={{ background: '#1e293b', border: '1px solid #334155' }}>
              <div className="modal-header border-0">
                <h5 className="modal-title text-white">
                  <i className="bi bi-sliders me-2 text-success"></i>
                  {t('accounts.adjustBalance')}
                </h5>
                <button 
                  type="button" 
                  className="btn-close btn-close-white" 
                  onClick={() => setShowAdjustModal(false)}
                ></button>
              </div>
              <div className="modal-body">
                <div className="alert alert-info bg-info bg-opacity-10 border-info">
                  <i className="bi bi-info-circle me-2"></i>
                  {t('accounts.adjustInfo')}
                </div>
                <div className="mb-3">
                  <label className="form-label text-white">{t('accounts.accountName')}</label>
                  <input 
                    type="text" 
                    className="form-control bg-dark text-white border-secondary" 
                    value={adjustAccount.name} 
                    disabled 
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label text-white">{t('accounts.currentBalance')}</label>
                  <input 
                    type="text" 
                    className="form-control bg-dark text-white border-secondary" 
                    value={formatCurrency(adjustAccount.current_balance, adjustAccount.currency)} 
                    disabled 
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label text-white">
                    {t('accounts.targetBalance')} <span className="text-danger">*</span>
                  </label>
                  <input 
                    type="number" 
                    step="0.01"
                    className="form-control bg-dark text-white border-secondary" 
                    value={targetBalance}
                    onChange={(e) => setTargetBalance(e.target.value)}
                    placeholder={t('accounts.targetBalancePlaceholder')}
                  />
                  <small className="text-muted">
                    {t('accounts.targetBalanceHelp')}
                  </small>
                </div>
              </div>
              <div className="modal-footer border-0">
                <button 
                  type="button" 
                  className="btn btn-secondary" 
                  onClick={() => setShowAdjustModal(false)}
                >
                  {t('common.cancel')}
                </button>
                <button 
                  type="button" 
                  className="btn btn-success"
                  onClick={handleAdjustBalance}
                  disabled={adjusting || targetBalance === ''}
                >
                  {adjusting ? (
                    <>
                      <span className="spinner-border spinner-border-sm me-2"></span>
                      {t('common.loading')}
                    </>
                  ) : (
                    <>
                      <i className="bi bi-check-lg me-2"></i>
                      {t('accounts.adjust')}
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Modal de Confirmação de Exclusão */}
      <ConfirmModal
        show={showDeleteModal}
        onHide={() => setShowDeleteModal(false)}
        onConfirm={handleDeleteConfirm}
        title={t('accounts.deleteAccount')}
        message={t('accounts.deleteConfirm')}
        confirmText={t('common.delete')}
        loading={saving}
      />
    </div>
  );
};

export default Accounts;
