'use client';

import { useState, useEffect, useCallback } from 'react';
import { Users, Plus, Pencil, Trash2, Activity, Loader2, AlertCircle, CheckCircle, X, Search } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

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

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

type ModalType = 'create' | 'edit' | 'delete' | 'logs' | null;

export default function UsersContent() {
  const [users, setUsers] = useState<UserItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<ModalType>(null);
  const [selectedUser, setSelectedUser] = useState<UserItem | null>(null);
  const [userLogs, setUserLogs] = useState<LogEntry[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [search, setSearch] = useState('');

  // Form state
  const [formEmail, setFormEmail] = useState('');
  const [formName, setFormName] = useState('');
  const [formPassword, setFormPassword] = useState('');
  const [formRole, setFormRole] = useState('operario');
  const [formLoading, setFormLoading] = useState(false);
  const [formMessage, setFormMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const fetchUsers = useCallback(async () => {
    try {
      const res = await fetch('/api/users');
      const data = await res.json();
      if (data?.users) setUsers(data.users ?? []);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const openCreate = () => {
    setFormEmail('');
    setFormName('');
    setFormPassword('');
    setFormRole('operario');
    setFormMessage(null);
    setModal('create');
  };

  const openEdit = (user: UserItem) => {
    setSelectedUser(user);
    setFormEmail(user?.email ?? '');
    setFormName(user?.name ?? '');
    setFormPassword('');
    setFormRole(user?.role ?? 'operario');
    setFormMessage(null);
    setModal('edit');
  };

  const openDelete = (user: UserItem) => {
    setSelectedUser(user);
    setModal('delete');
  };

  const openLogs = async (user: UserItem) => {
    setSelectedUser(user);
    setUserLogs([]);
    setLogsLoading(true);
    setModal('logs');
    try {
      const res = await fetch(`/api/users/${user?.id}/logs`);
      const data = await res.json();
      if (data?.logs) setUserLogs(data.logs ?? []);
    } catch (e) {
      console.error(e);
    } finally {
      setLogsLoading(false);
    }
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormLoading(true);
    setFormMessage(null);
    try {
      const res = await fetch('/api/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: formEmail, password: formPassword, name: formName, role: formRole }),
      });
      const data = await res.json();
      if (data?.success) {
        setFormMessage({ type: 'success', text: 'Usuario creado correctamente' });
        fetchUsers();
        setTimeout(() => setModal(null), 1000);
      } else {
        setFormMessage({ type: 'error', text: data?.error ?? 'Error al crear usuario' });
      }
    } catch {
      setFormMessage({ type: 'error', text: 'Error de conexión' });
    } finally {
      setFormLoading(false);
    }
  };

  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedUser) return;
    setFormLoading(true);
    setFormMessage(null);
    try {
      const body: Record<string, string> = { email: formEmail, name: formName, role: formRole };
      if (formPassword) body.password = formPassword;
      const res = await fetch(`/api/users/${selectedUser.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (data?.success) {
        setFormMessage({ type: 'success', text: 'Usuario actualizado correctamente' });
        fetchUsers();
        setTimeout(() => setModal(null), 1000);
      } else {
        setFormMessage({ type: 'error', text: data?.error ?? 'Error al actualizar' });
      }
    } catch {
      setFormMessage({ type: 'error', text: 'Error de conexión' });
    } finally {
      setFormLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!selectedUser) return;
    setFormLoading(true);
    try {
      const res = await fetch(`/api/users/${selectedUser.id}`, { method: 'DELETE' });
      const data = await res.json();
      if (data?.success) {
        fetchUsers();
        setModal(null);
      } else {
        alert(data?.error ?? 'Error al eliminar');
      }
    } catch {
      alert('Error de conexión');
    } finally {
      setFormLoading(false);
    }
  };

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

  const filteredUsers = (users ?? []).filter((u) => {
    const s = search?.toLowerCase?.() ?? '';
    return (u?.email?.toLowerCase?.() ?? '').includes(s) || (u?.name?.toLowerCase?.() ?? '').includes(s);
  });

  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>
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-[#1a365d]">Gestión de Usuarios</h1>
          <p className="text-gray-500 text-sm">Administra los usuarios del sistema</p>
        </div>
        <button onClick={openCreate} className="inline-flex items-center gap-2 bg-[#1a365d] hover:bg-[#2c5282] text-white px-4 py-2.5 rounded-lg font-medium transition-colors text-sm">
          <Plus className="w-4 h-4" /> Crear usuario
        </button>
      </motion.div>

      {/* Search */}
      <div className="relative mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
        <input type="text" placeholder="Buscar por email o nombre..." value={search} onChange={(e) => setSearch(e.target.value)}
          className="w-full pl-10 pr-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 bg-white" />
      </div>

      {/* Users table */}
      <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
        className="bg-white rounded-lg shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-12"><Loader2 className="w-6 h-6 animate-spin text-gray-400" /></div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="text-left px-4 py-3 font-medium text-gray-600">Email</th>
                  <th className="text-left px-4 py-3 font-medium text-gray-600">Nombre</th>
                  <th className="text-left px-4 py-3 font-medium text-gray-600">Rol</th>
                  <th className="text-left px-4 py-3 font-medium text-gray-600 hidden md:table-cell">Último acceso</th>
                  <th className="text-right px-4 py-3 font-medium text-gray-600">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {filteredUsers?.map((user) => (
                  <tr key={user?.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 text-gray-800">{user?.email}</td>
                    <td className="px-4 py-3 text-gray-800">{user?.name || '-'}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex px-2 py-0.5 text-xs font-medium rounded-full ${user?.role === 'admin' ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'}`}>
                        {user?.role}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 hidden md:table-cell">{formatDate(user?.lastLogin)}</td>
                    <td className="px-4 py-3 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <button onClick={() => openEdit(user)} title="Editar" className="p-1.5 hover:bg-blue-50 rounded-lg text-blue-600 transition"><Pencil className="w-4 h-4" /></button>
                        <button onClick={() => openLogs(user)} title="Ver logs" className="p-1.5 hover:bg-purple-50 rounded-lg text-purple-600 transition"><Activity className="w-4 h-4" /></button>
                        <button onClick={() => openDelete(user)} title="Eliminar" className="p-1.5 hover:bg-red-50 rounded-lg text-red-600 transition"><Trash2 className="w-4 h-4" /></button>
                      </div>
                    </td>
                  </tr>
                ))}
                {(filteredUsers?.length ?? 0) === 0 && (
                  <tr><td colSpan={5} className="px-4 py-8 text-center text-gray-400">No se encontraron usuarios</td></tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </motion.div>

      {/* Modals */}
      <AnimatePresence>
        {modal && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={() => setModal(null)}>
            <motion.div initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.95, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[85vh] overflow-y-auto">

              {/* Create / Edit */}
              {(modal === 'create' || modal === 'edit') && (
                <div className="p-6">
                  <div className="flex items-center justify-between mb-5">
                    <h3 className="text-lg font-semibold text-[#1a365d]">
                      {modal === 'create' ? 'Crear usuario' : 'Editar usuario'}
                    </h3>
                    <button onClick={() => setModal(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5 text-gray-500" /></button>
                  </div>
                  {formMessage && (
                    <div className={`flex items-center gap-2 p-3 rounded-lg text-sm mb-4 ${formMessage.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                      {formMessage.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
                      {formMessage.text}
                    </div>
                  )}
                  <form onSubmit={modal === 'create' ? handleCreate : handleEdit} className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                      <input type="email" value={formEmail} onChange={(e) => setFormEmail(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">Nombre</label>
                      <input type="text" value={formName} onChange={(e) => setFormName(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">
                        Contraseña {modal === 'edit' && <span className="text-gray-400 font-normal">(dejar vacío para mantener)</span>}
                      </label>
                      <input type="password" value={formPassword} onChange={(e) => setFormPassword(e.target.value)}
                        {...(modal === 'create' ? { required: true, 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">Rol</label>
                      <select value={formRole} onChange={(e) => setFormRole(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 bg-white">
                        <option value="operario">Operario</option>
                        <option value="admin">Admin</option>
                      </select>
                    </div>
                    <div className="flex gap-3">
                      <button type="button" onClick={() => setModal(null)} className="flex-1 px-4 py-2.5 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 font-medium transition text-sm">Cancelar</button>
                      <button type="submit" disabled={formLoading}
                        className="flex-1 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 text-sm">
                        {formLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : null}
                        {modal === 'create' ? 'Crear' : 'Guardar'}
                      </button>
                    </div>
                  </form>
                </div>
              )}

              {/* Delete confirm */}
              {modal === 'delete' && (
                <div className="p-6">
                  <div className="flex items-center justify-between mb-5">
                    <h3 className="text-lg font-semibold text-red-600">Eliminar usuario</h3>
                    <button onClick={() => setModal(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5 text-gray-500" /></button>
                  </div>
                  <p className="text-gray-700 mb-6">¿Estás seguro de que quieres eliminar al usuario <strong>{selectedUser?.email}</strong>? Esta acción no se puede deshacer.</p>
                  <div className="flex gap-3">
                    <button onClick={() => setModal(null)} className="flex-1 px-4 py-2.5 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 font-medium transition text-sm">Cancelar</button>
                    <button onClick={handleDelete} disabled={formLoading}
                      className="flex-1 bg-red-600 hover:bg-red-700 text-white py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 disabled:opacity-60 text-sm">
                      {formLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : null}
                      Eliminar
                    </button>
                  </div>
                </div>
              )}

              {/* Logs */}
              {modal === 'logs' && (
                <div className="p-6">
                  <div className="flex items-center justify-between mb-5">
                    <h3 className="text-lg font-semibold text-[#1a365d]">Actividad de {selectedUser?.name || selectedUser?.email}</h3>
                    <button onClick={() => setModal(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5 text-gray-500" /></button>
                  </div>
                  {logsLoading ? (
                    <div className="flex items-center justify-center py-8"><Loader2 className="w-6 h-6 animate-spin text-gray-400" /></div>
                  ) : (userLogs?.length ?? 0) === 0 ? (
                    <p className="text-gray-500 text-sm text-center py-8">No hay registros de actividad</p>
                  ) : (
                    <div className="space-y-2 max-h-96 overflow-y-auto">
                      {userLogs?.map((log) => (
                        <div key={log?.id} className="bg-gray-50 rounded-lg px-4 py-3 text-sm">
                          <div className="flex items-center justify-between">
                            <span className="font-medium text-gray-800">{actionLabels[log?.action] ?? log?.action}</span>
                            <span className="text-gray-400 text-xs">{formatDate(log?.timestamp)}</span>
                          </div>
                          {log?.details ? <p className="text-gray-500 mt-1">{log.details}</p> : null}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
