import { useState, useEffect } from 'react';
import type { User } from '../../types/User';
import { userService, type CreateUserDto } from '../../services/userService';
import Modal from '../../components/Modal';
import { Plus, Edit, Trash2, Shield, User as UserIcon } from 'lucide-react';

export default function UserManager() {
  const [users, setUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  const [formData, setFormData] = useState({
    username: '',
    password: '',
    role: 'Usuario',
    email: ''
  });

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

  const loadUsers = async () => {
    setIsLoading(true);
    try {
      const data = await userService.getAll();
      setUsers(data);
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingId(null);
    setFormData({ username: '', password: '', role: 'Usuario', email: '' });
    setIsModalOpen(true);
  };

  const handleEdit = (user: User) => {
    setEditingId(user.id);
    setFormData({
      username: user.username,
      password: '', // Password vacío al editar
      role: user.role,
      email: user.email || ''
    });
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Eliminar usuario?')) return;
    try {
      await userService.delete(id);
      loadUsers();
    } catch {
      alert('Error eliminando');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      // Validar password obligatorio al crear
      if (!editingId && !formData.password) {
        alert("La contraseña es obligatoria para nuevos usuarios");
        return;
      }

      const payload: CreateUserDto = {
        username: formData.username,
        role: formData.role,
        email: formData.email,
        password: formData.password || undefined // Enviar undefined si está vacío en edit
      };

      if (editingId) {
        await userService.update(editingId, payload);
      } else {
        // En create, password es string (ya validado arriba)
        await userService.create(payload as CreateUserDto);
      }
      setIsModalOpen(false);
      loadUsers();
    } catch {
      alert('Error procesando usuario');
    }
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold text-gray-800">Gestión de Usuarios</h2>
        <button
          onClick={handleCreate}
          className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition"
        >
          <Plus size={20} />
          <span>Nuevo Usuario</span>
        </button>
      </div>

      <div className="bg-white rounded shadow cursor-default">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="p-4 font-semibold text-gray-600">Usuario</th>
              <th className="p-4 font-semibold text-gray-600">Rol</th>
              <th className="p-4 font-semibold text-gray-600">Email</th>
              <th className="p-4 font-semibold text-gray-600">Alta</th>
              <th className="p-4 font-semibold text-gray-600 text-right">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {users.map(user => (
              <tr key={user.id} className="border-b border-gray-100 hover:bg-gray-50">
                <td className="p-4 flex items-center gap-2">
                  <div className="bg-blue-100 p-1.5 rounded-full text-blue-600">
                    <UserIcon size={16} />
                  </div>
                  <span className="font-medium">{user.username}</span>
                </td>
                <td className="p-4">
                  <span className="inline-flex items-center gap-1 bg-gray-100 px-2 py-1 rounded text-sm">
                    <Shield size={12} className="text-gray-500" />
                    {user.role}
                  </span>
                </td>
                <td className="p-4 text-gray-600">{user.email || '-'}</td>
                <td className="p-4 text-gray-500 text-sm">
                  {new Date(user.createdAt).toLocaleDateString()}
                </td>
                <td className="p-4 text-right">
                  <button onClick={() => handleEdit(user)} className="text-blue-600 hover:bg-blue-50 p-2 rounded mr-1">
                    <Edit size={18} />
                  </button>
                  <button onClick={() => handleDelete(user.id)} className="text-red-600 hover:bg-red-50 p-2 rounded">
                    <Trash2 size={18} />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {users.length === 0 && !isLoading && (
          <div className="p-8 text-center text-gray-500">No hay usuarios registrados.</div>
        )}
      </div>

      <Modal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={editingId ? 'Editar Usuario' : 'Nuevo Usuario'}
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700">Usuario</label>
            <input
              type="text"
              required
              value={formData.username}
              onChange={(e) => setFormData({ ...formData, username: e.target.value })}
              className="w-full border p-2 rounded mt-1"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">
              {editingId ? 'Nueva Contraseña (Dejar vacío para no cambiar)' : 'Contraseña'}
            </label>
            <input
              type="password"
              required={!editingId}
              value={formData.password}
              onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              className="w-full border p-2 rounded mt-1"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Rol</label>
            <select
              value={formData.role}
              onChange={(e) => setFormData({ ...formData, role: e.target.value })}
              className="w-full border p-2 rounded mt-1"
            >
              <option value="Admin">Admin</option>
              <option value="Cajero">Cajero</option>
              <option value="Usuario">Usuario</option>
              <option value="Moderador">Moderador</option>
              <option value="Diagramador">Diagramador</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Email</label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              className="w-full border p-2 rounded mt-1"
            />
          </div>
          <div className="flex justify-end gap-2 pt-4">
            <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 hover:bg-gray-100 rounded">Cancelar</button>
            <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Guardar</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
