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

/**
 * Modal para criar recorrência a partir de uma transação existente
 */
const CreateRecurrenceModal = ({ 
  show, 
  onClose, 
  transaction, 
  onSuccess 
}) => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [frequencies, setFrequencies] = useState({});
  
  const [formData, setFormData] = useState({
    frequency: 'monthly',
    name: '',
    description: '',
    frequency_interval: 1,
    day_of_month: null,
    start_date: '',
    end_date: '',
    max_occurrences: '',
  });

  // Carregar frequências disponíveis
  useEffect(() => {
    const loadFrequencies = async () => {
      try {
        const data = await recurringService.getFrequencies();
        setFrequencies(data);
      } catch (err) {
        console.error('Erro ao carregar frequências:', err);
      }
    };
    loadFrequencies();
  }, []);

  // Reset form quando transação muda
  useEffect(() => {
    if (transaction) {
      const date = new Date(transaction.planned_date);
      setFormData({
        frequency: 'monthly',
        name: transaction.description || '',
        description: '',
        frequency_interval: 1,
        day_of_month: date.getDate(),
        start_date: transaction.planned_date?.split('T')[0] || '',
        end_date: '',
        max_occurrences: '',
      });
    }
  }, [transaction]);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const payload = {
        transaction_id: transaction.id,
        frequency: formData.frequency,
        name: formData.name || undefined,
        description: formData.description || undefined,
        frequency_interval: formData.frequency_interval || 1,
        day_of_month: formData.day_of_month || undefined,
        start_date: formData.start_date || undefined,
        end_date: formData.end_date || undefined,
        max_occurrences: formData.max_occurrences || undefined,
      };

      const result = await recurringService.createFromTransaction(payload);
      
      if (onSuccess) {
        onSuccess(result);
      }
      onClose();
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  };

  if (!transaction) return null;

  const showDayOfMonth = ['monthly', 'bimonthly', 'quarterly', 'semiannual', 'annual'].includes(formData.frequency);

  return (
    <Modal 
      show={show} 
      onClose={onClose} 
      title={t('recurring.createFromTransaction')}
      size="lg"
    >
      <form onSubmit={handleSubmit}>
        <div className="modal-body">
          {error && (
            <div className="alert alert-danger mb-3">
              {error}
            </div>
          )}

          {/* Info da transação */}
          <div className="alert alert-info mb-4">
            <h6 className="mb-2">{t('transactions.transaction')}</h6>
            <div><strong>{transaction.description}</strong></div>
            <div className="small text-muted">
              {new Date(transaction.planned_date).toLocaleDateString()} - 
              {' '}{new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'EUR' }).format(transaction.planned_amount)}
            </div>
          </div>

          <div className="row g-3">
            {/* Nome */}
            <div className="col-12">
              <label className="form-label">{t('recurring.templateName')}</label>
              <input
                type="text"
                className="form-control"
                name="name"
                value={formData.name}
                onChange={handleChange}
                placeholder={transaction.description}
              />
            </div>

            {/* Descrição */}
            <div className="col-12">
              <label className="form-label">{t('recurring.description')}</label>
              <textarea
                className="form-control"
                name="description"
                value={formData.description}
                onChange={handleChange}
                rows={2}
                placeholder={t('common.optional')}
              />
            </div>

            {/* Frequência */}
            <div className="col-md-6">
              <label className="form-label">{t('recurring.frequency')} *</label>
              <select
                className="form-select"
                name="frequency"
                value={formData.frequency}
                onChange={handleChange}
                required
              >
                {Object.entries(frequencies).map(([key, label]) => (
                  <option key={key} value={key}>
                    {t(`recurring.frequencies.${key}`, label)}
                  </option>
                ))}
              </select>
            </div>

            {/* Intervalo */}
            <div className="col-md-6">
              <label className="form-label">{t('recurring.frequencyInterval')}</label>
              <input
                type="number"
                className="form-control"
                name="frequency_interval"
                value={formData.frequency_interval}
                onChange={handleChange}
                min={1}
                max={12}
              />
              <small className="text-muted">
                {formData.frequency_interval > 1 && `A cada ${formData.frequency_interval} períodos`}
              </small>
            </div>

            {/* Dia do Mês */}
            {showDayOfMonth && (
              <div className="col-md-6">
                <label className="form-label">{t('recurring.dayOfMonth')}</label>
                <input
                  type="number"
                  className="form-control"
                  name="day_of_month"
                  value={formData.day_of_month || ''}
                  onChange={handleChange}
                  min={1}
                  max={31}
                />
                <small className="text-muted">
                  {t('recurring.shortMonthInfo')}
                </small>
              </div>
            )}

            {/* Máximo de Parcelas */}
            <div className="col-md-6">
              <label className="form-label">{t('recurring.maxOccurrences')}</label>
              <input
                type="number"
                className="form-control"
                name="max_occurrences"
                value={formData.max_occurrences}
                onChange={handleChange}
                min={1}
                max={999}
                placeholder={t('recurring.noLimit')}
              />
            </div>

            {/* Data de Início */}
            <div className="col-md-6">
              <label className="form-label">{t('recurring.startDate')} *</label>
              <input
                type="date"
                className="form-control"
                name="start_date"
                value={formData.start_date}
                onChange={handleChange}
                required
              />
              <small className="text-muted">
                {t('recurring.startDateHint')}
              </small>
            </div>

            {/* Data Final */}
            <div className="col-md-6">
              <label className="form-label">{t('recurring.endDate')}</label>
              <input
                type="date"
                className="form-control"
                name="end_date"
                value={formData.end_date}
                onChange={handleChange}
              />
              <small className="text-muted">
                {t('common.optional')}
              </small>
            </div>
          </div>
        </div>

        <div className="modal-footer">
          <button 
            type="button" 
            className="btn btn-secondary" 
            onClick={onClose}
            disabled={loading}
          >
            {t('common.cancel')}
          </button>
          <button 
            type="submit" 
            className="btn btn-primary"
            disabled={loading}
          >
            {loading ? (
              <>
                <span className="spinner-border spinner-border-sm me-2" />
                {t('common.processing')}
              </>
            ) : (
              <>
                <i className="bi bi-arrow-repeat me-2" />
                {t('recurring.createFromTransaction')}
              </>
            )}
          </button>
        </div>
      </form>
    </Modal>
  );
};

export default CreateRecurrenceModal;
