'use client';

import { useState, useEffect } from 'react';
import { User, Lock, Loader2, CheckCircle, AlertCircle, Activity } from 'lucide-react';
import { motion } from 'framer-motion';

interface UserProfile {
  id: string;
  email: string;
  name: string;
  role: string;
  createdAt: string;
  lastLogin: string | null;
}

interface LogEntry {
  id: string;
  action: string;
  details: string;
  timestamp: string;
}

export default function ProfileContent() {
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [name, setName] = useState('');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [pwLoading, setPwLoading] = useState(false);
  const [pwMessage, setPwMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    fetch('/api/profile')
      .then((r) => r.json())
      .then((d) => {
        if (d?.user) {
          setProfile(d.user);
          setName(d.user?.name ?? '');
        }
        if (d?.logs) setLogs(d.logs ?? []);
      })
      .catch(console.error);
  }, []);

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    try {
      const res = await fetch('/api/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name }),
      });
      const d = await res.json();
      if (d?.success) {
        setMessage({ type: 'success', text: 'Perfil actualizado correctamente' });
      } else {
        setMessage({ type: 'error', text: d?.error ?? 'Error al actualizar' });
      }
    } catch {
      setMessage({ type: 'error', text: 'Error de conexión' });
    } finally {
      setLoading(false);
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      setPwMessage({ type: 'error', text: 'Las contraseñas no coinciden' });
      return;
    }
    if (newPassword.length < 6) {
      setPwMessage({ type: 'error', text: 'La contraseña debe tener al menos 6 caracteres' });
      return;
    }
    setPwLoading(true);
    setPwMessage(null);
    try {
      const res = await fetch('/api/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      const d = await res.json();
      if (d?.success) {
        setPwMessage({ type: 'success', text: 'Contraseña cambiada correctamente' });
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
      } else {
        setPwMessage({ type: 'error', text: d?.error ?? 'Error al cambiar contraseña' });
      }
    } catch {
      setPwMessage({ type: 'error', text: 'Error de conexión' });
    } finally {
      setPwLoading(false);
    }
  };

  const actionLabels: Record<string, string> = {
    LOGIN_SUCCESS: 'Inicio de sesión',
    LOGIN_FAILED: 'Login fallido',
    PASSWORD_CHANGED: 'Contraseña cambiada',
    PASSWORD_RESET_REQUESTED: 'Recuperación solicitada',
    PASSWORD_RESET_COMPLETED: 'Contraseña restablecida',
    USER_CREATED: 'Usuario creado',
    USER_UPDATED: 'Usuario editado',
    USER_DELETED: 'Usuario eliminado',
    SMTP_CONFIG_UPDATED: 'SMTP actualizado',
  };

  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">Mi Perfil</h1>
        <p className="text-gray-500">Gestiona tu información personal y seguridad</p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Profile info */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="bg-white rounded-lg shadow-sm p-6">
          <div className="flex items-center gap-3 mb-5">
            <User className="w-5 h-5 text-[#1a365d]" />
            <h2 className="text-lg font-semibold text-[#1a365d]">Información personal</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={handleUpdateProfile} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
              <input type="email" value={profile?.email ?? ''} disabled className="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-gray-50 text-gray-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Nombre</label>
              <input type="text" value={name} onChange={(e) => setName(e.target.value)}
                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">Rol</label>
              <input type="text" value={profile?.role ?? ''} disabled className="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-gray-50 text-gray-500 capitalize" />
            </div>
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div className="bg-gray-50 rounded-lg p-3">
                <p className="text-gray-500">Creado</p>
                <p className="font-medium text-gray-800">{formatDate(profile?.createdAt)}</p>
              </div>
              <div className="bg-gray-50 rounded-lg p-3">
                <p className="text-gray-500">Último acceso</p>
                <p className="font-medium text-gray-800">{formatDate(profile?.lastLogin)}</p>
              </div>
            </div>
            <button type="submit" disabled={loading}
              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">
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : null}
              {loading ? 'Guardando...' : 'Guardar cambios'}
            </button>
          </form>
        </motion.div>

        {/* Change password */}
        <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">
          <div className="flex items-center gap-3 mb-5">
            <Lock className="w-5 h-5 text-[#1a365d]" />
            <h2 className="text-lg font-semibold text-[#1a365d]">Cambiar contraseña</h2>
          </div>
          {pwMessage && (
            <div className={`flex items-center gap-2 p-3 rounded-lg text-sm mb-4 ${pwMessage.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
              {pwMessage.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
              {pwMessage.text}
            </div>
          )}
          <form onSubmit={handleChangePassword} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Contraseña actual</label>
              <input type="password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} required
                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">Nueva contraseña</label>
              <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required minLength={6}
                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">Confirmar nueva contraseña</label>
              <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} required minLength={6}
                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={pwLoading}
              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">
              {pwLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : null}
              {pwLoading ? 'Cambiando...' : 'Cambiar contraseña'}
            </button>
          </form>
        </motion.div>
      </div>

      {/* Activity logs */}
      <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}
        className="bg-white rounded-lg shadow-sm p-6">
        <div className="flex items-center gap-3 mb-5">
          <Activity className="w-5 h-5 text-[#1a365d]" />
          <h2 className="text-lg font-semibold text-[#1a365d]">Última actividad</h2>
        </div>
        {(logs?.length ?? 0) === 0 ? (
          <p className="text-gray-500 text-sm">No hay registros de actividad</p>
        ) : (
          <div className="space-y-2">
            {logs?.map((log) => (
              <div key={log?.id} className="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3 text-sm">
                <div>
                  <span className="font-medium text-gray-800">{actionLabels[log?.action] ?? log?.action}</span>
                  {log?.details ? <span className="text-gray-500 ml-2">- {log.details}</span> : null}
                </div>
                <span className="text-gray-400 text-xs whitespace-nowrap ml-4">{formatDate(log?.timestamp)}</span>
              </div>
            ))}
          </div>
        )}
      </motion.div>
    </div>
  );

  function formatDate(d: string | null | undefined) {
    if (!d) return '';
    try { return new Date(d).toLocaleString('es-ES'); } catch { return d; }
  }
}
