import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from '../components/Toast';
import { preferencesService } from '../services/api';

export default function Preferences() {
  const { t, i18n } = useTranslation();
  const { showToast } = useToast();
  
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testingSending, setTestingSending] = useState(false);
  const [preferences, setPreferences] = useState({
    notify_due_payments: false,
    notify_due_payments_time: '20:00',
    notify_due_payments_email: '',
    language: 'pt-BR',
    timezone: 'Europe/Madrid',
    currency: 'EUR',
  });
  const [userEmail, setUserEmail] = useState('');

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

  const loadPreferences = async () => {
    try {
      setLoading(true);
      const response = await preferencesService.get();
      if (response.success) {
        setPreferences({
          notify_due_payments: response.data.notify_due_payments,
          notify_due_payments_time: response.data.notify_due_payments_time || '20:00',
          notify_due_payments_email: response.data.notify_due_payments_email || '',
          language: response.data.language || 'pt-BR',
          timezone: response.data.timezone || 'Europe/Madrid',
          currency: response.data.currency || 'EUR',
        });
        setUserEmail(response.data.user_email);
      }
    } catch (error) {
      console.error('Error loading preferences:', error);
      showToast(t('preferences.loadError'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      const response = await preferencesService.update(preferences);
      if (response.success) {
        showToast(t('preferences.saveSuccess'), 'success');
      }
    } catch (error) {
      console.error('Error saving preferences:', error);
      showToast(t('preferences.saveError'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleTestNotification = async () => {
    try {
      setTestingSending(true);
      const response = await preferencesService.testNotification();
      if (response.success) {
        showToast(t('preferences.testSent'), 'success');
      }
    } catch (error) {
      console.error('Error sending test notification:', error);
      showToast(t('preferences.testError'), 'error');
    } finally {
      setTestingSending(false);
    }
  };

  const handleChange = (field, value) => {
    setPreferences(prev => ({
      ...prev,
      [field]: value,
    }));
  };

  if (loading) {
    return (
      <div className="container-fluid py-4">
        <div className="d-flex justify-content-center align-items-center" style={{ minHeight: '400px' }}>
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">{t('common.loading')}</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container-fluid py-4">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h1 className="h3 text-white mb-1">
            <i className="bi bi-gear me-2"></i>
            {t('preferences.title')}
          </h1>
          <p className="text-slate-400 mb-0">{t('preferences.subtitle')}</p>
        </div>
        <button
          className="btn btn-primary"
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? (
            <>
              <span className="spinner-border spinner-border-sm me-2" role="status"></span>
              {t('common.saving')}
            </>
          ) : (
            <>
              <i className="bi bi-check-lg me-2"></i>
              {t('common.save')}
            </>
          )}
        </button>
      </div>

      <div className="row g-4">
        {/* Notificações de Vencimentos */}
        <div className="col-lg-6">
          <div className="card border-0 h-100" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h5 className="text-white mb-0">
                <i className="bi bi-bell text-warning me-2"></i>
                {t('preferences.duePaymentsNotification.title')}
              </h5>
            </div>
            <div className="card-body">
              <p className="text-slate-400 small mb-4">
                {t('preferences.duePaymentsNotification.description')}
              </p>

              {/* Toggle Ativar/Desativar */}
              <div className="form-check form-switch mb-4">
                <input
                  className="form-check-input"
                  type="checkbox"
                  id="notifyDuePayments"
                  checked={preferences.notify_due_payments}
                  onChange={(e) => handleChange('notify_due_payments', e.target.checked)}
                  style={{ width: '3rem', height: '1.5rem' }}
                />
                <label className="form-check-label text-white ms-2" htmlFor="notifyDuePayments">
                  {preferences.notify_due_payments 
                    ? t('preferences.duePaymentsNotification.enabled')
                    : t('preferences.duePaymentsNotification.disabled')
                  }
                </label>
              </div>

              {/* Configurações quando ativado */}
              {preferences.notify_due_payments && (
                <div className="p-3 rounded" style={{ background: '#1e293b' }}>
                  {/* Horário */}
                  <div className="mb-3">
                    <label className="form-label text-slate-400 small">
                      <i className="bi bi-clock me-1"></i>
                      {t('preferences.duePaymentsNotification.time')}
                    </label>
                    <input
                      type="time"
                      className="form-control bg-dark text-white border-secondary"
                      value={preferences.notify_due_payments_time}
                      onChange={(e) => handleChange('notify_due_payments_time', e.target.value)}
                    />
                    <small className="text-slate-500">
                      {t('preferences.duePaymentsNotification.timeHelp')}
                    </small>
                  </div>

                  {/* Email */}
                  <div className="mb-3">
                    <label className="form-label text-slate-400 small">
                      <i className="bi bi-envelope me-1"></i>
                      {t('preferences.duePaymentsNotification.email')}
                    </label>
                    <input
                      type="email"
                      className="form-control bg-dark text-white border-secondary"
                      placeholder={userEmail}
                      value={preferences.notify_due_payments_email}
                      onChange={(e) => handleChange('notify_due_payments_email', e.target.value)}
                    />
                    <small className="text-slate-500">
                      {t('preferences.duePaymentsNotification.emailHelp', { email: userEmail })}
                    </small>
                  </div>

                  {/* Botão de Teste */}
                  <button
                    className="btn btn-outline-warning btn-sm w-100"
                    onClick={handleTestNotification}
                    disabled={testingSending}
                  >
                    {testingSending ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2" role="status"></span>
                        {t('preferences.duePaymentsNotification.sending')}
                      </>
                    ) : (
                      <>
                        <i className="bi bi-send me-2"></i>
                        {t('preferences.duePaymentsNotification.testButton')}
                      </>
                    )}
                  </button>
                </div>
              )}

              {/* Info Box */}
              <div className="alert alert-info mt-4 mb-0" style={{ background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)' }}>
                <h6 className="text-info mb-2">
                  <i className="bi bi-info-circle me-2"></i>
                  {t('preferences.duePaymentsNotification.infoTitle')}
                </h6>
                <ul className="mb-0 small text-slate-300" style={{ paddingLeft: '1.2rem' }}>
                  <li>{t('preferences.duePaymentsNotification.info1')}</li>
                  <li>{t('preferences.duePaymentsNotification.info2')}</li>
                  <li>{t('preferences.duePaymentsNotification.info3')}</li>
                  <li>{t('preferences.duePaymentsNotification.info4')}</li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        {/* Outras Preferências */}
        <div className="col-lg-6">
          <div className="card border-0 h-100" style={{ background: '#0f172a' }}>
            <div className="card-header border-0 bg-transparent">
              <h5 className="text-white mb-0">
                <i className="bi bi-sliders text-primary me-2"></i>
                {t('preferences.general.title')}
              </h5>
            </div>
            <div className="card-body">
              {/* Idioma */}
              <div className="mb-4">
                <label className="form-label text-slate-400 small">
                  <i className="bi bi-translate me-1"></i>
                  {t('preferences.general.language')}
                </label>
                <select
                  className="form-select bg-dark text-white border-secondary"
                  value={preferences.language}
                  onChange={(e) => {
                    handleChange('language', e.target.value);
                    i18n.changeLanguage(e.target.value);
                  }}
                >
                  <option value="pt-BR">🇧🇷 Português (Brasil)</option>
                  <option value="en">🇺🇸 English</option>
                  <option value="es">🇪🇸 Español</option>
                </select>
              </div>

              {/* Moeda */}
              <div className="mb-4">
                <label className="form-label text-slate-400 small">
                  <i className="bi bi-currency-exchange me-1"></i>
                  {t('preferences.general.currency')}
                </label>
                <select
                  className="form-select bg-dark text-white border-secondary"
                  value={preferences.currency}
                  onChange={(e) => handleChange('currency', e.target.value)}
                >
                  <option value="EUR">€ Euro (EUR)</option>
                  <option value="USD">$ US Dollar (USD)</option>
                  <option value="BRL">R$ Real (BRL)</option>
                  <option value="GBP">£ Pound (GBP)</option>
                </select>
              </div>

              {/* Fuso Horário */}
              <div className="mb-4">
                <label className="form-label text-slate-400 small">
                  <i className="bi bi-globe me-1"></i>
                  {t('preferences.general.timezone')}
                </label>
                <select
                  className="form-select bg-dark text-white border-secondary"
                  value={preferences.timezone}
                  onChange={(e) => handleChange('timezone', e.target.value)}
                >
                  <option value="Europe/Madrid">Europe/Madrid (CET)</option>
                  <option value="Europe/London">Europe/London (GMT)</option>
                  <option value="America/Sao_Paulo">America/São Paulo (BRT)</option>
                  <option value="America/New_York">America/New York (EST)</option>
                  <option value="America/Los_Angeles">America/Los Angeles (PST)</option>
                  <option value="UTC">UTC</option>
                </select>
              </div>

              {/* Info */}
              <div className="text-slate-500 small mt-4">
                <i className="bi bi-info-circle me-1"></i>
                {t('preferences.general.note')}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
