'use client';

import { useState, useEffect } from 'react';
import { Mail, Loader2, CheckCircle, AlertCircle, Send, Save, Server } from 'lucide-react';
import { motion } from 'framer-motion';

interface SmtpConfig {
  id?: string;
  host: string;
  port: number;
  secure: boolean;
  smtpUser: string;
  fromEmail: string;
  hasPassword?: boolean;
}

export default function SmtpContent() {
  const [config, setConfig] = useState<SmtpConfig>({
    host: '', port: 587, secure: false, smtpUser: '', fromEmail: '',
  });
  const [smtpPass, setSmtpPass] = useState('');
  const [testEmail, setTestEmail] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [testMessage, setTestMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    fetch('/api/smtp')
      .then((r) => r.json())
      .then((d) => {
        if (d?.config) {
          setConfig(d.config);
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      const body: Record<string, unknown> = {
        host: config.host,
        port: config.port,
        secure: config.secure,
        smtpUser: config.smtpUser,
        fromEmail: config.fromEmail,
      };
      if (smtpPass) body.smtpPass = smtpPass;
      const res = await fetch('/api/smtp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (data?.success) {
        setMessage({ type: 'success', text: 'Configuración guardada correctamente' });
        if (data.config) setConfig({ ...config, ...(data.config ?? {}) });
      } else {
        setMessage({ type: 'error', text: data?.error ?? 'Error al guardar' });
      }
    } catch {
      setMessage({ type: 'error', text: 'Error de conexión' });
    } finally {
      setSaving(false);
    }
  };

  const handleTest = async () => {
    setTesting(true);
    setTestMessage(null);
    try {
      const res = await fetch('/api/smtp/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ testEmail }),
      });
      const data = await res.json();
      if (data?.success) {
        setTestMessage({ type: 'success', text: data?.message ?? 'Email enviado' });
      } else {
        setTestMessage({ type: 'error', text: data?.error ?? 'Error al enviar' });
      }
    } catch {
      setTestMessage({ type: 'error', text: 'Error de conexión' });
    } finally {
      setTesting(false);
    }
  };

  if (loading) {
    return <div className="flex items-center justify-center py-20"><Loader2 className="w-6 h-6 animate-spin text-gray-400" /></div>;
  }

  return (
    <div className="space-y-6">
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
        <h1 className="text-2xl font-bold text-[#1a365d] mb-1">Configuración SMTP</h1>
        <p className="text-gray-500">Configura el servidor de email para el envío de notificaciones</p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Config form */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="lg:col-span-2 bg-white rounded-lg shadow-sm p-6">
          <div className="flex items-center gap-3 mb-5">
            <Server className="w-5 h-5 text-[#1a365d]" />
            <h2 className="text-lg font-semibold text-[#1a365d]">Parámetros del servidor</h2>
          </div>

          {message && (
            <div className={`flex items-center gap-2 p-3 rounded-lg text-sm mb-4 ${message.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
              {message.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
              {message.text}
            </div>
          )}

          <form onSubmit={handleSave} className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Host SMTP</label>
                <input type="text" value={config.host} onChange={(e) => setConfig({ ...config, host: e.target.value })} placeholder="smtp.ejemplo.com"
                  className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none transition text-gray-900" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Puerto</label>
                <input type="number" value={config.port} onChange={(e) => setConfig({ ...config, port: Number(e.target.value) || 587 })}
                  className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none transition text-gray-900" />
              </div>
            </div>

            <div className="flex items-center gap-3">
              <label className="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" checked={config.secure} onChange={(e) => setConfig({ ...config, secure: e.target.checked })} className="sr-only peer" />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#3182ce] rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#3182ce]"></div>
              </label>
              <span className="text-sm text-gray-700">Conexión segura (SSL/TLS)</span>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Usuario SMTP</label>
              <input type="text" value={config.smtpUser} onChange={(e) => setConfig({ ...config, smtpUser: e.target.value })} placeholder="usuario@ejemplo.com"
                className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none transition text-gray-900" />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Contraseña SMTP {config.hasPassword && <span className="text-gray-400 font-normal">(guardada - dejar vacío para mantener)</span>}
              </label>
              <input type="password" value={smtpPass} onChange={(e) => setSmtpPass(e.target.value)} placeholder="••••••••"
                className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none transition text-gray-900" />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Email remitente</label>
              <input type="email" value={config.fromEmail} onChange={(e) => setConfig({ ...config, fromEmail: e.target.value })} placeholder="noreply@ejemplo.com"
                className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none transition text-gray-900" />
            </div>

            <button type="submit" disabled={saving}
              className="w-full bg-[#1a365d] hover:bg-[#2c5282] text-white py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 disabled:opacity-60">
              {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              {saving ? 'Guardando...' : 'Guardar configuración'}
            </button>
          </form>
        </motion.div>

        {/* Test panel */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}
          className="bg-white rounded-lg shadow-sm p-6 h-fit">
          <div className="flex items-center gap-3 mb-5">
            <Send className="w-5 h-5 text-[#1a365d]" />
            <h2 className="text-lg font-semibold text-[#1a365d]">Probar envío</h2>
          </div>

          {testMessage && (
            <div className={`flex items-center gap-2 p-3 rounded-lg text-sm mb-4 ${testMessage.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
              {testMessage.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
              {testMessage.text}
            </div>
          )}

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Email de prueba</label>
              <input type="email" value={testEmail} onChange={(e) => setTestEmail(e.target.value)} placeholder="test@ejemplo.com"
                className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none transition text-gray-900" />
            </div>
            <button onClick={handleTest} disabled={testing}
              className="w-full bg-green-600 hover:bg-green-700 text-white py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 disabled:opacity-60">
              {testing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Mail className="w-4 h-4" />}
              {testing ? 'Enviando...' : 'Enviar email de prueba'}
            </button>
          </div>

          <div className="mt-6 bg-gray-50 rounded-lg p-4">
            <h3 className="text-sm font-medium text-gray-700 mb-2">Estado</h3>
            <div className="flex items-center gap-2">
              <div className={`w-2.5 h-2.5 rounded-full ${config.host ? 'bg-green-500' : 'bg-gray-300'}`} />
              <span className="text-sm text-gray-600">{config.host ? 'Configurado' : 'No configurado'}</span>
            </div>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
