const { useState, useEffect, useCallback } = React;

// ============================================
// Modal reutilizable para formularios admin
// ============================================
const AdminModal = ({ open, title, onClose, onSave, saveLabel = "Guardar", children, wide = false }) => {
  if (!open) return null;

  return (
    <div className="adm-modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className={`adm-modal ${wide ? "adm-modal-wide" : ""}`}>
        <div className="adm-modal-head">
          <h2>{title}</h2>
          <button className="icon-btn-sm" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="adm-modal-body">
          {children}
        </div>
        <div className="adm-modal-foot">
          <button className="btn btn-cancel btn-sm" onClick={onClose}>Cancelar</button>
          <button className="btn btn-action btn-sm" onClick={onSave}><Icon name="save" size={14} /> {saveLabel}</button>
        </div>
      </div>
    </div>
  );
};

// ============================================
// AdminView principal
// ============================================
const AdminView = ({ showToast }) => {
  const [tab, setTab] = useState("stores");

  const tabs = [
    { id: "stores", label: "Tiendas",     icon: "store" },
    { id: "users",  label: "Usuarios",    icon: "users" },
  ];

  return (
    <div className="admin-wrap">
      <div className="admin-header">
        <h1><Icon name="shield" size={22} /> Administracion</h1>
      </div>
      <div className="admin-tabs">
        {tabs.map((t) => (
          <button key={t.id} className={`admin-tab ${tab === t.id ? "is-active" : ""}`} onClick={() => setTab(t.id)}>
            <Icon name={t.icon} size={15} /> {t.label}
          </button>
        ))}
      </div>
      <div className="admin-content">
        {tab === "stores" && <StoresPanel showToast={showToast} />}
        {tab === "users" && <UsersPanel showToast={showToast} />}
      </div>
    </div>
  );
};

// ---- Stores ----
const StoresPanel = ({ showToast }) => {
  const [stores, setStores] = useState([]);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState({});

  const load = useCallback(async () => {
    const res = await fetchWithAuth(`${API_BASE}/admin/stores`);
    if (res.ok) { const d = await res.json(); setStores(d.stores || []); }
  }, []);

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

  const save = async () => {
    const method = editing === "new" ? "POST" : "PUT";
    const url = editing === "new" ? `${API_BASE}/admin/stores` : `${API_BASE}/admin/stores/${form.id}`;
    const res = await fetchWithAuth(url, { method, body: JSON.stringify(form) });
    if (res.ok) { showToast("Tienda guardada"); setEditing(null); load(); }
    else { const d = await res.json().catch(() => ({})); showToast(d.message || "Error"); }
  };

  const startEdit = (s) => { setForm({ ...s }); setEditing(s.id); };
  const startNew = () => {
    setForm({ code: "", name: "", address: "", db_host: "localhost", db_port: 3306, db_name: "", db_user: "root", db_password: "" });
    setEditing("new");
  };

  return (
    <div>
      <div className="admin-toolbar">
        <h2>Tiendas</h2>
        <button className="btn btn-action btn-sm" onClick={startNew}><Icon name="plus" size={14} /> Nueva tienda</button>
      </div>

      <AdminModal
        open={!!editing}
        title={editing === "new" ? "Nueva tienda" : "Editar tienda"}
        onClose={() => setEditing(null)}
        onSave={save}
      >
        <div className="admin-form-grid">
          <FormField label="Codigo" value={form.code} onChange={(v) => setForm({ ...form, code: v })} />
          <FormField label="Nombre" value={form.name} onChange={(v) => setForm({ ...form, name: v })} />
          <FormField label="Direccion" value={form.address} onChange={(v) => setForm({ ...form, address: v })} />
          <FormField label="DB Host" value={form.db_host} onChange={(v) => setForm({ ...form, db_host: v })} />
          <FormField label="DB Puerto" value={form.db_port} type="number" onChange={(v) => setForm({ ...form, db_port: Number(v) })} />
          <FormField label="DB Nombre" value={form.db_name} onChange={(v) => setForm({ ...form, db_name: v })} />
          <FormField label="DB Usuario" value={form.db_user} onChange={(v) => setForm({ ...form, db_user: v })} />
          <FormField label="DB Password" value={form.db_password} type="password" onChange={(v) => setForm({ ...form, db_password: v })} />
        </div>
      </AdminModal>

      <table className="admin-table">
        <thead><tr><th>Codigo</th><th>Nombre</th><th>Direccion</th><th>BD</th><th>Estado</th><th></th></tr></thead>
        <tbody>
          {stores.map((s) => (
            <tr key={s.id}>
              <td className="mono">{s.code}</td>
              <td>{s.name}</td>
              <td>{s.address || "-"}</td>
              <td className="mono">{s.db_host}:{s.db_port}/{s.db_name}</td>
              <td><span className={`status-dot ${s.is_active ? "active" : "inactive"}`} />{s.is_active ? "Activa" : "Inactiva"}</td>
              <td><button className="icon-btn-sm" onClick={() => startEdit(s)}><Icon name="edit" size={14} /></button></td>
            </tr>
          ))}
          {stores.length === 0 && <tr><td colSpan={6} className="empty-cell">Sin tiendas registradas</td></tr>}
        </tbody>
      </table>
    </div>
  );
};

// ---- Users ----
const UsersPanel = ({ showToast }) => {
  const [users, setUsers] = useState([]);
  const [stores, setStores] = useState([]);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState({});
  const [search, setSearch] = useState("");
  const [deleting, setDeleting] = useState(null);

  const load = useCallback(async () => {
    const [uRes, sRes] = await Promise.all([
      fetchWithAuth(`${API_BASE}/admin/users`),
      fetchWithAuth(`${API_BASE}/admin/stores`),
    ]);
    if (uRes.ok) { const d = await uRes.json(); setUsers(d.users || []); }
    if (sRes.ok) { const d = await sRes.json(); setStores(d.stores || []); }
  }, []);

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

  const save = async () => {
    const method = editing === "new" ? "POST" : "PUT";
    const url = editing === "new" ? `${API_BASE}/admin/users` : `${API_BASE}/admin/users/${form.id}`;
    const body = { ...form };
    if (editing !== "new" && !body.password) delete body.password;
    const res = await fetchWithAuth(url, { method, body: JSON.stringify(body) });
    if (res.ok) { showToast("Usuario guardado"); setEditing(null); load(); }
    else { const d = await res.json().catch(() => ({})); showToast(d.message || "Error"); }
  };

  const confirmRemove = async () => {
    if (!deleting) return;
    const res = await fetchWithAuth(`${API_BASE}/admin/users/${deleting.id}`, { method: "DELETE" });
    if (res.ok) { showToast("Usuario eliminado"); setDeleting(null); load(); }
    else { setDeleting(null); }
  };

  const startNew = () => {
    setForm({ username: "", password: "", display_name: "", role: "gerente", store_id: "" });
    setEditing("new");
  };

  const roleOptions = ["admin", "gerente", "kds"];

  const filteredUsers = users.filter((u) => {
    if (!search) return true;
    const s = search.toLowerCase();
    return u.username.toLowerCase().includes(s)
      || u.display_name.toLowerCase().includes(s)
      || (u.role || "").toLowerCase().includes(s)
      || (u.store_name || "").toLowerCase().includes(s);
  });

  return (
    <div>
      <div className="admin-toolbar">
        <h2>Usuarios</h2>
        <SearchBar value={search} onChange={setSearch} placeholder="Buscar por nombre, usuario, rol..." />
        <button className="btn btn-action btn-sm" onClick={startNew}><Icon name="plus" size={14} /> Nuevo usuario</button>
      </div>

      <ConfirmModal
        open={!!deleting}
        title={`Eliminar usuario "${deleting?.display_name || ""}"`}
        message={`Se eliminara el usuario "${deleting?.username || ""}" del sistema.`}
        onConfirm={confirmRemove}
        onCancel={() => setDeleting(null)}
        confirmLabel="Eliminar usuario"
      />

      <AdminModal
        open={!!editing}
        title={editing === "new" ? "Nuevo usuario" : "Editar usuario"}
        onClose={() => setEditing(null)}
        onSave={save}
      >
        <div className="admin-form-grid">
          <FormField label="Usuario" value={form.username} onChange={(v) => setForm({ ...form, username: v })} />
          <FormField label={editing === "new" ? "Contrasena" : "Nueva contrasena (vacio = sin cambio)"} value={form.password || ""} type="password" onChange={(v) => setForm({ ...form, password: v })} />
          <FormField label="Nombre" value={form.display_name} onChange={(v) => setForm({ ...form, display_name: v })} />
          <div className="form-field">
            <label>Rol</label>
            <select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
              {roleOptions.map((r) => <option key={r} value={r}>{ROLES[r]?.label || r}</option>)}
            </select>
          </div>
          <div className="form-field">
            <label>Tienda</label>
            <select value={form.store_id || ""} onChange={(e) => setForm({ ...form, store_id: e.target.value ? Number(e.target.value) : null })}>
              <option value="">Global (sin tienda)</option>
              {stores.map((s) => <option key={s.id} value={s.id}>{s.name} ({s.code})</option>)}
            </select>
          </div>
        </div>
      </AdminModal>

      <table className="admin-table">
        <thead><tr><th>Usuario</th><th>Nombre</th><th>Rol</th><th>Tienda</th><th>Estado</th><th></th></tr></thead>
        <tbody>
          {filteredUsers.map((u) => (
            <tr key={u.id}>
              <td className="mono">{u.username}</td>
              <td>{u.display_name}</td>
              <td><span className="role-chip">{ROLES[u.role]?.label || u.role}</span></td>
              <td>{u.store_name || "Global"}</td>
              <td><span className={`status-dot ${u.is_active ? "active" : "inactive"}`} />{u.is_active ? "Activo" : "Inactivo"}</td>
              <td>
                <button className="icon-btn-sm" onClick={() => { setForm({ ...u }); setEditing(u.id); }}><Icon name="edit" size={14} /></button>
                <button className="icon-btn-sm" style={{ color: "#C2474B" }} onClick={() => setDeleting(u)}><Icon name="trash" size={14} /></button>
              </td>
            </tr>
          ))}
          {filteredUsers.length === 0 && <tr><td colSpan={6} className="empty-cell">{search ? "Sin resultados para la busqueda" : "Sin usuarios"}</td></tr>}
        </tbody>
      </table>
    </div>
  );
};

// ---- Shared ----
const FormField = ({ label, value, onChange, type = "text", placeholder = "" }) => (
  <div className="form-field">
    <label>{label}</label>
    <input type={type} value={value || ""} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />
  </div>
);

const SearchBar = ({ value, onChange, placeholder = "Buscar..." }) => (
  <div className="search-inline">
    <Icon name="search" size={14} />
    <input type="text" placeholder={placeholder} value={value} onChange={(e) => onChange(e.target.value)} />
    {value && <button className="search-clear" onClick={() => onChange("")}><Icon name="x" size={10} /></button>}
  </div>
);

// ============================================
// Modal de confirmacion reutilizable
// ============================================
const ConfirmModal = ({ open, title, message, details, onConfirm, onCancel, confirmLabel = "Eliminar", confirmDanger = true }) => {
  if (!open) return null;

  return (
    <div className="adm-modal-backdrop" style={{ zIndex: 70 }} onClick={(e) => { if (e.target === e.currentTarget) onCancel(); }}>
      <div className="confirm-modal">
        <div className="confirm-modal-icon" style={confirmDanger ? { background: "color-mix(in oklab, var(--danger) 12%, var(--surface))" } : {}}>
          <Icon name={confirmDanger ? "alert" : "check"} size={28} style={{ color: confirmDanger ? "var(--danger)" : "var(--accent)" }} />
        </div>
        <h3 className="confirm-modal-title">{title}</h3>
        <p className="confirm-modal-msg">{message}</p>
        {details && <div className="confirm-modal-details">{details}</div>}
        <div className="confirm-modal-actions">
          <button className="btn btn-cancel" onClick={onCancel}>Cancelar</button>
          <button className={`btn ${confirmDanger ? "btn-danger" : "btn-action"}`} onClick={onConfirm}>
            <Icon name={confirmDanger ? "trash" : "check"} size={14} /> {confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AdminView, AdminModal, FormField, SearchBar, ConfirmModal });
