import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import Modal from '../components/Modal';
import Toast from '../components/Toast';
import { recurringService, accountService, categoryService } from '../services/api';

const RecurringTransactions = () => {
  const { t } = useTranslation();
  
  // State
  const [templates, setTemplates] = useState([]);
  const [pendingInstances, setPendingInstances] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [toast, setToast] = useState({ show: false, message: '', type: 'success' });
  
  // Filters
  const [filters, setFilters] = useState({
    is_active: '',
    type: '',
    frequency: '',
  });
  
  // Modals
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [selectedInstance, setSelectedInstance] = useState(null);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [showPayModal, setShowPayModal] = useState(false);
  const [showReconcileModal, setShowReconcileModal] = useState(false);
  const [showEditTemplateModal, setShowEditTemplateModal] = useState(false);
  const [showEditInstanceModal, setShowEditInstanceModal] = useState(false);
  const [showDeleteTemplateModal, setShowDeleteTemplateModal] = useState(false);
  const [showSkipInstanceModal, setShowSkipInstanceModal] = useState(false);
  const [showCancelInstanceModal, setShowCancelInstanceModal] = useState(false);
  const [showPauseResumeModal, setShowPauseResumeModal] = useState(false);
  const [showPayConfirmModal, setShowPayConfirmModal] = useState(false);
  const [showReconcileConfirmModal, setShowReconcileConfirmModal] = useState(false);
  const [reconcileTransactionId, setReconcileTransactionId] = useState(null);
  
  // Data for selects
  const [accounts, setAccounts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [frequencies, setFrequencies] = useState({});
  const [candidates, setCandidates] = useState([]);
  
  // Tab active
  const [activeTab, setActiveTab] = useState('templates');

  // Load data
  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [templatesRes, pendingRes, freqRes, accountsRes, categoriesRes] = await Promise.all([
        recurringService.getTemplates(filters),
        recurringService.getPendingInstances({ limit: 50 }),
        recurringService.getFrequencies(),
        accountService.getAll(),
        categoryService.getAll(),
      ]);
      
      setTemplates(templatesRes.data || templatesRes);
      setPendingInstances(pendingRes);
      setFrequencies(freqRes);
      setAccounts(accountsRes.data || accountsRes);
      setCategories(categoriesRes.data || categoriesRes);
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  }, [filters, t]);

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

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

  // Handlers
  const handleEditTemplate = (template) => {
    setSelectedTemplate(template);
    setShowEditTemplateModal(true);
  };

  const handleEditInstance = (instance) => {
    setSelectedInstance(instance);
    setShowEditInstanceModal(true);
  };

  const submitEditTemplate = async (data) => {
    try {
      await recurringService.updateTemplate(selectedTemplate.id, data);
      showToast(t('recurring.updateSuccess'));
      setShowEditTemplateModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const submitEditInstance = async (data) => {
    try {
      await recurringService.updateInstance(selectedInstance.id, data);
      showToast(t('recurring.instanceUpdateSuccess'));
      setShowEditInstanceModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const handlePauseResume = (template) => {
    setSelectedTemplate(template);
    setShowPauseResumeModal(true);
  };

  const submitPauseResume = async () => {
    try {
      if (selectedTemplate.is_active) {
        await recurringService.pauseTemplate(selectedTemplate.id);
        showToast(t('recurring.pauseSuccess'));
      } else {
        await recurringService.resumeTemplate(selectedTemplate.id);
        showToast(t('recurring.resumeSuccess'));
      }
      setShowPauseResumeModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const handleDelete = (template) => {
    setSelectedTemplate(template);
    setShowDeleteTemplateModal(true);
  };

  const submitDeleteTemplate = async () => {
    try {
      await recurringService.deleteTemplate(selectedTemplate.id);
      showToast(t('recurring.deleteSuccess'));
      setShowDeleteTemplateModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const handleViewInstances = async (template) => {
    setSelectedTemplate(template);
    setShowDetailModal(true);
  };

  const handlePayInstance = (instance) => {
    setSelectedInstance(instance);
    setShowPayModal(true);
  };

  const handleReconcileInstance = async (instance) => {
    setSelectedInstance(instance);
    try {
      const candidatesData = await recurringService.findCandidates(instance.id);
      setCandidates(candidatesData);
      setShowReconcileModal(true);
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const handleSkipInstance = (instance) => {
    setSelectedInstance(instance);
    setShowSkipInstanceModal(true);
  };

  const submitSkipInstance = async () => {
    try {
      await recurringService.skipInstance(selectedInstance.id);
      showToast(t('recurring.skipSuccess'));
      setShowSkipInstanceModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const handleCancelInstance = (instance) => {
    setSelectedInstance(instance);
    setShowCancelInstanceModal(true);
  };

  const submitCancelInstance = async () => {
    try {
      await recurringService.cancelInstance(selectedInstance.id);
      showToast(t('recurring.cancelSuccess'));
      setShowCancelInstanceModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const submitDeleteTemplateFromInstance = async () => {
    try {
      const templateId = selectedInstance.template_id || selectedInstance.template?.id;
      await recurringService.deleteTemplate(templateId);
      showToast(t('recurring.deleteSuccess'));
      setShowCancelInstanceModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const submitPay = async (data) => {
    try {
      await recurringService.payInstance(selectedInstance.id, data);
      showToast(t('recurring.paySuccess'));
      setShowPayModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  const submitReconcile = async (transactionId) => {
    try {
      await recurringService.reconcileInstance(selectedInstance.id, transactionId);
      showToast(t('recurring.reconcileSuccess'));
      setShowReconcileModal(false);
      loadData();
    } catch (err) {
      showToast(err.response?.data?.message || t('common.error'), 'danger');
    }
  };

  // Format helpers
  const formatCurrency = (value) => {
    return new Intl.NumberFormat('pt-BR', { 
      style: 'currency', 
      currency: 'EUR' 
    }).format(value);
  };

  const formatDate = (date) => {
    return new Date(date).toLocaleDateString();
  };

  const getStatusBadge = (status) => {
    const badges = {
      pending: 'bg-warning text-dark',
      paid: 'bg-success',
      skipped: 'bg-secondary',
      cancelled: 'bg-danger',
    };
    return badges[status] || 'bg-secondary';
  };

  const getDueDateClass = (instance) => {
    if (instance.status !== 'pending') return '';
    const daysUntil = Math.ceil((new Date(instance.due_date) - new Date()) / (1000 * 60 * 60 * 24));
    if (daysUntil < 0) return 'text-danger fw-bold';
    if (daysUntil <= 3) return 'text-warning';
    return '';
  };

  return (
    <>
      <div className="container-fluid py-4">
        {/* Header */}
        <div className="d-flex justify-content-between align-items-center mb-4">
          <h1 className="h3 mb-0">
            <i className="bi bi-arrow-repeat me-2" />
            {t('recurring.title')}
          </h1>
          <button 
            className="btn btn-outline-light btn-sm"
            onClick={loadData}
            disabled={loading}
          >
            <i className="bi bi-arrow-clockwise me-1" />
            {t('common.refresh')}
          </button>
        </div>

        {error && (
          <div className="alert alert-danger">{error}</div>
        )}

        {/* Tabs */}
        <ul className="nav nav-tabs mb-4">
          <li className="nav-item">
            <button 
              className={`nav-link ${activeTab === 'templates' ? 'active' : ''}`}
              onClick={() => setActiveTab('templates')}
            >
              <i className="bi bi-list-ul me-2" />
              {t('recurring.templates')}
              <span className="badge bg-secondary ms-2">{templates.length}</span>
            </button>
          </li>
          <li className="nav-item">
            <button 
              className={`nav-link ${activeTab === 'pending' ? 'active' : ''}`}
              onClick={() => setActiveTab('pending')}
            >
              <i className="bi bi-clock me-2" />
              {t('recurring.pendingInstances')}
              <span className="badge bg-warning text-dark ms-2">{pendingInstances.length}</span>
            </button>
          </li>
        </ul>

        {/* Templates Tab */}
        {activeTab === 'templates' && (
          <>
            {/* Filters */}
            <div className="card mb-4" style={{ background: '#1e293b' }}>
              <div className="card-body">
                <div className="row g-3">
                  <div className="col-md-3">
                    <label className="form-label">{t('common.status')}</label>
                    <select 
                      className="form-select"
                      value={filters.is_active}
                      onChange={(e) => setFilters(f => ({ ...f, 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 className="col-md-3">
                    <label className="form-label">{t('common.type')}</label>
                    <select 
                      className="form-select"
                      value={filters.type}
                      onChange={(e) => setFilters(f => ({ ...f, type: e.target.value }))}
                    >
                      <option value="">{t('common.all')}</option>
                      <option value="expense">{t('transactions.expense')}</option>
                      <option value="income">{t('transactions.income')}</option>
                    </select>
                  </div>
                  <div className="col-md-3">
                    <label className="form-label">{t('recurring.frequency')}</label>
                    <select 
                      className="form-select"
                      value={filters.frequency}
                      onChange={(e) => setFilters(f => ({ ...f, frequency: e.target.value }))}
                    >
                      <option value="">{t('common.all')}</option>
                      {Object.entries(frequencies).map(([key, label]) => (
                        <option key={key} value={key}>
                          {t(`recurring.frequencies.${key}`, label)}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>
            </div>

            {/* Templates List */}
            {loading ? (
              <div className="text-center py-5">
                <div className="spinner-border text-primary" />
              </div>
            ) : templates.length === 0 ? (
              <div className="text-center py-5 text-muted">
                <i className="bi bi-inbox display-1" />
                <p className="mt-3">{t('recurring.noTemplates')}</p>
              </div>
            ) : (
              <div className="table-responsive">
                <table className="table table-dark table-hover">
                  <thead>
                    <tr>
                      <th>{t('common.name')}</th>
                      <th>{t('recurring.frequency')}</th>
                      <th>{t('common.type')}</th>
                      <th className="text-end">{t('recurring.plannedAmount')}</th>
                      <th className="text-center">{t('recurring.pendingInstances')}</th>
                      <th className="text-center">{t('common.status')}</th>
                      <th className="text-end">{t('common.actions')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {templates.map((template) => (
                      <tr key={template.id}>
                        <td>
                          <div className="fw-bold">{template.name}</div>
                          <small className="text-muted">{template.transaction_description}</small>
                        </td>
                        <td>
                          {t(`recurring.frequencies.${template.frequency}`, template.frequency)}
                          {template.frequency_interval > 1 && (
                            <small className="text-muted ms-1">
                              (x{template.frequency_interval})
                            </small>
                          )}
                        </td>
                        <td>
                          <span className={`badge ${template.type === 'expense' ? 'bg-danger' : 'bg-success'}`}>
                            {t(`transactions.${template.type}`)}
                          </span>
                        </td>
                        <td className="text-end">
                          {formatCurrency(template.planned_amount)}
                        </td>
                        <td className="text-center">
                          <span className="badge bg-warning text-dark">
                            {template.pending_instances_count || 0}
                          </span>
                        </td>
                        <td className="text-center">
                          <span className={`badge ${template.is_active ? 'bg-success' : 'bg-secondary'}`}>
                            {template.is_active ? t('common.active') : t('common.inactive')}
                          </span>
                        </td>
                        <td className="text-end">
                          <div className="btn-group btn-group-sm">
                            <button 
                              className="btn btn-outline-info"
                              onClick={() => handleViewInstances(template)}
                              title={t('recurring.actions.viewInstances')}
                            >
                              <i className="bi bi-eye" />
                            </button>
                            <button 
                              className="btn btn-outline-primary"
                              onClick={() => handleEditTemplate(template)}
                              title={t('common.edit')}
                            >
                              <i className="bi bi-pencil" />
                            </button>
                            <button 
                              className={`btn btn-outline-${template.is_active ? 'warning' : 'success'}`}
                              onClick={() => handlePauseResume(template)}
                              title={template.is_active ? t('recurring.actions.pause') : t('recurring.actions.resume')}
                            >
                              <i className={`bi bi-${template.is_active ? 'pause' : 'play'}`} />
                            </button>
                            <button 
                              className="btn btn-outline-danger"
                              onClick={() => handleDelete(template)}
                              title={t('common.delete')}
                            >
                              <i className="bi bi-trash" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}

        {/* Pending Instances Tab */}
        {activeTab === 'pending' && (
          <>
            {loading ? (
              <div className="text-center py-5">
                <div className="spinner-border text-primary" />
              </div>
            ) : pendingInstances.length === 0 ? (
              <div className="text-center py-5 text-muted">
                <i className="bi bi-check-circle display-1" />
                <p className="mt-3">{t('recurring.noPendingInstances')}</p>
              </div>
            ) : (
              <div className="table-responsive">
                <table className="table table-dark table-hover">
                  <thead>
                    <tr>
                      <th>{t('recurring.templateName')}</th>
                      <th>{t('recurring.occurrenceNumber')}</th>
                      <th>{t('recurring.dueDate')}</th>
                      <th className="text-end">{t('recurring.plannedAmount')}</th>
                      <th className="text-center">{t('common.status')}</th>
                      <th className="text-end">{t('common.actions')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {pendingInstances.map((instance) => (
                      <tr key={instance.id}>
                        <td>
                          <div className="fw-bold">{instance.template?.name}</div>
                          <small className="text-muted">
                            {instance.template?.account?.name}
                          </small>
                        </td>
                        <td>#{instance.occurrence_number}</td>
                        <td className={getDueDateClass(instance)}>
                          {formatDate(instance.due_date)}
                          {instance.status === 'pending' && (
                            <div className="small">
                              {(() => {
                                const days = Math.ceil((new Date(instance.due_date) - new Date()) / (1000 * 60 * 60 * 24));
                                if (days < 0) return <span className="text-danger">{Math.abs(days)} {t('recurring.daysOverdue')}</span>;
                                if (days === 0) return <span className="text-warning">{t('recurring.dueToday')}</span>;
                                return <span className="text-muted">{days} {t('recurring.daysUntilDue')}</span>;
                              })()}
                            </div>
                          )}
                        </td>
                        <td className="text-end">
                          {formatCurrency(instance.planned_amount)}
                        </td>
                        <td className="text-center">
                          <span className={`badge ${getStatusBadge(instance.status)}`}>
                            {t(`recurring.status.${instance.status}`)}
                          </span>
                        </td>
                        <td className="text-end" style={{ minWidth: '200px' }}>
                          <div className="btn-group btn-group-sm flex-wrap">
                            <button 
                              className="btn btn-success btn-sm"
                              onClick={() => handlePayInstance(instance)}
                              title={t('recurring.actions.pay')}
                            >
                              <i className="bi bi-check-lg" />
                            </button>
                            <button 
                              className="btn btn-primary btn-sm"
                              onClick={() => handleReconcileInstance(instance)}
                              title={t('recurring.actions.reconcile')}
                            >
                              <i className="bi bi-link-45deg" />
                            </button>
                            <button 
                              className="btn btn-info btn-sm"
                              onClick={() => handleEditInstance(instance)}
                              title={t('common.edit')}
                            >
                              <i className="bi bi-pencil" />
                            </button>
                            <button 
                              className="btn btn-secondary btn-sm"
                              onClick={() => handleSkipInstance(instance)}
                              title={t('recurring.actions.skip')}
                            >
                              <i className="bi bi-skip-forward" />
                            </button>
                            <button 
                              className="btn btn-danger btn-sm"
                              onClick={() => handleCancelInstance(instance)}
                              title={t('recurring.actions.cancel')}
                            >
                              <i className="bi bi-x-lg" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}

        {/* Detail Modal */}
        <Modal
          show={showDetailModal}
          onClose={() => setShowDetailModal(false)}
          title={selectedTemplate?.name}
          size="lg"
        >
          {selectedTemplate && (
            <div className="modal-body">
              <div className="row mb-4">
                <div className="col-md-6">
                  <p><strong>{t('recurring.frequency')}:</strong> {t(`recurring.frequencies.${selectedTemplate.frequency}`)}</p>
                  <p><strong>{t('recurring.plannedAmount')}:</strong> {formatCurrency(selectedTemplate.planned_amount)}</p>
                  <p><strong>{t('common.type')}:</strong> {t(`transactions.${selectedTemplate.type}`)}</p>
                </div>
                <div className="col-md-6">
                  <p><strong>{t('recurring.startDate')}:</strong> {formatDate(selectedTemplate.start_date)}</p>
                  {selectedTemplate.end_date && (
                    <p><strong>{t('recurring.endDate')}:</strong> {formatDate(selectedTemplate.end_date)}</p>
                  )}
                  {selectedTemplate.max_occurrences && (
                    <p><strong>{t('recurring.maxOccurrences')}:</strong> {selectedTemplate.max_occurrences}</p>
                  )}
                </div>
              </div>

              <h6>{t('recurring.instances')}</h6>
              <div className="table-responsive" style={{ maxHeight: '300px' }}>
                <table className="table table-dark table-sm">
                  <thead className="sticky-top">
                    <tr>
                      <th>#</th>
                      <th>{t('recurring.dueDate')}</th>
                      <th className="text-end">{t('recurring.plannedAmount')}</th>
                      <th className="text-center">{t('common.status')}</th>
                      <th className="text-end">{t('common.actions')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {selectedTemplate.instances?.map((instance) => (
                      <tr key={instance.id}>
                        <td>{instance.occurrence_number}</td>
                        <td>{formatDate(instance.due_date)}</td>
                        <td className="text-end">{formatCurrency(instance.planned_amount)}</td>
                        <td className="text-center">
                          <span className={`badge ${getStatusBadge(instance.status)}`}>
                            {t(`recurring.status.${instance.status}`)}
                          </span>
                        </td>
                        <td className="text-end">
                          {instance.status === 'pending' && (
                            <div className="btn-group btn-group-sm">
                              <button 
                                className="btn btn-outline-success btn-sm"
                                onClick={() => {
                                  setSelectedInstance(instance);
                                  setShowPayModal(true);
                                }}
                                title={t('recurring.actions.pay')}
                              >
                                <i className="bi bi-check-lg" />
                              </button>
                              <button 
                                className="btn btn-outline-info btn-sm"
                                onClick={() => handleEditInstance(instance)}
                                title={t('common.edit')}
                              >
                                <i className="bi bi-pencil" />
                              </button>
                              <button 
                                className="btn btn-outline-danger btn-sm"
                                onClick={() => handleCancelInstance(instance)}
                                title={t('recurring.actions.cancel')}
                              >
                                <i className="bi bi-x-lg" />
                              </button>
                            </div>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </Modal>

        {/* Pay Modal */}
        <PayInstanceModal
          show={showPayModal}
          onClose={() => setShowPayModal(false)}
          instance={selectedInstance}
          onSubmit={submitPay}
          formatCurrency={formatCurrency}
          t={t}
        />

        {/* Reconcile Modal */}
        <ReconcileModal
          show={showReconcileModal}
          onClose={() => setShowReconcileModal(false)}
          instance={selectedInstance}
          candidates={candidates}
          onSubmit={submitReconcile}
          formatCurrency={formatCurrency}
          formatDate={formatDate}
          t={t}
        />

        {/* Edit Template Modal */}
        <EditTemplateModal
          show={showEditTemplateModal}
          onClose={() => setShowEditTemplateModal(false)}
          template={selectedTemplate}
          accounts={accounts}
          categories={categories}
          onSubmit={submitEditTemplate}
          t={t}
        />

        {/* Edit Instance Modal */}
        <EditInstanceModal
          show={showEditInstanceModal}
          onClose={() => setShowEditInstanceModal(false)}
          instance={selectedInstance}
          onSubmit={submitEditInstance}
          formatCurrency={formatCurrency}
          t={t}
        />

        {/* Delete Template Confirmation Modal */}
        <DeleteTemplateConfirmModal
          show={showDeleteTemplateModal}
          onClose={() => setShowDeleteTemplateModal(false)}
          onConfirm={submitDeleteTemplate}
          template={selectedTemplate}
          t={t}
        />

        {/* Skip Instance Confirmation Modal */}
        <SkipInstanceConfirmModal
          show={showSkipInstanceModal}
          onClose={() => setShowSkipInstanceModal(false)}
          onConfirm={submitSkipInstance}
          instance={selectedInstance}
          t={t}
        />

        {/* Cancel Instance Modal with options */}
        <CancelInstanceModal
          show={showCancelInstanceModal}
          onClose={() => setShowCancelInstanceModal(false)}
          instance={selectedInstance}
          onCancelInstance={submitCancelInstance}
          onDeleteTemplate={submitDeleteTemplateFromInstance}
          t={t}
        />

        {/* Pause/Resume Confirmation Modal */}
        <PauseResumeConfirmModal
          show={showPauseResumeModal}
          onClose={() => setShowPauseResumeModal(false)}
          onConfirm={submitPauseResume}
          template={selectedTemplate}
          t={t}
        />

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

// Sub-component: Pay Instance Modal
const PayInstanceModal = ({ show, onClose, instance, onSubmit, formatCurrency, t }) => {
  const [formData, setFormData] = useState({
    amount: '',
    effective_date: new Date().toISOString().split('T')[0],
    notes: '',
  });

  useEffect(() => {
    if (instance) {
      setFormData({
        amount: instance.planned_amount,
        effective_date: new Date().toISOString().split('T')[0],
        notes: '',
      });
    }
  }, [instance]);

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  if (!instance) return null;

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.actions.pay')}>
      <form onSubmit={handleSubmit}>
        <div className="modal-body">
          <div className="alert alert-info mb-3">
            <strong>{instance.template?.name}</strong>
            <div className="small">
              {t('recurring.occurrenceNumber')}{instance.occurrence_number} - 
              {t('recurring.dueDate')}: {new Date(instance.due_date).toLocaleDateString()}
            </div>
          </div>

          <div className="mb-3">
            <label className="form-label">{t('recurring.paidAmount')}</label>
            <input
              type="number"
              className="form-control"
              step="0.01"
              value={formData.amount}
              onChange={(e) => setFormData(f => ({ ...f, amount: e.target.value }))}
              required
            />
            <small className="text-muted">
              {t('recurring.plannedAmount')}: {formatCurrency(instance.planned_amount)}
            </small>
          </div>

          <div className="mb-3">
            <label className="form-label">{t('transactions.effectiveDate')}</label>
            <input
              type="date"
              className="form-control"
              value={formData.effective_date}
              onChange={(e) => setFormData(f => ({ ...f, effective_date: e.target.value }))}
              required
            />
          </div>

          <div className="mb-3">
            <label className="form-label">{t('transactions.notes')}</label>
            <textarea
              className="form-control"
              rows={2}
              value={formData.notes}
              onChange={(e) => setFormData(f => ({ ...f, notes: e.target.value }))}
            />
          </div>
        </div>
        <div className="modal-footer">
          <button type="button" className="btn btn-secondary" onClick={onClose}>
            {t('common.cancel')}
          </button>
          <button type="submit" className="btn btn-success">
            <i className="bi bi-check-lg me-2" />
            {t('recurring.actions.pay')}
          </button>
        </div>
      </form>
    </Modal>
  );
};

// Sub-component: Reconcile Modal
const ReconcileModal = ({ show, onClose, instance, candidates, onSubmit, formatCurrency, formatDate, t }) => {
  if (!instance) return null;

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.reconcileWith')} size="lg">
      <div className="modal-body">
        <div className="alert alert-info mb-3">
          <strong>{instance.template?.name}</strong>
          <div className="small">
            {t('recurring.occurrenceNumber')}{instance.occurrence_number} - 
            {t('recurring.dueDate')}: {formatDate(instance.due_date)} -
            {t('recurring.plannedAmount')}: {formatCurrency(instance.planned_amount)}
          </div>
        </div>

        <h6>{t('recurring.candidateTransactions')}</h6>
        
        {candidates.length === 0 ? (
          <div className="text-center text-muted py-4">
            <i className="bi bi-search display-4" />
            <p className="mt-2">{t('recurring.noCandidates')}</p>
          </div>
        ) : (
          <div className="list-group">
            {candidates.map((transaction) => (
              <button
                key={transaction.id}
                className="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
                style={{ background: '#334155', borderColor: '#475569' }}
                onClick={() => onSubmit(transaction.id)}
              >
                <div>
                  <div className="fw-bold">{transaction.description}</div>
                  <small className="text-muted">
                    {formatDate(transaction.effective_date)} - {transaction.account?.name}
                  </small>
                </div>
                <span className="badge bg-primary">{formatCurrency(transaction.amount)}</span>
              </button>
            ))}
          </div>
        )}
      </div>
      <div className="modal-footer">
        <button type="button" className="btn btn-secondary" onClick={onClose}>
          {t('common.cancel')}
        </button>
      </div>
    </Modal>
  );
};

// Sub-component: Edit Template Modal
const EditTemplateModal = ({ show, onClose, template, accounts, categories, onSubmit, t }) => {
  const [formData, setFormData] = useState({
    name: '',
    amount: '',
    frequency: 'monthly',
    type: 'expense',
    account_id: '',
    category_id: '',
    day_of_month: '',
    notes: ''
  });

  useEffect(() => {
    if (template) {
      setFormData({
        name: template.name || '',
        amount: template.amount || '',
        frequency: template.frequency || 'monthly',
        type: template.type || 'expense',
        account_id: template.account_id || '',
        category_id: template.category_id || '',
        day_of_month: template.day_of_month || '',
        notes: template.notes || ''
      });
    }
  }, [template]);

  if (!template) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.editTemplate')} size="lg">
      <form onSubmit={handleSubmit}>
        <div className="modal-body">
          <div className="row">
            <div className="col-md-6 mb-3">
              <label className="form-label">{t('recurring.name')}</label>
              <input
                type="text"
                className="form-control"
                value={formData.name}
                onChange={(e) => setFormData(f => ({ ...f, name: e.target.value }))}
                required
              />
            </div>
            <div className="col-md-6 mb-3">
              <label className="form-label">{t('transactions.amount')}</label>
              <input
                type="number"
                step="0.01"
                className="form-control"
                value={formData.amount}
                onChange={(e) => setFormData(f => ({ ...f, amount: e.target.value }))}
                required
              />
            </div>
          </div>

          <div className="row">
            <div className="col-md-4 mb-3">
              <label className="form-label">{t('recurring.type')}</label>
              <select
                className="form-select"
                value={formData.type}
                onChange={(e) => setFormData(f => ({ ...f, type: e.target.value }))}
              >
                <option value="expense">{t('transactions.expense')}</option>
                <option value="income">{t('transactions.income')}</option>
              </select>
            </div>
            <div className="col-md-4 mb-3">
              <label className="form-label">{t('recurring.frequency')}</label>
              <select
                className="form-select"
                value={formData.frequency}
                onChange={(e) => setFormData(f => ({ ...f, frequency: e.target.value }))}
              >
                <option value="weekly">{t('recurring.frequencies.weekly')}</option>
                <option value="monthly">{t('recurring.frequencies.monthly')}</option>
                <option value="yearly">{t('recurring.frequencies.yearly')}</option>
              </select>
            </div>
            <div className="col-md-4 mb-3">
              <label className="form-label">{t('recurring.dayOfMonth')}</label>
              <input
                type="number"
                min="1"
                max="31"
                className="form-control"
                value={formData.day_of_month}
                onChange={(e) => setFormData(f => ({ ...f, day_of_month: e.target.value }))}
              />
            </div>
          </div>

          <div className="row">
            <div className="col-md-6 mb-3">
              <label className="form-label">{t('transactions.account')}</label>
              <select
                className="form-select"
                value={formData.account_id}
                onChange={(e) => setFormData(f => ({ ...f, account_id: e.target.value }))}
              >
                <option value="">{t('common.select')}</option>
                {accounts.map(account => (
                  <option key={account.id} value={account.id}>{account.name}</option>
                ))}
              </select>
            </div>
            <div className="col-md-6 mb-3">
              <label className="form-label">{t('transactions.category')}</label>
              <select
                className="form-select"
                value={formData.category_id}
                onChange={(e) => setFormData(f => ({ ...f, category_id: e.target.value }))}
              >
                <option value="">{t('common.select')}</option>
                {categories.map(category => (
                  <option key={category.id} value={category.id}>{category.name}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="mb-3">
            <label className="form-label">{t('transactions.notes')}</label>
            <textarea
              className="form-control"
              rows={2}
              value={formData.notes}
              onChange={(e) => setFormData(f => ({ ...f, notes: e.target.value }))}
            />
          </div>
        </div>
        <div className="modal-footer">
          <button type="button" className="btn btn-secondary" onClick={onClose}>
            {t('common.cancel')}
          </button>
          <button type="submit" className="btn btn-primary">
            <i className="bi bi-check-lg me-2" />
            {t('common.save')}
          </button>
        </div>
      </form>
    </Modal>
  );
};

// Sub-component: Edit Instance Modal
const EditInstanceModal = ({ show, onClose, instance, onSubmit, formatCurrency, t }) => {
  const [formData, setFormData] = useState({
    planned_amount: '',
    due_date: '',
    notes: ''
  });

  // Helper para converter data ISO para yyyy-MM-dd
  const formatDateForInput = (dateStr) => {
    if (!dateStr) return '';
    return dateStr.split('T')[0];
  };

  useEffect(() => {
    if (instance) {
      setFormData({
        planned_amount: instance.planned_amount || '',
        due_date: formatDateForInput(instance.due_date),
        notes: instance.notes || ''
      });
    }
  }, [instance]);

  if (!instance) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.editInstance')}>
      <form onSubmit={handleSubmit}>
        <div className="modal-body">
          <div className="alert alert-info mb-3">
            <strong>{instance.template?.name}</strong>
            <div className="small">
              {t('recurring.occurrenceNumber')}{instance.occurrence_number}
            </div>
          </div>

          <div className="mb-3">
            <label className="form-label">{t('recurring.plannedAmount')}</label>
            <input
              type="number"
              step="0.01"
              className="form-control"
              value={formData.planned_amount}
              onChange={(e) => setFormData(f => ({ ...f, planned_amount: e.target.value }))}
              required
            />
          </div>

          <div className="mb-3">
            <label className="form-label">{t('recurring.dueDate')}</label>
            <input
              type="date"
              className="form-control"
              value={formData.due_date}
              onChange={(e) => setFormData(f => ({ ...f, due_date: e.target.value }))}
              required
            />
          </div>

          <div className="mb-3">
            <label className="form-label">{t('transactions.notes')}</label>
            <textarea
              className="form-control"
              rows={2}
              value={formData.notes}
              onChange={(e) => setFormData(f => ({ ...f, notes: e.target.value }))}
            />
          </div>
        </div>
        <div className="modal-footer">
          <button type="button" className="btn btn-secondary" onClick={onClose}>
            {t('common.cancel')}
          </button>
          <button type="submit" className="btn btn-primary">
            <i className="bi bi-check-lg me-2" />
            {t('common.save')}
          </button>
        </div>
      </form>
    </Modal>
  );
};

// Sub-component: Confirm Modal
const ConfirmModal = ({ show, onClose, onConfirm, title, message, details, confirmText, confirmVariant = 'danger', icon, t }) => {
  return (
    <Modal show={show} onClose={onClose} title={title}>
      <div className="modal-body">
        {icon && (
          <div className="text-center mb-3">
            <i className={`bi ${icon} display-4 text-${confirmVariant}`}></i>
          </div>
        )}
        <p className="text-center mb-3">{message}</p>
        {details && (
          <div className="alert alert-secondary">
            {details}
          </div>
        )}
      </div>
      <div className="modal-footer">
        <button type="button" className="btn btn-secondary" onClick={onClose}>
          {t('common.cancel')}
        </button>
        <button type="button" className={`btn btn-${confirmVariant}`} onClick={onConfirm}>
          <i className={`bi ${icon || 'bi-check-lg'} me-2`}></i>
          {confirmText}
        </button>
      </div>
    </Modal>
  );
};

// Sub-component: Pause/Resume Confirm Modal
const PauseResumeConfirmModal = ({ show, onClose, onConfirm, template, t }) => {
  if (!template) return null;

  const isPausing = template.is_active;
  
  return (
    <Modal show={show} onClose={onClose} title={isPausing ? t('recurring.confirmPauseTitle') : t('recurring.confirmResumeTitle')}>
      <div className="modal-body">
        <div className="text-center mb-3">
          <i className={`bi ${isPausing ? 'bi-pause-circle' : 'bi-play-circle'} display-4 text-${isPausing ? 'warning' : 'success'}`}></i>
        </div>
        
        <div className="alert alert-info mb-3">
          <strong>{template.name}</strong>
          <div className="small">
            {t(`recurring.frequencies.${template.frequency}`)} - {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'EUR' }).format(template.planned_amount)}
          </div>
        </div>

        {isPausing ? (
          <div className="alert alert-warning">
            <i className="bi bi-exclamation-triangle me-2"></i>
            <strong>{t('recurring.pauseWarningTitle')}</strong>
            <ul className="mb-0 mt-2 ps-3">
              <li>{t('recurring.pauseWarning1')}</li>
              <li>{t('recurring.pauseWarning2')}</li>
              <li>{t('recurring.pauseWarning3')}</li>
            </ul>
          </div>
        ) : (
          <div className="alert alert-success">
            <i className="bi bi-info-circle me-2"></i>
            <strong>{t('recurring.resumeInfoTitle')}</strong>
            <ul className="mb-0 mt-2 ps-3">
              <li>{t('recurring.resumeInfo1')}</li>
              <li>{t('recurring.resumeInfo2')}</li>
            </ul>
          </div>
        )}
      </div>
      <div className="modal-footer">
        <button type="button" className="btn btn-secondary" onClick={onClose}>
          {t('common.cancel')}
        </button>
        <button 
          type="button" 
          className={`btn btn-${isPausing ? 'warning' : 'success'}`} 
          onClick={onConfirm}
        >
          <i className={`bi ${isPausing ? 'bi-pause' : 'bi-play'} me-2`}></i>
          {isPausing ? t('recurring.actions.pause') : t('recurring.actions.resume')}
        </button>
      </div>
    </Modal>
  );
};

// Sub-component: Cancel Instance Modal with option to delete all
const CancelInstanceModal = ({ show, onClose, instance, onCancelInstance, onDeleteTemplate, t }) => {
  if (!instance) return null;

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.cancelOptions')}>
      <div className="modal-body">
        <div className="alert alert-info mb-3">
          <strong>{instance.template?.name}</strong>
          <div className="small">
            {t('recurring.occurrenceNumber')}{instance.occurrence_number}
          </div>
        </div>
        
        <p className="mb-4">{t('recurring.whatToDo')}</p>
        
        <div className="d-grid gap-3">
          <button 
            className="btn btn-warning btn-lg text-start"
            onClick={onCancelInstance}
          >
            <i className="bi bi-x-circle me-2" />
            <div>
              <strong>{t('recurring.cancelThisOnly')}</strong>
              <div className="small opacity-75">{t('recurring.cancelThisOnlyDesc')}</div>
            </div>
          </button>
          
          <button 
            className="btn btn-danger btn-lg text-start"
            onClick={onDeleteTemplate}
          >
            <i className="bi bi-trash me-2" />
            <div>
              <strong>{t('recurring.deleteAllRecurrences')}</strong>
              <div className="small opacity-75">{t('recurring.deleteAllRecurrencesDesc')}</div>
            </div>
          </button>
        </div>
      </div>
      <div className="modal-footer">
        <button type="button" className="btn btn-secondary" onClick={onClose}>
          {t('common.cancel')}
        </button>
      </div>
    </Modal>
  );
};

// Sub-component: Delete Template Confirm Modal
const DeleteTemplateConfirmModal = ({ show, onClose, onConfirm, template, t }) => {
  if (!template) return null;

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.deleteTemplate')}>
      <div className="modal-body">
        <div className="text-center mb-3">
          <i className="bi bi-trash display-4 text-danger"></i>
        </div>
        
        <div className="alert alert-info mb-3">
          <strong>{template.name}</strong>
          <div className="small">
            {t(`recurring.frequencies.${template.frequency}`)} - {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'EUR' }).format(template.amount)}
          </div>
        </div>

        <div className="alert alert-danger">
          <i className="bi bi-exclamation-triangle me-2"></i>
          <strong>{t('recurring.deleteWarningTitle')}</strong>
          <ul className="mb-0 mt-2 ps-3">
            <li>{t('recurring.deleteWarning1')}</li>
            <li>{t('recurring.deleteWarning2')}</li>
            <li>{t('recurring.deleteWarning3')}</li>
          </ul>
        </div>
      </div>
      <div className="modal-footer">
        <button type="button" className="btn btn-secondary" onClick={onClose}>
          {t('common.cancel')}
        </button>
        <button 
          type="button" 
          className="btn btn-danger" 
          onClick={onConfirm}
        >
          <i className="bi bi-trash me-2"></i>
          {t('common.delete')}
        </button>
      </div>
    </Modal>
  );
};

// Sub-component: Skip Instance Confirm Modal
const SkipInstanceConfirmModal = ({ show, onClose, onConfirm, instance, t }) => {
  if (!instance) return null;

  return (
    <Modal show={show} onClose={onClose} title={t('recurring.actions.skip')}>
      <div className="modal-body">
        <div className="text-center mb-3">
          <i className="bi bi-skip-forward display-4 text-secondary"></i>
        </div>
        
        <div className="alert alert-info mb-3">
          <strong>{instance.template?.name}</strong>
          <div className="small">
            {t('recurring.occurrenceNumber')}{instance.occurrence_number} - 
            {t('recurring.dueDate')}: {new Date(instance.due_date).toLocaleDateString()}
          </div>
          <div className="small">
            {t('recurring.plannedAmount')}: {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'EUR' }).format(instance.planned_amount)}
          </div>
        </div>

        <div className="alert alert-warning">
          <i className="bi bi-info-circle me-2"></i>
          <strong>{t('recurring.skipWarningTitle')}</strong>
          <ul className="mb-0 mt-2 ps-3">
            <li>{t('recurring.skipWarning1')}</li>
            <li>{t('recurring.skipWarning2')}</li>
            <li>{t('recurring.skipWarning3')}</li>
          </ul>
        </div>
      </div>
      <div className="modal-footer">
        <button type="button" className="btn btn-secondary" onClick={onClose}>
          {t('common.cancel')}
        </button>
        <button 
          type="button" 
          className="btn btn-warning" 
          onClick={onConfirm}
        >
          <i className="bi bi-skip-forward me-2"></i>
          {t('recurring.actions.skip')}
        </button>
      </div>
    </Modal>
  );
};

export default RecurringTransactions;
