'use client';

import React, { useState, useEffect, useMemo } from 'react';
import MainLayout from '@/components/layout/MainLayout';

interface UserItem {
  id: string;
  username: string | null;
  email: string | null;
  name: string | null;
  role: 'ADMIN' | 'COLD_ROOM' | 'FARM';
  farmId: string | null;
  farmName: string | null;
  createdAt: string;
}

interface FarmOption {
  id: string;
  name: string;
  farmCode?: string | null;
  ruc?: string | null;
}

export default function UsuariosPage() {
  const [users, setUsers] = useState<UserItem[]>([]);
  const [farms, setFarms] = useState<FarmOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<string>('');

  // Filters
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState<'ALL' | 'ADMIN' | 'COLD_ROOM' | 'FARM'>('ALL');

  // Modals state
  const [modalOpen, setModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<UserItem | null>(null);
  const [form, setForm] = useState({
    name: '',
    username: '',
    email: '',
    password: '',
    role: 'ADMIN' as 'ADMIN' | 'COLD_ROOM' | 'FARM',
    farmId: ''
  });
  const [formError, setFormError] = useState('');
  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const fetchUsers = async (isManual = false) => {
    if (isManual) setRefreshing(true);
    else setLoading(true);

    try {
      const [uRes, fRes] = await Promise.all([
        fetch('/api/users'),
        fetch('/api/farms')
      ]);

      if (uRes.ok) {
        const uData = await uRes.json();
        if (Array.isArray(uData)) setUsers(uData);
      }
      if (fRes.ok) {
        const fData = await fRes.json();
        if (Array.isArray(fData)) setFarms(fData);
      }
      const now = new Date();
      setLastUpdated(now.toLocaleTimeString());
    } catch (e) {
      console.error('Error fetching users:', e);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const openCreateModal = () => {
    setEditingUser(null);
    setForm({
      name: '',
      username: '',
      email: '',
      password: '',
      role: 'ADMIN',
      farmId: farms[0]?.id || ''
    });
    setFormError('');
    setModalOpen(true);
  };

  const openEditModal = (u: UserItem) => {
    setEditingUser(u);
    setForm({
      name: u.name || '',
      username: u.username || '',
      email: u.email || '',
      password: '',
      role: u.role,
      farmId: u.farmId || farms[0]?.id || ''
    });
    setFormError('');
    setModalOpen(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError('');

    if (!form.username && !form.email) {
      setFormError('Ingresa un nombre de usuario o correo electrónico.');
      return;
    }
    if (!editingUser && !form.password.trim()) {
      setFormError('La contraseña es requerida para un usuario nuevo.');
      return;
    }
    if (form.role === 'FARM' && !form.farmId) {
      setFormError('Selecciona una Finca para el usuario de rol Finca.');
      return;
    }

    setSaving(true);
    try {
      const url = '/api/users';
      const method = editingUser ? 'PUT' : 'POST';
      const payload: any = {
        name: form.name.trim(),
        username: form.username.trim(),
        email: form.email.trim(),
        role: form.role,
        farmId: form.role === 'FARM' ? form.farmId : null
      };

      if (editingUser) {
        payload.id = editingUser.id;
        if (form.password.trim()) {
          payload.password = form.password.trim();
        }
      } else {
        payload.password = form.password.trim();
      }

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al guardar usuario');

      setModalOpen(false);
      fetchUsers(true);
    } catch (err: any) {
      setFormError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string, name: string) => {
    if (!window.confirm(`¿Estás seguro de eliminar al usuario "${name}"? Esta acción no se puede deshacer.`)) return;

    setDeletingId(id);
    try {
      const res = await fetch(`/api/users?id=${id}`, { method: 'DELETE' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al eliminar usuario');
      fetchUsers(true);
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    } finally {
      setDeletingId(null);
    }
  };

  // Filtered Users
  const filteredUsers = useMemo(() => {
    return users.filter(u => {
      if (roleFilter !== 'ALL' && u.role !== roleFilter) return false;
      if (search.trim()) {
        const q = search.toLowerCase();
        const str = `${u.name || ''} ${u.username || ''} ${u.email || ''} ${u.farmName || ''}`.toLowerCase();
        if (!str.includes(q)) return false;
      }
      return true;
    });
  }, [users, roleFilter, search]);

  const kpis = useMemo(() => {
    const total = users.length;
    const admin = users.filter(u => u.role === 'ADMIN').length;
    const coldRoom = users.filter(u => u.role === 'COLD_ROOM').length;
    const farm = users.filter(u => u.role === 'FARM').length;
    return { total, admin, coldRoom, farm };
  }, [users]);

  return (
    <MainLayout>
      <div style={{ padding: '1.5rem', maxWidth: '1400px', margin: '0 auto' }}>
        
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
          <div>
            <h1 style={{ margin: 0, fontSize: '1.85rem', color: '#1c5236', fontWeight: 800, display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
              👥 Gestión de Usuarios y Permisos
            </h1>
            <p style={{ margin: '0.35rem 0 0', color: '#64748b', fontSize: '0.9rem' }}>
              Crea y administra cuentas con accesos separados: Administradores (todo), Cuarto Frío (cuarto frío y tracking) o Fincas asociadas.
            </p>
          </div>
          <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
            <button
              onClick={() => fetchUsers(true)}
              disabled={refreshing}
              style={{
                display: 'flex', alignItems: 'center', gap: '0.5rem',
                background: '#f8fafc', border: '1px solid #cbd5e1', borderRadius: '10px',
                padding: '0.65rem 1.1rem', fontWeight: 700, fontSize: '0.88rem', color: '#334155',
                cursor: refreshing ? 'not-allowed' : 'pointer', transition: 'all 0.2s ease',
                boxShadow: '0 2px 5px rgba(0,0,0,0.04)'
              }}
              title="Actualizar tabla instantáneamente"
            >
              <svg
                width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                style={{ animation: refreshing ? 'spin 0.8s linear infinite' : 'none' }}
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              {refreshing ? 'Actualizando...' : 'Actualizar Información'}
            </button>
            <button
              onClick={openCreateModal}
              style={{
                display: 'flex', alignItems: 'center', gap: '0.5rem',
                background: 'linear-gradient(135deg, #1c5236, #2d6a4f)',
                color: '#fff', border: 'none', borderRadius: '10px',
                padding: '0.65rem 1.4rem', fontWeight: 800, fontSize: '0.92rem',
                cursor: 'pointer', boxShadow: '0 4px 14px rgba(28,82,54,0.3)'
              }}
            >
              ➕ Crear Usuario
            </button>
          </div>
        </div>

        {/* KPI Cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '1rem', marginBottom: '1.75rem' }}>
          <div style={{ background: '#fff', padding: '1.15rem 1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 2px 6px rgba(0,0,0,0.03)' }}>
            <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Total Usuarios</div>
            <div style={{ fontSize: '1.8rem', fontWeight: 800, color: '#1e293b', marginTop: '0.35rem' }}>{kpis.total}</div>
          </div>
          <div style={{ background: '#fff', padding: '1.15rem 1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 2px 6px rgba(0,0,0,0.03)' }}>
            <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#1e293b', textTransform: 'uppercase', letterSpacing: '0.05em' }}>👑 Administradores</div>
            <div style={{ fontSize: '1.8rem', fontWeight: 800, color: '#1c5236', marginTop: '0.35rem' }}>{kpis.admin}</div>
            <div style={{ fontSize: '0.75rem', color: '#64748b' }}>Acceso total</div>
          </div>
          <div style={{ background: '#fff', padding: '1.15rem 1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 2px 6px rgba(0,0,0,0.03)' }}>
            <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#0369a1', textTransform: 'uppercase', letterSpacing: '0.05em' }}>❄️ Cuarto Frío</div>
            <div style={{ fontSize: '1.8rem', fontWeight: 800, color: '#0284c7', marginTop: '0.35rem' }}>{kpis.coldRoom}</div>
            <div style={{ fontSize: '0.75rem', color: '#64748b' }}>Cuarto Frío & Tracking</div>
          </div>
          <div style={{ background: '#fff', padding: '1.15rem 1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 2px 6px rgba(0,0,0,0.03)' }}>
            <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#15803d', textTransform: 'uppercase', letterSpacing: '0.05em' }}>🌾 Fincas</div>
            <div style={{ fontSize: '1.8rem', fontWeight: 800, color: '#16a34a', marginTop: '0.35rem' }}>{kpis.farm}</div>
            <div style={{ fontSize: '0.75rem', color: '#64748b' }}>Pedidos & Etiquetas de su finca</div>
          </div>
        </div>

        {/* Filter bar */}
        <div style={{ background: '#fff', padding: '1.1rem 1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', marginBottom: '1.5rem', display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between' }}>
          {/* Search */}
          <div style={{ flex: 1, minWidth: '280px', position: 'relative' }}>
            <input
              type="text"
              placeholder="Buscar por nombre, correo, usuario o finca..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              style={{
                width: '100%', padding: '0.55rem 0.85rem 0.55rem 2.2rem',
                border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.88rem',
                boxSizing: 'border-box', outline: 'none'
              }}
            />
            <span style={{ position: 'absolute', left: '0.75rem', top: '50%', transform: 'translateY(-50%)', color: '#94a3b8' }}>
              🔍
            </span>
          </div>

          {/* Role Filter Tabs */}
          <div style={{ display: 'flex', gap: '0.35rem', background: '#f1f5f9', padding: '0.25rem', borderRadius: '8px' }}>
            {[
              { id: 'ALL', label: 'Todos' },
              { id: 'ADMIN', label: '👑 Admin' },
              { id: 'COLD_ROOM', label: '❄️ Cuarto Frío' },
              { id: 'FARM', label: '🌾 Finca' }
            ].map(tab => (
              <button
                key={tab.id}
                onClick={() => setRoleFilter(tab.id as any)}
                style={{
                  padding: '0.4rem 0.85rem', border: 'none', borderRadius: '6px',
                  background: roleFilter === tab.id ? '#fff' : 'transparent',
                  color: roleFilter === tab.id ? '#1c5236' : '#64748b',
                  fontWeight: roleFilter === tab.id ? 800 : 600, fontSize: '0.8rem',
                  cursor: 'pointer', boxShadow: roleFilter === tab.id ? '0 1px 4px rgba(0,0,0,0.08)' : 'none',
                  transition: 'all 0.15s ease'
                }}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {lastUpdated && (
            <div style={{ fontSize: '0.75rem', color: '#94a3b8' }}>
              Última sincronización: <b>{lastUpdated}</b>
            </div>
          )}
        </div>

        {/* Users Table */}
        <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 4px 12px rgba(0,0,0,0.04)', overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.85rem' }}>
            <thead>
              <tr style={{ background: '#1c5236', color: '#fff' }}>
                <th style={{ padding: '0.85rem 1rem', fontWeight: 700 }}>NOMBRE</th>
                <th style={{ padding: '0.85rem 1rem', fontWeight: 700 }}>CORREO / USUARIO</th>
                <th style={{ padding: '0.85rem 1rem', fontWeight: 700 }}>ROL Y ACCESO</th>
                <th style={{ padding: '0.85rem 1rem', fontWeight: 700 }}>FINCA ASIGNADA</th>
                <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>FECHA ALTA</th>
                <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>ACCIONES</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={6} style={{ textAlign: 'center', padding: '3.5rem', color: '#94a3b8' }}>
                    Cargando usuarios...
                  </td>
                </tr>
              ) : filteredUsers.length === 0 ? (
                <tr>
                  <td colSpan={6} style={{ textAlign: 'center', padding: '3.5rem', color: '#94a3b8' }}>
                    No se encontraron usuarios con los filtros seleccionados.
                  </td>
                </tr>
              ) : (
                filteredUsers.map(u => (
                  <tr key={u.id} style={{ borderBottom: '1px solid #f1f5f9', transition: 'background 0.15s ease' }}>
                    {/* Nombre */}
                    <td style={{ padding: '0.85rem 1rem', fontWeight: 700, color: '#1e293b' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
                        <div style={{
                          width: '32px', height: '32px', borderRadius: '50%',
                          background: u.role === 'ADMIN' ? '#1c5236' : (u.role === 'COLD_ROOM' ? '#0284c7' : '#16a34a'),
                          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontWeight: 800, fontSize: '0.75rem'
                        }}>
                          {(u.name || u.username || 'U').slice(0, 2).toUpperCase()}
                        </div>
                        <div>
                          <div>{u.name || 'Sin nombre'}</div>
                          <div style={{ fontSize: '0.72rem', color: '#94a3b8', fontWeight: 500 }}>ID: {u.id.slice(0, 8)}...</div>
                        </div>
                      </div>
                    </td>

                    {/* Email / Username */}
                    <td style={{ padding: '0.85rem 1rem' }}>
                      <div style={{ fontWeight: 600, color: '#0f172a' }}>{u.email || u.username || '—'}</div>
                      {u.username && u.email && u.username !== u.email && (
                        <div style={{ fontSize: '0.75rem', color: '#64748b' }}>Usuario: {u.username}</div>
                      )}
                    </td>

                    {/* Rol */}
                    <td style={{ padding: '0.85rem 1rem' }}>
                      {u.role === 'ADMIN' && (
                        <span style={{ background: '#ecfdf5', color: '#065f46', border: '1px solid #a7f3d0', padding: '0.25rem 0.65rem', borderRadius: '20px', fontSize: '0.78rem', fontWeight: 800, display: 'inline-flex', alignItems: 'center', gap: '0.35rem' }}>
                          👑 Administrador (Todo)
                        </span>
                      )}
                      {u.role === 'COLD_ROOM' && (
                        <span style={{ background: '#f0f9ff', color: '#0369a1', border: '1px solid #bae6fd', padding: '0.25rem 0.65rem', borderRadius: '20px', fontSize: '0.78rem', fontWeight: 800, display: 'inline-flex', alignItems: 'center', gap: '0.35rem' }}>
                          ❄️ Cuarto Frío & Tracking
                        </span>
                      )}
                      {u.role === 'FARM' && (
                        <span style={{ background: '#fefce8', color: '#854d0e', border: '1px solid #fef08a', padding: '0.25rem 0.65rem', borderRadius: '20px', fontSize: '0.78rem', fontWeight: 800, display: 'inline-flex', alignItems: 'center', gap: '0.35rem' }}>
                          🌾 Finca (Pedidos & Etiquetas)
                        </span>
                      )}
                    </td>

                    {/* Finca Asignada */}
                    <td style={{ padding: '0.85rem 1rem' }}>
                      {u.role === 'FARM' ? (
                        <span style={{ background: '#f1f5f9', color: '#166534', border: '1px solid #bbf7d0', padding: '0.25rem 0.6rem', borderRadius: '8px', fontSize: '0.8rem', fontWeight: 700 }}>
                          🌾 {u.farmName || 'Finca sin nombre'}
                        </span>
                      ) : (
                        <span style={{ color: '#94a3b8' }}>— No aplica —</span>
                      )}
                    </td>

                    {/* Fecha de alta */}
                    <td style={{ padding: '0.85rem 1rem', textAlign: 'center', color: '#64748b', fontSize: '0.78rem' }}>
                      {new Date(u.createdAt).toLocaleDateString()}
                    </td>

                    {/* Acciones */}
                    <td style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>
                      <div style={{ display: 'flex', gap: '0.4rem', justifyContent: 'center' }}>
                        <button
                          onClick={() => openEditModal(u)}
                          style={{
                            padding: '0.35rem 0.75rem', borderRadius: '6px', border: '1px solid #cbd5e1',
                            background: '#f8fafc', color: '#1e293b', fontWeight: 700, fontSize: '0.78rem',
                            cursor: 'pointer'
                          }}
                        >
                          ✏️ Editar
                        </button>
                        <button
                          onClick={() => handleDelete(u.id, u.name || u.username || 'Usuario')}
                          disabled={deletingId === u.id}
                          style={{
                            padding: '0.35rem 0.75rem', borderRadius: '6px', border: '1px solid #fecaca',
                            background: '#fef2f2', color: '#b91c1c', fontWeight: 700, fontSize: '0.78rem',
                            cursor: deletingId === u.id ? 'not-allowed' : 'pointer'
                          }}
                        >
                          {deletingId === u.id ? '...' : '🗑️'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Modal: Crear / Editar Usuario */}
        {modalOpen && (
          <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 1200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
            <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '560px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 25px 50px rgba(0,0,0,0.3)' }}>
              
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', borderBottom: '1px solid #e2e8f0', paddingBottom: '0.75rem' }}>
                <h2 style={{ margin: 0, fontSize: '1.35rem', color: '#1c5236', fontWeight: 800 }}>
                  {editingUser ? '✏️ Editar Usuario' : '➕ Crear Nuevo Usuario'}
                </h2>
                <button onClick={() => setModalOpen(false)} style={{ background: 'transparent', border: 'none', fontSize: '1.2rem', cursor: 'pointer', color: '#94a3b8' }}>
                  ✕
                </button>
              </div>

              {formError && (
                <div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: '8px', padding: '0.75rem 1rem', marginBottom: '1.25rem', color: '#b91c1c', fontSize: '0.85rem', fontWeight: 600 }}>
                  ⚠️ {formError}
                </div>
              )}

              <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                
                {/* Nombre */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.78rem', fontWeight: 700, color: '#334155', marginBottom: '0.25rem' }}>
                    Nombre Completo o de Contacto
                  </label>
                  <input
                    type="text"
                    placeholder="Ej. Juan Pérez / Latina Farms"
                    value={form.name}
                    onChange={e => setForm({ ...form, name: e.target.value })}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #cbd5e1', borderRadius: '8px', boxSizing: 'border-box' }}
                  />
                </div>

                {/* Email */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.78rem', fontWeight: 700, color: '#334155', marginBottom: '0.25rem' }}>
                    Correo Electrónico (para login con correo) *
                  </label>
                  <input
                    type="email"
                    placeholder="usuario@finca.com"
                    value={form.email}
                    onChange={e => setForm({ ...form, email: e.target.value })}
                    required
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #cbd5e1', borderRadius: '8px', boxSizing: 'border-box' }}
                  />
                </div>

                {/* Username */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.78rem', fontWeight: 700, color: '#334155', marginBottom: '0.25rem' }}>
                    Nombre de Usuario (opcional o igual al correo)
                  </label>
                  <input
                    type="text"
                    placeholder="juanperez"
                    value={form.username}
                    onChange={e => setForm({ ...form, username: e.target.value })}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #cbd5e1', borderRadius: '8px', boxSizing: 'border-box' }}
                  />
                </div>

                {/* Password */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.78rem', fontWeight: 700, color: '#334155', marginBottom: '0.25rem' }}>
                    Contraseña {editingUser ? '(dejar vacío para mantener la actual)' : '*'}
                  </label>
                  <input
                    type="password"
                    placeholder="Mínimo 6 caracteres"
                    value={form.password}
                    onChange={e => setForm({ ...form, password: e.target.value })}
                    required={!editingUser}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #cbd5e1', borderRadius: '8px', boxSizing: 'border-box' }}
                  />
                </div>

                {/* Role Selection */}
                <div>
                  <label style={{ display: 'block', fontSize: '0.78rem', fontWeight: 700, color: '#334155', marginBottom: '0.4rem' }}>
                    Rol y Tipo de Acceso *
                  </label>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '0.5rem' }}>
                    <div
                      onClick={() => setForm({ ...form, role: 'ADMIN' })}
                      style={{
                        padding: '0.85rem 0.6rem', border: form.role === 'ADMIN' ? '2px solid #1c5236' : '1px solid #cbd5e1',
                        borderRadius: '10px', background: form.role === 'ADMIN' ? '#f0fdf4' : '#fff',
                        cursor: 'pointer', textAlign: 'center'
                      }}
                    >
                      <div style={{ fontSize: '1.25rem' }}>👑</div>
                      <div style={{ fontWeight: 800, fontSize: '0.82rem', color: '#1c5236', marginTop: '0.2rem' }}>Administrador</div>
                      <div style={{ fontSize: '0.7rem', color: '#64748b', marginTop: '0.2rem' }}>Acceso total a todo el sistema</div>
                    </div>

                    <div
                      onClick={() => setForm({ ...form, role: 'COLD_ROOM' })}
                      style={{
                        padding: '0.85rem 0.6rem', border: form.role === 'COLD_ROOM' ? '2px solid #0284c7' : '1px solid #cbd5e1',
                        borderRadius: '10px', background: form.role === 'COLD_ROOM' ? '#f0f9ff' : '#fff',
                        cursor: 'pointer', textAlign: 'center'
                      }}
                    >
                      <div style={{ fontSize: '1.25rem' }}>❄️</div>
                      <div style={{ fontWeight: 800, fontSize: '0.82rem', color: '#0369a1', marginTop: '0.2rem' }}>Cuarto Frío</div>
                      <div style={{ fontSize: '0.7rem', color: '#64748b', marginTop: '0.2rem' }}>Cuarto Frío y Tracking</div>
                    </div>

                    <div
                      onClick={() => setForm({ ...form, role: 'FARM' })}
                      style={{
                        padding: '0.85rem 0.6rem', border: form.role === 'FARM' ? '2px solid #16a34a' : '1px solid #cbd5e1',
                        borderRadius: '10px', background: form.role === 'FARM' ? '#fefce8' : '#fff',
                        cursor: 'pointer', textAlign: 'center'
                      }}
                    >
                      <div style={{ fontSize: '1.25rem' }}>🌾</div>
                      <div style={{ fontWeight: 800, fontSize: '0.82rem', color: '#854d0e', marginTop: '0.2rem' }}>Finca</div>
                      <div style={{ fontSize: '0.7rem', color: '#64748b', marginTop: '0.2rem' }}>Pedidos y Etiquetas de su finca</div>
                    </div>
                  </div>
                </div>

                {/* Farm Selector (only if role is FARM) */}
                {form.role === 'FARM' && (
                  <div style={{ background: '#f8fafc', padding: '1rem', borderRadius: '10px', border: '1px solid #cbd5e1' }}>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 800, color: '#166534', marginBottom: '0.4rem' }}>
                      🌾 Finca Asociada a este Usuario *
                    </label>
                    <select
                      value={form.farmId}
                      onChange={e => setForm({ ...form, farmId: e.target.value })}
                      required
                      style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #cbd5e1', borderRadius: '8px', background: '#fff', fontWeight: 600, fontSize: '0.88rem' }}
                    >
                      <option value="">— Seleccionar Finca —</option>
                      {farms.map(f => (
                        <option key={f.id} value={f.id}>
                          {f.name} {f.ruc ? `(${f.ruc})` : ''}
                        </option>
                      ))}
                    </select>
                    <div style={{ fontSize: '0.72rem', color: '#64748b', marginTop: '0.35rem' }}>
                      ⚠️ Este usuario solo podrá ver los pedidos, historial, rechazos y etiquetas pertenecientes exclusivamente a esta finca.
                    </div>
                  </div>
                )}

                {/* Action buttons */}
                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                  <button
                    type="button"
                    onClick={() => setModalOpen(false)}
                    style={{ padding: '0.65rem 1.25rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#fff', color: '#64748b', fontWeight: 700, cursor: 'pointer' }}
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    disabled={saving}
                    style={{
                      padding: '0.65rem 1.6rem', borderRadius: '8px', border: 'none',
                      background: '#1c5236', color: '#fff', fontWeight: 800, cursor: saving ? 'not-allowed' : 'pointer',
                      boxShadow: '0 4px 10px rgba(28,82,54,0.25)'
                    }}
                  >
                    {saving ? 'Guardando...' : editingUser ? 'Actualizar Usuario' : 'Crear Usuario'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

      </div>
    </MainLayout>
  );
}
