'use client';

import MainLayout from '@/components/layout/MainLayout';
import { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';

type Farm = {
  id: string;
  name: string;
  ruc?: string;
  farmCode?: string;
  exporterName?: string;
  address?: string;
  city?: string;
  country?: string;
  phone?: string;
  contactName?: string;
  contactOrders?: string;
  phoneOrders?: string;
  emailOrders?: string;
  notifyOrders?: boolean;
  contactLabels?: string;
  phoneLabels?: string;
  emailLabels?: string;
  notifyLabels?: boolean;
  contactCoord?: string;
  phoneCoord?: string;
  emailCoord?: string;
  notifyCoord?: boolean;
  createdAt: string;
};

type FarmUser = {
  id: string;
  email: string;
  name: string;
  password?: string;
  farmId: string;
  farmName: string;
  createdAt: string;
};

const emptyForm = {
  name: '', ruc: '', farmCode: '', exporterName: '', address: '',
  city: '', country: 'EC', phone: '', contactName: '',
  contactOrders: '', phoneOrders: '', emailOrders: '', notifyOrders: true,
  contactLabels: '', phoneLabels: '', emailLabels: '', notifyLabels: true,
  contactCoord: '', phoneCoord: '', emailCoord: '', notifyCoord: true
};

export default function FarmsPage() {
  const [farms, setFarms] = useState<Farm[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState('');
  const [error, setError] = useState('');

  // ── Varieties Upload Modal State ──
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [uploadFarmId, setUploadFarmId] = useState('');
  const [uploadExcelRows, setUploadExcelRows] = useState<any[]>([]);
  const [uploadPreview, setUploadPreview] = useState<any[]>([]);
  const [uploadingVarieties, setUploadingVarieties] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState('');
  const [uploadModalError, setUploadModalError] = useState('');

  // ── Farm Users Management Modal State ──
  const [showUsersModal, setShowUsersModal] = useState(false);
  const [farmUsers, setFarmUsers] = useState<FarmUser[]>([]);
  const [newUserForm, setNewUserForm] = useState({ farmId: '', email: '', password: '', name: '' });
  const [savingUser, setSavingUser] = useState(false);
  const [userError, setUserError] = useState('');
  const [userSuccess, setUserSuccess] = useState('');
  const [visiblePasswords, setVisiblePasswords] = useState<{ [id: string]: boolean }>({});
  const [copiedId, setCopiedId] = useState<string | null>(null);

  const togglePasswordVisibility = (id: string) => {
    setVisiblePasswords(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const copyPassword = (id: string, pwd?: string) => {
    if (!pwd) return;
    navigator.clipboard.writeText(pwd);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const fetchFarms = async () => {
    setLoading(true);
    const res = await fetch('/api/farms');
    if (res.ok) setFarms(await res.json());
    setLoading(false);
  };

  const fetchFarmUsers = async () => {
    try {
      const res = await fetch('/api/farms/users');
      if (res.ok) setFarmUsers(await res.json());
    } catch {}
  };

  useEffect(() => {
    fetchFarms();
    fetchFarmUsers();
  }, []);

  const openCreate = () => {
    setEditingId(null);
    setForm(emptyForm);
    setError('');
    setShowModal(true);
  };

  const openEdit = (f: Farm) => {
    setEditingId(f.id);
    setForm({
      name: f.name || '',
      ruc: f.ruc || '',
      farmCode: f.farmCode || '',
      exporterName: f.exporterName || '',
      address: f.address || '',
      city: f.city || '',
      country: f.country || 'EC',
      phone: f.phone || '',
      contactName: f.contactName || '',
      contactOrders: f.contactOrders || '',
      phoneOrders: f.phoneOrders || '',
      emailOrders: f.emailOrders || '',
      notifyOrders: f.notifyOrders !== false,
      contactLabels: f.contactLabels || '',
      phoneLabels: f.phoneLabels || '',
      emailLabels: f.emailLabels || '',
      notifyLabels: f.notifyLabels !== false,
      contactCoord: f.contactCoord || '',
      phoneCoord: f.phoneCoord || '',
      emailCoord: f.emailCoord || '',
      notifyCoord: f.notifyCoord !== false
    });
    setError('');
    setShowModal(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true); setError('');
    const url = editingId ? `/api/farms/${editingId}` : '/api/farms';
    const method = editingId ? 'PUT' : 'POST';
    
    try {
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (res.ok) {
        setShowModal(false);
        fetchFarms();
      } else {
        const data = await res.json();
        setError(data.error || 'Error al guardar');
      }
    } catch {
      setError('Error de conexión');
    }
    setSaving(false);
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('¿Eliminar esta finca de forma permanente?')) return;
    await fetch(`/api/farms/${id}`, { method: 'DELETE' });
    fetchFarms();
  };

  // ── Varieties Upload Handlers ──
  const openVarietyUpload = (farmId?: string) => {
    setUploadFarmId(farmId || (farms[0]?.id || ''));
    setUploadExcelRows([]);
    setUploadPreview([]);
    setUploadSuccess('');
    setUploadModalError('');
    setShowUploadModal(true);
  };

  const getRoseBunchWeight = (lengthCm: number) => {
    if (lengthCm <= 40) return 1.6;
    if (lengthCm <= 50) return 1.8;
    if (lengthCm <= 60) return 2.0;
    return 2.5;
  };

  const handleExcelFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadModalError('');
    setUploadSuccess('');
    const reader = new FileReader();

    reader.onload = (evt) => {
      try {
        const bstr = evt.target?.result;
        const wb = XLSX.read(bstr, { type: 'binary' });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const rawGrid: any[][] = XLSX.utils.sheet_to_json(ws, { header: 1 });

        if (!rawGrid.length || rawGrid.length < 2) {
          setUploadModalError('El archivo Excel está vacío o no contiene filas de datos.');
          return;
        }

        const headerRow: any[] = rawGrid[0] || [];
        let colProduct = -1, colVariety = -1, colColor = -1;
        let colStemLength = -1, colBoxType = -1, colBoxL = -1, colBoxW = -1, colBoxH = -1;
        let colDim = -1, colPack = -1, colStems = -1, colTotal = -1, colRealWeight = -1;

        headerRow.forEach((h: any, idx: number) => {
          const str = String(h || '').trim().toLowerCase();
          if (/^prod/i.test(str)) colProduct = idx;
          else if (/^var/i.test(str)) colVariety = idx;
          else if (/^col/i.test(str)) colColor = idx;
          else if (/^box\s*type|tipo.*caja/i.test(str)) colBoxType = idx;
          else if (/^width|ancho/i.test(str)) colBoxW = idx;
          else if (/^height|alto/i.test(str)) colBoxH = idx;
          else if (/^dim/i.test(str)) colDim = idx;
          else if (/^pack|ramos/i.test(str)) colPack = idx;
          else if (/^stems|tallos/i.test(str)) colStems = idx;
          else if (/^total/i.test(str)) colTotal = idx;
          else if (/real.*weight|peso.*real/i.test(str)) colRealWeight = idx;
        });

        // Distinguir columnas duplicadas de Lenght / Longitud:
        // Longitud de tallo está antes de Box Type (ej. "40cm", "50cm")
        // Longitud de caja está después de Box Type (dimensiones de caja: 70, 104, 105)
        headerRow.forEach((h: any, idx: number) => {
          const str = String(h || '').trim().toLowerCase();
          if (/leng|long|tallo/i.test(str)) {
            if (colBoxType !== -1 && idx < colBoxType) {
              colStemLength = idx;
            } else {
              colBoxL = idx;
            }
          }
        });

        // Fallbacks según formato oficial: Product(0), Variety(1), Color(2), Tallo(3), BoxType(4), BoxL(5), BoxW(6), BoxH(7), Dim(8), Pack(9), Stems(10), Total(11), RealWeight(12)
        if (colProduct === -1) colProduct = 0;
        if (colVariety === -1) colVariety = 1;
        if (colColor === -1) colColor = 2;
        if (colStemLength === -1) colStemLength = 3;
        if (colBoxType === -1) colBoxType = 4;
        if (colBoxL === -1) colBoxL = 5;
        if (colBoxW === -1) colBoxW = 6;
        if (colBoxH === -1) colBoxH = 7;
        if (colDim === -1) colDim = 8;
        if (colPack === -1) colPack = 9;
        if (colStems === -1) colStems = 10;
        if (colTotal === -1) colTotal = 11;
        if (colRealWeight === -1) colRealWeight = 12;

        const preparedRows: any[] = [];
        const previews: any[] = [];

        for (let i = 1; i < rawGrid.length; i++) {
          const row = rawGrid[i];
          if (!row || row.length === 0) continue;

          const product = String(row[colProduct] || 'Rose').trim();
          const variety = String(row[colVariety] || row[colProduct] || `VARIEDAD-${i}`).trim();
          if (!variety) continue;

          const color = String(row[colColor] || '').trim();

          const rawStem = String(row[colStemLength] || '');
          const lengthCm = parseFloat(rawStem.replace(/[^\d.]/g, '')) || 50;

          const rawBox = String(row[colBoxType] || 'EB').trim().toUpperCase();
          const boxType = rawBox || 'EB';

          const l = parseFloat(row[colBoxL]) || 104;
          const w = parseFloat(row[colBoxW]) || 18;
          const h = parseFloat(row[colBoxH]) || 14;

          const pack = parseInt(row[colPack], 10) || 0;
          // Regla: si el pack dice 0, no se debe subir esa línea
          if (!pack || pack <= 0) continue;

          const stems = parseInt(row[colStems], 10) || 25;
          const total = parseInt(row[colTotal], 10) || (pack * stems);

          const dimWeight = Math.round(((l * w * h) / 6000) * 100) / 100;

          // Regla: Si no tiene peso real y el producto es rosa se calcula: pack * peso del ramo (40cm=1.6kg, 50cm=1.8kg, 60cm=2.0kg, 70cm=2.5kg)
          let realWeight = parseFloat(row[colRealWeight]) || 0;
          if (!realWeight || realWeight <= 0) {
            if (/ros[ea]/i.test(product) || !product) {
              const bunchWeight = getRoseBunchWeight(lengthCm);
              realWeight = Math.round((pack * bunchWeight) * 100) / 100;
            }
          }

          const itemObj = {
            product,
            variety,
            color,
            lengthCm,
            boxType,
            l,
            w,
            h,
            pack,
            stems,
            total,
            dimWeight,
            realWeight
          };

          preparedRows.push(itemObj);
          previews.push({
            variety,
            code: variety.slice(0, 10).toUpperCase(),
            lengthCm,
            pack,
            stems,
            boxType,
            l,
            w,
            h,
            dimWeight,
            realWeight
          });
        }

        setUploadExcelRows(preparedRows);
        setUploadPreview(previews);
      } catch (err: any) {
        setUploadModalError(`Error al leer archivo: ${err.message}`);
      }
    };

    reader.readAsBinaryString(file);
  };

  const handleSaveVarieties = async () => {
    if (!uploadFarmId || !uploadExcelRows.length) {
      setUploadModalError('Selecciona una finca y sube un archivo Excel con variedades.');
      return;
    }

    setUploadingVarieties(true);
    setUploadModalError('');
    setUploadSuccess('');
    const targetFarm = farms.find(f => f.id === uploadFarmId);

    try {
      const res = await fetch('/api/farms/varieties/upload', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          farmId: uploadFarmId,
          farmName: targetFarm?.name || 'Finca',
          rows: uploadExcelRows
        })
      });

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

      setUploadSuccess(`¡Excelente! ${data.message}`);
      setUploadExcelRows([]);
      setUploadPreview([]);
    } catch (err: any) {
      setUploadModalError(err.message);
    } finally {
      setUploadingVarieties(false);
    }
  };

  // ── Farm User Creation Handlers ──
  const openUsersManagement = (farmId?: string) => {
    setNewUserForm({
      farmId: farmId || (farms[0]?.id || ''),
      email: '',
      password: '',
      name: ''
    });
    setUserError('');
    setUserSuccess('');
    setShowUsersModal(true);
    fetchFarmUsers();
  };

  const handleCreateFarmUser = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newUserForm.farmId || !newUserForm.email || !newUserForm.password) {
      setUserError('Finca, correo y contraseña son obligatorios.');
      return;
    }

    setSavingUser(true);
    setUserError('');
    setUserSuccess('');
    const selectedFarm = farms.find(f => f.id === newUserForm.farmId);

    try {
      const res = await fetch('/api/farms/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...newUserForm,
          farmName: selectedFarm?.name || 'Finca'
        })
      });

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

      setUserSuccess(`¡Usuario "${data.email || data.username}" creado exitosamente para la finca ${data.farmName}!`);
      setNewUserForm({ farmId: newUserForm.farmId, email: '', password: '', name: '' });
      fetchFarmUsers();
    } catch (err: any) {
      setUserError(err.message);
    } finally {
      setSavingUser(false);
    }
  };

  const handleDeleteFarmUser = async (userId: string) => {
    if (!window.confirm('¿Eliminar este usuario de finca?')) return;
    await fetch(`/api/farms/users?id=${userId}`, { method: 'DELETE' });
    fetchFarmUsers();
  };

  const filtered = farms.filter(f => 
    f.name.toLowerCase().includes(search.toLowerCase()) || 
    (f.ruc && f.ruc.toLowerCase().includes(search.toLowerCase())) ||
    (f.farmCode && f.farmCode.toLowerCase().includes(search.toLowerCase())) ||
    (f.country && f.country.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <MainLayout>
      <div style={{ padding: '2rem', maxWidth: '1280px', margin: '0 auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
          <div>
            <h1 style={{ margin: 0, fontSize: '1.75rem', fontWeight: 800, color: '#1a1a2e' }}>🌻 Fincas Proveedoras</h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Gestión de fincas, portales de acceso, variedades y cajas.</p>
          </div>
          <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
            <button
              onClick={() => openVarietyUpload()}
              style={{ padding: '0.6rem 1.1rem', borderRadius: '8px', border: '1.5px solid #059669', background: '#ecfdf5', color: '#059669', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
            >
              📥 Cargar Excel de Variedades
            </button>
            <button
              onClick={() => openUsersManagement()}
              style={{ padding: '0.6rem 1.1rem', borderRadius: '8px', border: '1.5px solid #3b82f6', background: '#eff6ff', color: '#1d4ed8', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
            >
              👤 Usuarios de Finca ({farmUsers.length})
            </button>
            <button
              onClick={() => window.open('/farms/portal', '_blank')}
              style={{ padding: '0.6rem 1.1rem', borderRadius: '8px', border: '1.5px solid #8b5cf6', background: '#f5f3ff', color: '#6d28d9', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
            >
              🌐 Abrir Portal Fincas
            </button>
            <button onClick={() => window.location.href = '/farms/invoices'}
              style={{ padding: '0.6rem 1.1rem', borderRadius: '8px', border: '1px solid #ddd', background: '#fff', color: '#333', cursor: 'pointer', fontWeight: 600, fontSize: '0.85rem' }}>
              Estado de Cuenta
            </button>
            <button onClick={openCreate}
              style={{ padding: '0.6rem 1.3rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #1c5236, #059669)', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem' }}>
              + Nueva Finca
            </button>
          </div>
        </div>

        <div style={{ marginBottom: '1rem' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar finca por nombre, RUC, código o país..."
            style={{ width: '100%', padding: '0.65rem 1rem', borderRadius: '8px', border: '1px solid #ddd', fontSize: '0.95rem', boxSizing: 'border-box' }} />
        </div>

        <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 2px 12px rgba(0,0,0,0.08)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem' }}>
            <thead>
              <tr style={{ background: 'linear-gradient(135deg, #1c5236, #059669)', color: '#fff' }}>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>RUC</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Finca</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>País</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Exportador</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Contacto</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'left' }}>Teléfono</th>
                <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>Cargando...</td></tr>
              ) : filtered.length === 0 ? (
                <tr><td colSpan={7} style={{ textAlign: 'center', padding: '2rem', color: '#999' }}>
                  {search ? 'No se encontraron fincas.' : 'No hay fincas registradas.'}
                </td></tr>
              ) : filtered.map((f, i) => (
                <tr key={f.id} style={{ background: i % 2 === 0 ? '#fff' : '#f8f9fa', borderBottom: '1px solid #eee' }}>
                  <td style={{ padding: '0.75rem 1rem' }}><code style={{ fontSize: '0.8rem', background: '#eff6ff', color: '#1d4ed8', padding: '0.15rem 0.5rem', borderRadius: '4px', fontWeight: 700 }}>{f.ruc || '---'}</code></td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#0f172a' }}>{f.name}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}><span style={{ fontWeight: 700, fontSize: '0.78rem', background: '#f3f4f6', padding: '0.2rem 0.5rem', borderRadius: '4px' }}>{f.country || 'EC'}</span></td>
                  <td style={{ padding: '0.75rem 1rem', color: '#475569' }}>{f.exporterName || '---'}</td>
                  <td style={{ padding: '0.75rem 1rem', color: '#475569' }}>{f.contactName || '---'}</td>
                  <td style={{ padding: '0.75rem 1rem', color: '#475569' }}>{f.phone || '---'}</td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <div style={{ display: 'inline-flex', gap: '0.35rem' }}>
                      <button
                        onClick={() => openVarietyUpload(f.id)}
                        title="Cargar Variedades y Cajas (Excel)"
                        style={{ background: '#ecfdf5', border: '1px solid #a7f3d0', borderRadius: '6px', padding: '0.35rem 0.6rem', cursor: 'pointer', color: '#059669', fontSize: '0.8rem', fontWeight: 700 }}
                      >
                        📦 Variedades
                      </button>
                      <button
                        onClick={() => openUsersManagement(f.id)}
                        title="Crear o Ver Usuario de Portal"
                        style={{ background: '#eff6ff', border: '1px solid #bfdbfe', borderRadius: '6px', padding: '0.35rem 0.6rem', cursor: 'pointer', color: '#1d4ed8', fontSize: '0.8rem', fontWeight: 700 }}
                      >
                        👤 Usuario
                      </button>
                      <button onClick={() => openEdit(f)} title="Editar Finca" style={{ background: '#e3f2fd', border: 'none', borderRadius: '6px', padding: '0.35rem 0.6rem', cursor: 'pointer', color: '#1565c0', fontSize: '0.85rem' }}>✏️</button>
                      <button onClick={() => handleDelete(f.id)} title="Eliminar Finca" style={{ background: '#fdecea', border: 'none', borderRadius: '6px', padding: '0.35rem 0.6rem', cursor: 'pointer', color: '#c62828', fontSize: '0.85rem' }}>🗑️</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* ── MODAL NUEVA/EDITAR FINCA ── */}
        {showModal && (
          <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
            <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '700px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto' }}>
              <h2 style={{ margin: '0 0 1.5rem', fontSize: '1.2rem', color: '#1a1a2e' }}>{editingId ? '✏️ Editar Finca' : '🌻 Nueva Finca'}</h2>
              
              {error && (
                <div style={{ background: '#fef2f2', border: '1.5px solid #f87171', color: '#b91c1c', padding: '0.75rem 1rem', borderRadius: '8px', fontSize: '0.85rem', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '1rem' }}>
                  ⚠️ {error}
                </div>
              )}

              <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Nombre de la Finca *</label>
                    <input required placeholder="Ej: Finca Las Rosas" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Código de Finca</label>
                    <input placeholder="Ej: F001" value={form.farmCode} onChange={e => setForm({ ...form, farmCode: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>RUC (Único) *</label>
                    <input placeholder="RUC de la finca" value={form.ruc} onChange={e => setForm({ ...form, ruc: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Nombre Exportador (Facturación)</label>
                    <input placeholder="Razón social" value={form.exporterName} onChange={e => setForm({ ...form, exporterName: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Ciudad</label>
                    <input placeholder="Ej: Quito" value={form.city} onChange={e => setForm({ ...form, city: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>País *</label>
                    <select required value={form.country} onChange={e => setForm({ ...form, country: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box', background: '#fff' }}>
                      <option value="EC">Ecuador (EC)</option>
                      <option value="CO">Colombia (CO)</option>
                      <option value="USA">Estados Unidos (USA)</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Dirección Física</label>
                  <input placeholder="Dirección completa" value={form.address} onChange={e => setForm({ ...form, address: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Contacto Principal</label>
                    <input placeholder="Nombre del contacto" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Teléfono</label>
                    <input placeholder="Teléfono" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
                  </div>
                </div>

                <div style={{ background: '#f8fafc', padding: '1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', marginTop: '0.5rem' }}>
                  <h3 style={{ margin: '0 0 0.85rem', fontSize: '0.95rem', fontWeight: 800, color: '#1c5236', display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                    📬 Contactos y Notificaciones de Pedidos
                  </h3>
                  <p style={{ margin: '0 0 1rem', fontSize: '0.8rem', color: '#64748b' }}>
                    Configura los datos del personal de la finca y selecciona con el checkbox quién debe recibir copia de las órdenes de compra.
                  </p>

                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '1.25rem' }}>
                    {/* Órdenes */}
                    <div style={{ background: '#ffffff', padding: '1rem', borderRadius: '10px', border: '1px solid #cbd5e1', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem', borderBottom: '1px solid #f1f5f9', paddingBottom: '0.4rem' }}>
                        <span style={{ fontWeight: 800, fontSize: '0.85rem', color: '#1e293b' }}>📦 ÓRDENES DE COMPRA</span>
                        <label style={{ display: 'flex', alignItems: 'center', gap: '0.35rem', fontSize: '0.75rem', fontWeight: 700, color: form.notifyOrders ? '#15803d' : '#64748b', cursor: 'pointer' }}>
                          <input
                            type="checkbox"
                            checked={form.notifyOrders}
                            onChange={e => setForm({ ...form, notifyOrders: e.target.checked })}
                            style={{ cursor: 'pointer' }}
                          />
                          Recibe Pedido
                        </label>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Nombre Contacto Órdenes</label>
                          <input
                            placeholder="Ej. María Fernanda"
                            value={form.contactOrders}
                            onChange={e => setForm({ ...form, contactOrders: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Celular / Teléfono</label>
                          <input
                            placeholder="Ej. +593 99 123 4567"
                            value={form.phoneOrders}
                            onChange={e => setForm({ ...form, phoneOrders: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Email Órdenes</label>
                          <input
                            type="email"
                            placeholder="ordenes@finca.com"
                            value={form.emailOrders}
                            onChange={e => setForm({ ...form, emailOrders: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                      </div>
                    </div>

                    {/* Etiquetas */}
                    <div style={{ background: '#ffffff', padding: '1rem', borderRadius: '10px', border: '1px solid #cbd5e1', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem', borderBottom: '1px solid #f1f5f9', paddingBottom: '0.4rem' }}>
                        <span style={{ fontWeight: 800, fontSize: '0.85rem', color: '#1e293b' }}>🏷️ ETIQUETAS DE CAJAS</span>
                        <label style={{ display: 'flex', alignItems: 'center', gap: '0.35rem', fontSize: '0.75rem', fontWeight: 700, color: form.notifyLabels ? '#15803d' : '#64748b', cursor: 'pointer' }}>
                          <input
                            type="checkbox"
                            checked={form.notifyLabels}
                            onChange={e => setForm({ ...form, notifyLabels: e.target.checked })}
                            style={{ cursor: 'pointer' }}
                          />
                          Recibe Pedido
                        </label>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Nombre Contacto Etiquetas</label>
                          <input
                            placeholder="Ej. Juan Pérez"
                            value={form.contactLabels}
                            onChange={e => setForm({ ...form, contactLabels: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Celular / Teléfono</label>
                          <input
                            placeholder="Ej. +593 98 765 4321"
                            value={form.phoneLabels}
                            onChange={e => setForm({ ...form, phoneLabels: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Email Etiquetas</label>
                          <input
                            type="email"
                            placeholder="etiquetas@finca.com"
                            value={form.emailLabels}
                            onChange={e => setForm({ ...form, emailLabels: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                      </div>
                    </div>

                    {/* Coordinación */}
                    <div style={{ background: '#ffffff', padding: '1rem', borderRadius: '10px', border: '1px solid #cbd5e1', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem', borderBottom: '1px solid #f1f5f9', paddingBottom: '0.4rem' }}>
                        <span style={{ fontWeight: 800, fontSize: '0.85rem', color: '#1e293b' }}>🤝 COORDINACIÓN GENERAL</span>
                        <label style={{ display: 'flex', alignItems: 'center', gap: '0.35rem', fontSize: '0.75rem', fontWeight: 700, color: form.notifyCoord ? '#15803d' : '#64748b', cursor: 'pointer' }}>
                          <input
                            type="checkbox"
                            checked={form.notifyCoord}
                            onChange={e => setForm({ ...form, notifyCoord: e.target.checked })}
                            style={{ cursor: 'pointer' }}
                          />
                          Recibe Pedido
                        </label>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Nombre Contacto Coordinación</label>
                          <input
                            placeholder="Ej. Ing. Carlos Andrade"
                            value={form.contactCoord}
                            onChange={e => setForm({ ...form, contactCoord: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Celular / Teléfono</label>
                          <input
                            placeholder="Ej. +593 99 999 8888"
                            value={form.phoneCoord}
                            onChange={e => setForm({ ...form, phoneCoord: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                        <div>
                          <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Email Coordinación</label>
                          <input
                            type="email"
                            placeholder="coordinacion@finca.com"
                            value={form.emailCoord}
                            onChange={e => setForm({ ...form, emailCoord: e.target.value })}
                            style={{ width: '100%', padding: '0.45rem 0.65rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                  <button type="button" onClick={() => setShowModal(false)} style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: '1px solid #ddd', background: '#fff', cursor: 'pointer' }}>Cancelar</button>
                  <button type="submit" disabled={saving} style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #1c5236, #059669)', color: '#fff', cursor: 'pointer', fontWeight: 700 }}>
                    {saving ? 'Guardando...' : editingId ? 'Actualizar Finca' : 'Guardar Finca'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* ── MODAL CARGAR VARIEDADES EXCEL ── */}
        {showUploadModal && (
          <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: '1rem' }}>
            <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '850px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem' }}>
                <h2 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 800, color: '#0f172a' }}>
                  📥 Carga de Variedades y Cajas por Finca
                </h2>
                <button onClick={() => setShowUploadModal(false)} style={{ border: 'none', background: 'none', fontSize: '1.25rem', cursor: 'pointer', color: '#64748b' }}>&times;</button>
              </div>

              <p style={{ color: '#64748b', fontSize: '0.85rem', margin: '0 0 1rem' }}>
                Sube el Excel con las variedades y especificaciones de cajas de la finca seleccionada. El sistema calculará automáticamente el <strong>Peso Real</strong> (40cm=1.6kg, 50cm=1.8kg, 60cm=2.0kg, 70cm=2.5kg por ramo) y el <strong>Peso Dimensional</strong>.
              </p>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1.25rem' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.35rem', color: '#334155' }}>
                    Seleccionar Finca Proveedora *
                  </label>
                  <select
                    value={uploadFarmId}
                    onChange={e => setUploadFarmId(e.target.value)}
                    style={{ width: '100%', padding: '0.65rem 0.8rem', borderRadius: '8px', border: '1.5px solid #cbd5e1', fontSize: '0.9rem', background: '#fff' }}
                  >
                    {farms.map(f => (
                      <option key={f.id} value={f.id}>{f.name} ({f.ruc || f.country || 'EC'})</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.35rem', color: '#334155' }}>
                    Archivo Excel de Variedades (.xlsx / .xls) *
                  </label>
                  <input
                    type="file"
                    accept=".xlsx, .xls"
                    onChange={handleExcelFileSelect}
                    style={{ width: '100%', padding: '0.5rem', borderRadius: '8px', border: '1px solid #cbd5e1', fontSize: '0.85rem' }}
                  />
                </div>
              </div>

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

              {uploadSuccess && (
                <div style={{ padding: '0.75rem 1rem', background: '#ecfdf5', border: '1px solid #a7f3d0', color: '#065f46', borderRadius: '8px', fontSize: '0.85rem', fontWeight: 600, marginBottom: '1rem' }}>
                  ✅ {uploadSuccess}
                </div>
              )}

              {/* Preview Table */}
              {uploadPreview.length > 0 && (
                <div style={{ marginTop: '1rem', border: '1px solid #e2e8f0', borderRadius: '10px', overflow: 'hidden', marginBottom: '1.5rem' }}>
                  <div style={{ background: '#f8fafc', padding: '0.6rem 1rem', fontWeight: 700, fontSize: '0.85rem', color: '#334155', borderBottom: '1px solid #e2e8f0' }}>
                    Vista Previa: {uploadPreview.length} variedades calculadas
                  </div>
                  <div style={{ maxHeight: '220px', overflowY: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.8rem' }}>
                      <thead>
                        <tr style={{ background: '#f1f5f9' }}>
                          <th style={{ padding: '0.5rem', textAlign: 'left' }}>Variedad</th>
                          <th style={{ padding: '0.5rem', textAlign: 'center' }}>Tallo</th>
                          <th style={{ padding: '0.5rem', textAlign: 'center' }}>Pack</th>
                          <th style={{ padding: '0.5rem', textAlign: 'center' }}>Caja</th>
                          <th style={{ padding: '0.5rem', textAlign: 'center' }}>Dim (LxWxH)</th>
                          <th style={{ padding: '0.5rem', textAlign: 'center', color: '#059669' }}>Peso Real</th>
                          <th style={{ padding: '0.5rem', textAlign: 'center', color: '#2563eb' }}>Peso DIM</th>
                        </tr>
                      </thead>
                      <tbody>
                        {uploadPreview.map((p, idx) => (
                          <tr key={idx} style={{ borderBottom: '1px solid #eee' }}>
                            <td style={{ padding: '0.45rem', fontWeight: 700 }}>{p.variety}</td>
                            <td style={{ padding: '0.45rem', textAlign: 'center' }}>{p.lengthCm}cm</td>
                            <td style={{ padding: '0.45rem', textAlign: 'center' }}>{p.pack}</td>
                            <td style={{ padding: '0.45rem', textAlign: 'center' }}>{p.boxType}</td>
                            <td style={{ padding: '0.45rem', textAlign: 'center' }}>{p.l}x{p.w}x{p.h}</td>
                            <td style={{ padding: '0.45rem', textAlign: 'center', fontWeight: 800, color: '#059669' }}>{p.realWeight}kg</td>
                            <td style={{ padding: '0.45rem', textAlign: 'center', fontWeight: 800, color: '#2563eb' }}>{p.dimWeight}kg</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  onClick={() => setShowUploadModal(false)}
                  style={{ padding: '0.6rem 1.25rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#fff', cursor: 'pointer', fontSize: '0.85rem' }}
                >
                  Cerrar
                </button>
                <button
                  type="button"
                  disabled={uploadingVarieties || uploadPreview.length === 0}
                  onClick={handleSaveVarieties}
                  style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #1c5236, #059669)', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem' }}
                >
                  {uploadingVarieties ? 'Procesando...' : `Confirmar y Cargar Variedades`}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ── MODAL USUARIOS DE FINCA ── */}
        {showUsersModal && (
          <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: '1rem' }}>
            <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '750px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem' }}>
                <h2 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 800, color: '#0f172a' }}>
                  👤 Gestión de Cuentas de Acceso para Fincas
                </h2>
                <button onClick={() => setShowUsersModal(false)} style={{ border: 'none', background: 'none', fontSize: '1.25rem', cursor: 'pointer', color: '#64748b' }}>&times;</button>
              </div>

              <p style={{ color: '#64748b', fontSize: '0.85rem', margin: '0 0 1.25rem' }}>
                Crea cuentas para que los administradores de fincas puedan iniciar sesión en el <strong>Portal de Fincas</strong> (<a href="/farms/portal" target="_blank" style={{ color: '#059669' }}>/farms/portal</a>) y gestionar sus propias listas.
              </p>

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

              {userSuccess && (
                <div style={{ padding: '0.6rem 0.9rem', background: '#ecfdf5', border: '1px solid #a7f3d0', color: '#065f46', borderRadius: '8px', fontSize: '0.85rem', fontWeight: 600, marginBottom: '1rem' }}>
                  ✅ {userSuccess}
                </div>
              )}

              {/* Form to create user */}
              <form onSubmit={handleCreateFarmUser} style={{ background: '#f8fafc', padding: '1.25rem', borderRadius: '12px', border: '1px solid #e2e8f0', marginBottom: '1.5rem' }}>
                <h4 style={{ margin: '0 0 0.75rem', fontSize: '0.9rem', fontWeight: 700, color: '#1e293b' }}>+ Crear Nuevo Usuario de Finca</h4>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, marginBottom: '0.25rem', color: '#334155' }}>Finca Asociada *</label>
                    <select
                      value={newUserForm.farmId}
                      onChange={e => setNewUserForm({ ...newUserForm, farmId: e.target.value })}
                      style={{ width: '100%', padding: '0.55rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.85rem', background: '#fff' }}
                      required
                    >
                      <option value="">-- Seleccionar Finca --</option>
                      {farms.map(f => (
                        <option key={f.id} value={f.id}>{f.name}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, marginBottom: '0.25rem', color: '#334155' }}>Nombre Contacto / Cargo</label>
                    <input
                      type="text"
                      placeholder="Ej: Ing. Carlos Pérez"
                      value={newUserForm.name}
                      onChange={e => setNewUserForm({ ...newUserForm, name: e.target.value })}
                      style={{ width: '100%', padding: '0.55rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.85rem', boxSizing: 'border-box' }}
                    />
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '1rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, marginBottom: '0.25rem', color: '#334155' }}>Correo Electrónico (Login) *</label>
                    <input
                      type="email"
                      required
                      placeholder="ventas@finca.com"
                      value={newUserForm.email}
                      onChange={e => setNewUserForm({ ...newUserForm, email: e.target.value })}
                      style={{ width: '100%', padding: '0.55rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.85rem', boxSizing: 'border-box' }}
                    />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, marginBottom: '0.25rem', color: '#334155' }}>Contraseña de Acceso *</label>
                    <input
                      type="password"
                      required
                      placeholder="••••••••"
                      value={newUserForm.password}
                      onChange={e => setNewUserForm({ ...newUserForm, password: e.target.value })}
                      style={{ width: '100%', padding: '0.55rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.85rem', boxSizing: 'border-box' }}
                    />
                  </div>
                </div>

                <button
                  type="submit"
                  disabled={savingUser}
                  style={{ padding: '0.55rem 1.25rem', borderRadius: '8px', border: 'none', background: '#059669', color: '#fff', fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer' }}
                >
                  {savingUser ? 'Guardando...' : 'Crear Cuenta de Acceso'}
                </button>
              </form>

              {/* List of active users */}
              <h4 style={{ margin: '0 0 0.75rem', fontSize: '0.9rem', fontWeight: 700, color: '#1e293b' }}>
                Usuarios de Finca Registrados ({farmUsers.length})
              </h4>
              <div style={{ border: '1px solid #e2e8f0', borderRadius: '8px', overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.85rem' }}>
                  <thead>
                    <tr style={{ background: '#f1f5f9', color: '#334155' }}>
                      <th style={{ padding: '0.6rem 0.8rem', textAlign: 'left' }}>Finca</th>
                      <th style={{ padding: '0.6rem 0.8rem', textAlign: 'left' }}>Contacto</th>
                      <th style={{ padding: '0.6rem 0.8rem', textAlign: 'left' }}>Email / Login</th>
                      <th style={{ padding: '0.6rem 0.8rem', textAlign: 'left' }}>Contraseña</th>
                      <th style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>Acción</th>
                    </tr>
                  </thead>
                  <tbody>
                    {farmUsers.length === 0 ? (
                      <tr><td colSpan={5} style={{ textAlign: 'center', padding: '1.5rem', color: '#94a3b8' }}>No hay usuarios de finca creados aún.</td></tr>
                    ) : (
                      farmUsers.map(u => (
                        <tr key={u.id} style={{ borderBottom: '1px solid #eee' }}>
                          <td style={{ padding: '0.6rem 0.8rem', fontWeight: 700, color: '#0f172a' }}>{u.farmName}</td>
                          <td style={{ padding: '0.6rem 0.8rem' }}>{u.name}</td>
                          <td style={{ padding: '0.6rem 0.8rem', fontFamily: 'monospace', color: '#1d4ed8' }}>{u.email}</td>
                          <td style={{ padding: '0.6rem 0.8rem' }}>
                            <div style={{ display: 'inline-flex', alignItems: 'center', gap: '0.35rem', background: '#f8fafc', padding: '0.2rem 0.5rem', borderRadius: '6px', border: '1px solid #e2e8f0' }}>
                              <span style={{ fontFamily: 'monospace', fontSize: '0.85rem', color: '#0f172a', fontWeight: 600 }}>
                                {visiblePasswords[u.id] ? (u.password || '••••••••') : '••••••••'}
                              </span>
                              <button
                                type="button"
                                onClick={() => togglePasswordVisibility(u.id)}
                                title={visiblePasswords[u.id] ? "Ocultar contraseña" : "Ver contraseña"}
                                style={{ border: 'none', background: 'none', cursor: 'pointer', padding: '0.1rem 0.2rem', fontSize: '0.85rem' }}
                              >
                                {visiblePasswords[u.id] ? '🙈' : '👁️'}
                              </button>
                              {u.password && (
                                <button
                                  type="button"
                                  onClick={() => copyPassword(u.id, u.password)}
                                  title="Copiar contraseña"
                                  style={{ border: 'none', background: 'none', cursor: 'pointer', padding: '0.1rem 0.2rem', fontSize: '0.8rem' }}
                                >
                                  {copiedId === u.id ? '✅' : '📋'}
                                </button>
                              )}
                            </div>
                          </td>
                          <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                            <button
                              onClick={() => handleDeleteFarmUser(u.id)}
                              style={{ border: 'none', background: '#fef2f2', color: '#dc2626', borderRadius: '4px', padding: '0.25rem 0.5rem', cursor: 'pointer', fontSize: '0.75rem', fontWeight: 700 }}
                            >
                              Eliminar
                            </button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </div>
    </MainLayout>
  );
}
