// Admin (Team) views: gestione Clienti e Utilizzatori
const { useState: useStateA, useEffect: useEffectA } = React;

const API_BASE = window.APP_CONFIG?.API_URL || "/api";

function getToken() {
  return localStorage.getItem("token");
}

async function apiCall(endpoint, options = {}) {
  const token = getToken();
  const res = await fetch(`${API_BASE}${endpoint}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${token}`,
      ...options.headers
    }
  });
  return res.json();
}

// Vista principale Admin - Lista Clienti
function AdminClients({ onOpenClient, config }) {
  const [clients, setClients] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [newOpen, setNewOpen] = useStateA(false);

  const labelPlural = config?.label_client_plural || "Clienti";
  const labelSingular = config?.label_client_singular || "Cliente";

  const loadClients = async () => {
    setLoading(true);
    const data = await apiCall("/clients");
    if (data.success) {
      setClients(data.clients);
    }
    setLoading(false);
  };

  useEffectA(() => {
    loadClients();
  }, []);

  const totalTenants = clients.reduce((s, c) => s + parseInt(c.tenant_count || 0), 0);
  const totalUsers = clients.reduce((s, c) => s + parseInt(c.user_count || 0), 0);

  const handleCreated = () => {
    setNewOpen(false);
    loadClients();
  };

  if (loading) {
    return <div className="panel"><div className="panel-body">Caricamento...</div></div>;
  }

  return (
    <div>
      <div className="stats-grid">
        <div className="stat-card">
          <div className="label">Clienti Attivi</div>
          <div className="value">{clients.filter(c => c.active).length}</div>
          <div className="delta">su piattaforma StockConnect</div>
        </div>
        <div className="stat-card">
          <div className="label">Utenti Totali</div>
          <div className="value">{totalUsers}</div>
        </div>
      </div>

      <div className="toolbar">
        <SectionH>{labelPlural}</SectionH>
        <div className="right">
          <button className="btn btn-primary" onClick={() => setNewOpen(true)}>
            <span className="icon">{Icon.plus}</span>Nuovo {labelSingular}
          </button>
        </div>
      </div>

      <div className="panel">
        {clients.length === 0 ? (
          <div className="panel-body empty">
            <div style={{padding: "40px 20px", textAlign: "center", color: "var(--text-3)"}}>
              Nessun {labelSingular.toLowerCase()} presente. Clicca "Nuovo {labelSingular}" per crearne uno.
            </div>
          </div>
        ) : (
          <table className="data">
            <thead>
              <tr>
                <th>Codice</th>
                <th>Ragione Sociale</th>
                <th>Cod. Gestionale</th>
                <th>Creato</th>
                <th>2FA</th>
                <th>Stato</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {clients.map(c => (
                <tr key={c.id} onClick={() => onOpenClient(c)} style={{cursor: "pointer"}}>
                  <td className="mono">{c.code}</td>
                  <td><strong>{c.name}</strong></td>
                  <td className="mono">{c.gestionale_code || "-"}</td>
                  <td>{new Date(c.created_at).toLocaleDateString("it-CH")}</td>
                  <td>{c.twofa_required ? <Badge type="ok" dot>2FA</Badge> : <Badge type="neutral">no 2FA</Badge>}</td>
                  <td>{c.active ? <Badge type="ok" dot>attivo</Badge> : <Badge type="warn" dot>disattivato</Badge>}</td>
                  <td>
                    <button className="btn btn-secondary btn-sm" onClick={(e) => { e.stopPropagation(); onOpenClient(c); }}>
                      Apri ›
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {newOpen && <NewClientModal onClose={() => setNewOpen(false)} onCreated={handleCreated} config={config} />}
    </div>
  );
}

// Modal Nuovo Cliente
function NewClientModal({ onClose, onCreated, config }) {
  const [form, setForm] = useStateA({
    code: "",
    name: "",
    industry: "",
    email: "",
    phone: "",
    vat_number: "",
    tenant_auto_limit: 3,
    twofa_required: false
  });
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA("");

  const labelSingular = config?.label_client_singular || "Cliente";

  const handleChange = (field, value) => {
    setForm(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async () => {
    if (!form.code || !form.name) {
      setError("Codice e ragione sociale sono obbligatori");
      return;
    }

    setSaving(true);
    setError("");

    const data = await apiCall("/clients", {
      method: "POST",
      body: JSON.stringify(form)
    });

    if (data.success) {
      onCreated(data.client);
    } else {
      setError(data.error || "Errore creazione");
    }
    setSaving(false);
  };

  return (
    <Modal title={`Nuovo ${labelSingular}`} size="lg" onClose={onClose} footer={<>
      <button className="btn btn-secondary" onClick={onClose} disabled={saving}>Annulla</button>
      <button className="btn btn-primary" onClick={handleSubmit} disabled={saving}>
        {saving ? "Creazione..." : `Crea ${labelSingular}`}
      </button>
    </>}>
      {error && (
        <div style={{marginBottom: 16, padding: "10px 12px", background: "rgba(220,53,69,0.1)", border: "1px solid rgba(220,53,69,0.3)", borderRadius: 4, color: "#dc3545", fontSize: 13}}>
          {error}
        </div>
      )}

      <h3 style={{margin: "0 0 8px", fontSize: 13, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em"}}>Dati anagrafici</h3>
      <div className="field-grid">
        <div className="field">
          <label>Ragione sociale *</label>
          <input type="text" value={form.name} onChange={(e) => handleChange("name", e.target.value)} placeholder="es. Atelier Logistica SA"/>
        </div>
        <div className="field">
          <label>Codice *</label>
          <input type="text" value={form.code} onChange={(e) => handleChange("code", e.target.value.toUpperCase())} placeholder="es. ATLOG" className="mono" maxLength={20}/>
        </div>
        <div className="field">
          <label>Settore</label>
          <input type="text" value={form.industry} onChange={(e) => handleChange("industry", e.target.value)} placeholder="es. Logistica"/>
        </div>
        <div className="field">
          <label>Partita IVA / IDE</label>
          <input type="text" value={form.vat_number} onChange={(e) => handleChange("vat_number", e.target.value)} placeholder="CHE-123.456.789"/>
        </div>
        <div className="field">
          <label>Email referente</label>
          <input type="email" value={form.email} onChange={(e) => handleChange("email", e.target.value)}/>
        </div>
        <div className="field">
          <label>Telefono</label>
          <input type="text" value={form.phone} onChange={(e) => handleChange("phone", e.target.value)}/>
        </div>
      </div>

      <div style={{marginTop: 16}}>
        <Checkbox checked={form.twofa_required} onChange={(v) => handleChange("twofa_required", v)} label="Richiedi 2FA per tutti gli utenti"/>
      </div>
    </Modal>
  );
}

// Vista Dettaglio Cliente con lista Utilizzatori
function AdminClientDetail({ client, onBack, onRefresh, config }) {
  const [tenants, setTenants] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [newTenantOpen, setNewTenantOpen] = useStateA(false);
  const [editOpen, setEditOpen] = useStateA(false);

  const loadTenants = async () => {
    setLoading(true);
    const data = await apiCall(`/clients/${client.id}`);
    if (data.success) {
      setTenants(data.tenants || []);
    }
    setLoading(false);
  };

  useEffectA(() => {
    loadTenants();
  }, [client.id]);

  const handleTenantCreated = () => {
    setNewTenantOpen(false);
    loadTenants();
    onRefresh();
  };

  const handleClientUpdated = () => {
    setEditOpen(false);
    onRefresh();
  };

  const canCreateAutonomous = tenants.filter(t => !t.created_by_team).length < client.tenant_auto_limit;

  return (
    <div>
      <div style={{marginBottom: 16}}>
        <button className="btn btn-secondary btn-sm" onClick={onBack}>
          ‹ Torna alla lista
        </button>
      </div>

      <div className="panel mb-16">
        <div className="panel-header">
          <h3>{client.name}</h3>
          <div style={{display: "flex", gap: 8}}>
            <Badge type={client.active ? "ok" : "warn"} dot>{client.active ? "attivo" : "disattivato"}</Badge>
            <button className="btn btn-secondary btn-sm" onClick={() => setEditOpen(true)}>Modifica</button>
          </div>
        </div>
        <div className="panel-body">
          <div style={{display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 16}}>
            <div><strong>Codice:</strong> <span className="mono">{client.code}</span></div>
            <div><strong>Settore:</strong> {client.industry || "-"}</div>
            <div><strong>Email:</strong> {client.email || "-"}</div>
            <div><strong>Telefono:</strong> {client.phone || "-"}</div>
            <div><strong>P.IVA:</strong> {client.vat_number || "-"}</div>
            <div><strong>Limite utilizzatori:</strong> {client.tenant_auto_limit}</div>
            <div><strong>2FA richiesto:</strong> {client.twofa_required ? "Si" : "No"}</div>
            <div><strong>Creato:</strong> {new Date(client.created_at).toLocaleDateString("it-CH")}</div>
          </div>
        </div>
      </div>

      <div className="toolbar">
        <SectionH>Utilizzatori <span className="sub">· {tenants.length} totali</span></SectionH>
        <div className="right">
          <button className="btn btn-primary" onClick={() => setNewTenantOpen(true)}>
            <span className="icon">{Icon.plus}</span>Nuovo Utilizzatore
          </button>
        </div>
      </div>

      <div className="panel">
        {loading ? (
          <div className="panel-body">Caricamento...</div>
        ) : tenants.length === 0 ? (
          <div className="panel-body empty">
            <div style={{padding: "40px 20px", textAlign: "center", color: "var(--text-3)"}}>
              Nessun utilizzatore. Clicca "Nuovo Utilizzatore" per crearne uno.
            </div>
          </div>
        ) : (
          <table className="data">
            <thead>
              <tr>
                <th>Codice</th>
                <th>Nome</th>
                <th>Permessi</th>
                <th>Utenti</th>
                <th>Creato da</th>
                <th>Stato</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {tenants.map(t => (
                <tr key={t.id}>
                  <td className="mono">{t.code}</td>
                  <td><strong>{t.name}</strong></td>
                  <td>
                    <div style={{display: "flex", gap: 4, flexWrap: "wrap"}}>
                      {t.enable_saldi && <Badge type="ok">Saldi</Badge>}
                      {t.enable_movimenti && <Badge type="ok">Movimenti</Badge>}
                    </div>
                  </td>
                  <td>{t.user_count || 0}</td>
                  <td>{t.created_by_team ? <Badge type="info">Team</Badge> : <Badge type="neutral">Cliente</Badge>}</td>
                  <td>{t.active ? <Badge type="ok" dot>attivo</Badge> : <Badge type="warn" dot>disattivo</Badge>}</td>
                  <td>
                    <button className="btn btn-secondary btn-sm">Modifica</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {!canCreateAutonomous && tenants.length > 0 && (
        <div className="twofa-card" style={{marginTop: 16}}>
          <div style={{fontSize: 12.5, color: "var(--text-2)"}}>
            <strong>Nota:</strong> Il cliente ha raggiunto il limite di {client.tenant_auto_limit} utilizzatori creabili in autonomia.
            I prossimi utilizzatori verranno creati da Team (segnati come "Creato da: Team").
          </div>
        </div>
      )}

      {newTenantOpen && (
        <NewTenantModal
          clientId={client.id}
          onClose={() => setNewTenantOpen(false)}
          onCreated={handleTenantCreated}
        />
      )}

      {editOpen && (
        <EditClientModal
          client={client}
          onClose={() => setEditOpen(false)}
          onUpdated={handleClientUpdated}
          config={config}
        />
      )}
    </div>
  );
}

// Modal Nuovo Utilizzatore
function NewTenantModal({ clientId, onClose, onCreated }) {
  const [form, setForm] = useStateA({
    code: "",
    name: "",
    enable_saldi: true,
    enable_movimenti: false
  });
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA("");

  const handleChange = (field, value) => {
    setForm(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async () => {
    if (!form.code || !form.name) {
      setError("Codice e nome sono obbligatori");
      return;
    }

    setSaving(true);
    setError("");

    const data = await apiCall("/tenants", {
      method: "POST",
      body: JSON.stringify({ ...form, client_id: clientId })
    });

    if (data.success) {
      onCreated(data.tenant);
    } else {
      setError(data.error || "Errore creazione");
    }
    setSaving(false);
  };

  return (
    <Modal title="Nuovo Utilizzatore" size="md" onClose={onClose} footer={<>
      <button className="btn btn-secondary" onClick={onClose} disabled={saving}>Annulla</button>
      <button className="btn btn-primary" onClick={handleSubmit} disabled={saving}>
        {saving ? "Creazione..." : "Crea Utilizzatore"}
      </button>
    </>}>
      {error && (
        <div style={{marginBottom: 16, padding: "10px 12px", background: "rgba(220,53,69,0.1)", border: "1px solid rgba(220,53,69,0.3)", borderRadius: 4, color: "#dc3545", fontSize: 13}}>
          {error}
        </div>
      )}

      <div className="field-grid">
        <div className="field">
          <label>Nome *</label>
          <input type="text" value={form.name} onChange={(e) => handleChange("name", e.target.value)} placeholder="es. Frédérique Constant SA"/>
        </div>
        <div className="field">
          <label>Codice *</label>
          <input type="text" value={form.code} onChange={(e) => handleChange("code", e.target.value.toUpperCase())} placeholder="es. FCSA" className="mono" maxLength={20}/>
        </div>
      </div>

      <h3 style={{margin: "22px 0 8px", fontSize: 13, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em"}}>Permessi</h3>
      <div style={{display: "grid", gap: 10}}>
        <Checkbox checked={form.enable_saldi} onChange={(v) => handleChange("enable_saldi", v)} label="Visualizzazione Saldi"/>
        <Checkbox checked={form.enable_movimenti} onChange={(v) => handleChange("enable_movimenti", v)} label="Visualizzazione Movimenti"/>
      </div>
    </Modal>
  );
}

// Modal Modifica Cliente
function EditClientModal({ client, onClose, onUpdated, config }) {
  const [form, setForm] = useStateA({
    name: client.name,
    industry: client.industry || "",
    email: client.email || "",
    phone: client.phone || "",
    vat_number: client.vat_number || "",
    tenant_auto_limit: client.tenant_auto_limit,
    twofa_required: client.twofa_required,
    active: client.active
  });
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA("");

  const labelSingular = config?.label_client_singular || "Cliente";

  const handleChange = (field, value) => {
    setForm(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async () => {
    setSaving(true);
    setError("");

    const data = await apiCall(`/clients/${client.id}`, {
      method: "PUT",
      body: JSON.stringify(form)
    });

    if (data.success) {
      onUpdated(data.client);
    } else {
      setError(data.error || "Errore aggiornamento");
    }
    setSaving(false);
  };

  return (
    <Modal title={`Modifica ${labelSingular}`} size="lg" onClose={onClose} footer={<>
      <button className="btn btn-secondary" onClick={onClose} disabled={saving}>Annulla</button>
      <button className="btn btn-primary" onClick={handleSubmit} disabled={saving}>
        {saving ? "Salvataggio..." : "Salva"}
      </button>
    </>}>
      {error && (
        <div style={{marginBottom: 16, padding: "10px 12px", background: "rgba(220,53,69,0.1)", border: "1px solid rgba(220,53,69,0.3)", borderRadius: 4, color: "#dc3545", fontSize: 13}}>
          {error}
        </div>
      )}

      <div className="field-grid">
        <div className="field">
          <label>Ragione sociale</label>
          <input type="text" value={form.name} onChange={(e) => handleChange("name", e.target.value)}/>
        </div>
        <div className="field">
          <label>Codice</label>
          <input type="text" value={client.code} disabled className="mono"/>
        </div>
        <div className="field">
          <label>Settore</label>
          <input type="text" value={form.industry} onChange={(e) => handleChange("industry", e.target.value)}/>
        </div>
        <div className="field">
          <label>P.IVA / IDE</label>
          <input type="text" value={form.vat_number} onChange={(e) => handleChange("vat_number", e.target.value)}/>
        </div>
        <div className="field">
          <label>Email</label>
          <input type="email" value={form.email} onChange={(e) => handleChange("email", e.target.value)}/>
        </div>
        <div className="field">
          <label>Telefono</label>
          <input type="text" value={form.phone} onChange={(e) => handleChange("phone", e.target.value)}/>
        </div>
        <div className="field">
          <label>Limite utilizzatori autonomi</label>
          <select value={form.tenant_auto_limit} onChange={(e) => handleChange("tenant_auto_limit", parseInt(e.target.value))}>
            <option value="3">3</option>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="999">Illimitato</option>
          </select>
        </div>
      </div>

      <div style={{marginTop: 16, display: "grid", gap: 10}}>
        <Checkbox checked={form.twofa_required} onChange={(v) => handleChange("twofa_required", v)} label="Richiedi 2FA per tutti gli utenti"/>
        <Checkbox checked={form.active} onChange={(v) => handleChange("active", v)} label="Cliente attivo"/>
      </div>
    </Modal>
  );
}

// Esporta per uso globale
window.AdminClients = AdminClients;
window.AdminClientDetail = AdminClientDetail;
