/* Uleez — Admin screens part 4 : candidatures loueur
 *
 * Les candidatures arrivent du formulaire PUBLIC de la landing (POST /public/lessor-applications).
 * Ce sont des demandes, pas des comptes : rien n'est créé automatiquement. L'admin examine, crée
 * le compte depuis Loueurs → Ajouter, envoie le lien de connexion, puis marque la candidature.
 *
 * ⚠️ Tout ce qui s'affiche ici a été saisi par un inconnu. React échappe le texte ; on n'utilise
 * JAMAIS dangerouslySetInnerHTML sur ces champs.
 */
const { useState: useA4, useEffect: useAE4 } = React;

const APPLICATION_TABS = [
  { id: 'new',       label: 'Nouvelles' },
  { id: 'contacted', label: 'Contactées' },
  { id: 'approved',  label: 'Approuvées' },
  { id: 'rejected',  label: 'Refusées' },
  { id: 'all',       label: 'Toutes' },
];
const APPLICATION_STATUS = {
  new:       { label: 'Nouvelle',   cls: 'blue' },
  contacted: { label: 'Contactée',  cls: 'amber' },
  approved:  { label: 'Approuvée',  cls: 'green' },
  rejected:  { label: 'Refusée',    cls: 'rose' },
};

function AdminApplications() {
  const toast = useToast();
  const [tab, setTab] = useA4('new');
  const [rows, setRows] = useA4([]);
  const [total, setTotal] = useA4(0);
  const [loading, setLoading] = useA4(true);
  const [err, setErr] = useA4(false);
  const [viewing, setViewing] = useA4(null);
  const [note, setNote] = useA4('');
  const [saving, setSaving] = useA4(false);

  const load = () => {
    setLoading(true); setErr(false);
    API.admin.getLessorApplications({ status: tab })
      .then((res) => { setRows(res.items || []); setTotal(res.total || 0); setLoading(false); })
      .catch(() => { setErr(true); setLoading(false); });
  };
  useAE4(() => { load(); }, [tab]);

  const open = (a) => { setViewing(a); setNote(a.adminNote || ''); };
  const setStatus = async (status) => {
    if (!viewing) return;
    setSaving(true);
    try {
      const updated = await API.admin.updateLessorApplication(viewing.id, { status, adminNote: note });
      // Hors de l'onglet courant, la ligne disparaît de la liste (« Nouvelles » → « Contactées »).
      setRows((rs) => (tab === 'all' ? rs.map((x) => (x.id === updated.id ? updated : x)) : rs.filter((x) => x.id !== updated.id)));
      setViewing(null);
      toast({ variant: 'success', title: 'Candidature mise à jour', desc: APPLICATION_STATUS[status].label });
    } catch (ex) {
      toast({ variant: 'error', title: 'Erreur', desc: ex.message });
    } finally { setSaving(false); }
  };

  return (
    <div className="page-wide">
      <div className="toolbar" style={{ marginBottom: 14 }}>
        <div className="chips">
          {APPLICATION_TABS.map((t) => (
            <Chip key={t.id} active={tab === t.id} onClick={() => setTab(t.id)}>{t.label}</Chip>
          ))}
        </div>
        <div className="spacer" />
        <span className="muted" style={{ fontSize: 13 }}>{total} candidature(s)</span>
      </div>

      <Card>
        {loading && <div style={{ padding: 24 }}><Sk w="100%" h={120} r={8} /></div>}
        {err && <div style={{ padding: 48 }}><EmptyState variant="err" title="Impossible de charger les candidatures" /></div>}
        {!loading && !err && (
          <div className="tbl-wrap">
            <table className="tbl">
              <thead><tr>
                <th>Entreprise</th><th>Contact</th><th>Wilaya</th><th>Type</th><th>Flotte</th><th>Reçue le</th><th>Statut</th>
              </tr></thead>
              <tbody>
                {rows.length === 0 && (
                  <tr><td colSpan={7} style={{ textAlign: 'center', padding: 32, color: 'var(--muted)' }}>Aucune candidature</td></tr>
                )}
                {rows.map((a) => (
                  <tr key={a.id} className="clickable" onClick={() => open(a)}>
                    <td><div className="n">{a.businessName}</div></td>
                    <td>
                      <div>{a.contactName}</div>
                      <div className="muted" style={{ fontSize: 12 }}>{a.email}</div>
                    </td>
                    <td className="nowrap">{a.wilaya}</td>
                    <td>{a.type === 'agency' ? 'Agence' : 'Indépendant'}</td>
                    <td>{a.fleetSize != null ? `${a.fleetSize} véh.` : '—'}</td>
                    <td className="nowrap">{a.createdAt ? new Date(a.createdAt).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' }) : '—'}</td>
                    <td><StatusBadge map={APPLICATION_STATUS} value={a.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {viewing && (
        <Modal wide title={viewing.businessName} desc={`${viewing.contactName} · ${viewing.wilaya}`} icon={{ name: 'building', color: 'blue' }} onClose={() => setViewing(null)}
          footer={<>
            <Button variant="secondary" onClick={() => setViewing(null)}>Fermer</Button>
            <Button variant="secondary" icon="phone" loading={saving} onClick={() => setStatus('contacted')}>Marquer contactée</Button>
            <Button variant="danger" icon="ban" loading={saving} onClick={() => setStatus('rejected')}>Refuser</Button>
            <Button variant="primary" icon="check" loading={saving} onClick={() => setStatus('approved')}>Marquer approuvée</Button>
          </>}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
            <div>
              <div className="kv"><span className="k">Contact</span><span className="v">{viewing.contactName}</span></div>
              <div className="kv"><span className="k">E-mail</span><span className="v">{viewing.email}</span></div>
              <div className="kv"><span className="k">Téléphone</span><span className="v">{viewing.phone}</span></div>
              <div className="kv"><span className="k">Wilaya</span><span className="v">{viewing.wilaya}</span></div>
              <div className="kv"><span className="k">Type</span><span className="v">{viewing.type === 'agency' ? 'Agence' : 'Indépendant'}</span></div>
              <div className="kv"><span className="k">Flotte</span><span className="v">{viewing.fleetSize != null ? `${viewing.fleetSize} véhicule(s)` : '—'}</span></div>
              <div className="kv"><span className="k">Langue</span><span className="v">{(viewing.language || 'fr').toUpperCase()}</span></div>
            </div>
            <div>
              <div className="flabel" style={{ marginBottom: 6 }}>Message du candidat</div>
              <div className="muted" style={{ fontSize: 13, whiteSpace: 'pre-wrap', wordBreak: 'break-word', minHeight: 40 }}>
                {viewing.message || 'Aucun message.'}
              </div>
              <div className="flabel" style={{ margin: '14px 0 6px' }}>Note interne</div>
              <textarea className="input" rows={4} maxLength={2000} value={note} onChange={(e) => setNote(e.target.value)}
                placeholder="Suite donnée, date d'appel…" />
            </div>
          </div>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 14 }}>
            Aucun compte n'est créé automatiquement : créez le loueur depuis Loueurs → Ajouter, envoyez-lui son lien de connexion, puis marquez la candidature « approuvée ».
          </div>
        </Modal>
      )}
    </div>
  );
}

Object.assign(window, { AdminApplications });
