// ============================================================
//  Polycall / SOPHON - Onglet Historique (dossier client)
//  Affiche : appels passes + commentaires, notes de suivi,
//  ajout de note, et edition des coordonnees de reference.
// ============================================================

function fmtDate(iso) {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    return d.toLocaleDateString("fr-FR", { day: "2-digit", month: "short", year: "numeric" })
      + " a " + d.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" });
  } catch (e) { return iso; }
}

function ClientHistory({ fiche, op, onClientUpdated }) {
  const [loading, setLoading] = React.useState(true);
  const [data, setData] = React.useState(null);        // { client, fiches, notes }
  const [err, setErr] = React.useState("");
  const [noteText, setNoteText] = React.useState("");
  const [savingNote, setSavingNote] = React.useState(false);
  const [editMode, setEditMode] = React.useState(false);
  const [form, setForm] = React.useState(null);
  const [savingClient, setSavingClient] = React.useState(false);

  // Retrouve le client lie a cette fiche (par n° client ou telephone) dans la liste de l'operation.
  const linkedClient = React.useMemo(() => {
    if (!op || !op.clients) return null;
    const num = (fiche.fields.clientNum || "").trim();
    const tel = (fiche.fields.tel || "").trim();
    return op.clients.find((c) => (num && c.num === num) || (tel && c.tel === tel)) || null;
  }, [op, fiche.fields.clientNum, fiche.fields.tel]);

  React.useEffect(() => {
    let alive = true;
    (async () => {
      if (!linkedClient || !linkedClient.id) { setLoading(false); return; }
      setLoading(true); setErr("");
      try {
        const res = await PolycallAPI.clientHistory(linkedClient.id);
        if (alive) { setData(res); setForm(res ? { ...res.client } : null); }
      } catch (e) {
        if (alive) setErr(e.message || "Impossible de charger l'historique.");
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [linkedClient]);

  async function addNote() {
    const body = noteText.trim();
    if (!body || !linkedClient) return;
    setSavingNote(true);
    try {
      const r = await PolycallAPI.addClientNote(linkedClient.id, body);
      setData((d) => ({ ...d, notes: [{ id: r.id, body, authorName: r.authorName, createdAt: r.createdAt }, ...(d.notes || [])] }));
      setNoteText("");
    } catch (e) {
      setErr(e.message || "Echec de l'ajout de la note.");
    } finally {
      setSavingNote(false);
    }
  }

  async function saveClient() {
    if (!linkedClient || !form) return;
    setSavingClient(true);
    try {
      await PolycallAPI.updateClient(linkedClient.id, form);
      setData((d) => ({ ...d, client: { ...form } }));
      setEditMode(false);
      if (onClientUpdated) onClientUpdated(form);
    } catch (e) {
      setErr(e.message || "Echec de la mise a jour.");
    } finally {
      setSavingClient(false);
    }
  }

  // --- Pas de client identifie : message d'accueil ---
  if (!linkedClient) {
    return (
      <div style={{ maxWidth: 900, padding: "8px 0" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--ink-soft)", fontSize: 14, padding: "20px 0" }}>
          <I.history s={20} style={{ color: "var(--ink-faint)" }} />
          <div>
            <b style={{ display: "block", color: "var(--ink)" }}>Aucun client identifie</b>
            Renseignez le n° client ou le telephone, ou selectionnez un client existant pour voir son historique.
          </div>
        </div>
      </div>
    );
  }

  if (loading) return <div style={{ padding: 20, color: "var(--ink-soft)" }}>Chargement de l'historique…</div>;

  const cli = (data && data.client) || linkedClient;
  const fiches = (data && data.fiches) || [];
  const notes = (data && data.notes) || [];

  return (
    <div style={{ maxWidth: 980, padding: "4px 0", display: "grid", gap: 18 }}>
      {err && <div className="login-err" style={{ marginBottom: 0 }}><I.info s={15} /> {err}</div>}

      {/* ---- En-tete client + edition coordonnees ---- */}
      <div style={{ border: "1px solid var(--line)", borderRadius: 12, padding: 16, background: "var(--surface)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: editMode ? 14 : 0 }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>
              {cli.societe || [cli.civilite, cli.prenom, cli.nom].filter(Boolean).join(" ") || "Client"}
            </div>
            {!editMode && (
              <div style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 4, display: "flex", gap: 14, flexWrap: "wrap" }}>
                {cli.num && <span>N° {cli.num}</span>}
                {cli.tel && <span><I.phone s={12} /> {cli.tel}</span>}
                {cli.email && <span><I.mail s={12} /> {cli.email}</span>}
                {cli.ville && <span>{cli.cp} {cli.ville}</span>}
              </div>
            )}
          </div>
          {!editMode
            ? <button className="iconbtn sm" title="Modifier les coordonnees" onClick={() => { setForm({ ...cli }); setEditMode(true); }}><I.edit s={16} /></button>
            : <div style={{ display: "flex", gap: 8 }}>
                <button className="acct-item" onClick={() => setEditMode(false)} style={{ padding: "6px 12px" }}>Annuler</button>
                <button className="acct-item" onClick={saveClient} disabled={savingClient} style={{ padding: "6px 12px", background: "var(--solid)", color: "var(--on-solid)" }}>{savingClient ? "…" : "Enregistrer"}</button>
              </div>}
        </div>

        {editMode && form && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <EditCell label="Nom" value={form.nom} onChange={(v) => setForm({ ...form, nom: v })} />
            <EditCell label="Prenom" value={form.prenom} onChange={(v) => setForm({ ...form, prenom: v })} />
            <EditCell label="Societe" value={form.societe} onChange={(v) => setForm({ ...form, societe: v })} />
            <EditCell label="N° client" value={form.num} onChange={(v) => setForm({ ...form, num: v })} />
            <EditCell label="Telephone" value={form.tel} onChange={(v) => setForm({ ...form, tel: v })} />
            <EditCell label="E-mail" value={form.email} onChange={(v) => setForm({ ...form, email: v })} />
            <EditCell label="Adresse" value={form.adresse} onChange={(v) => setForm({ ...form, adresse: v })} />
            <EditCell label="Code postal" value={form.cp} onChange={(v) => setForm({ ...form, cp: v })} />
            <EditCell label="Ville" value={form.ville} onChange={(v) => setForm({ ...form, ville: v })} />
          </div>
        )}
      </div>

      {/* ---- Journal de suivi : ajouter une note ---- */}
      <div>
        <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)", marginBottom: 8, display: "flex", alignItems: "center", gap: 7 }}>
          <I.edit s={15} /> Journal de suivi
        </div>
        <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
          <textarea value={noteText} onChange={(e) => setNoteText(e.target.value)}
            placeholder="Ajouter un commentaire de suivi (rappel, contexte, suite a donner…)"
            rows={2}
            style={{ flex: 1, padding: "10px 12px", borderRadius: 9, border: "1px solid var(--line-strong)", background: "var(--surface)", color: "var(--ink)", fontSize: 13.5, resize: "vertical", fontFamily: "inherit" }} />
          <button className="acct-item" onClick={addNote} disabled={savingNote || !noteText.trim()}
            style={{ alignSelf: "flex-start", padding: "10px 16px", background: "var(--solid)", color: "var(--on-solid)" }}>
            {savingNote ? "…" : "Ajouter"}
          </button>
        </div>

        {notes.length === 0
          ? <div style={{ fontSize: 12.5, color: "var(--ink-faint)", paddingBottom: 8 }}>Aucune note de suivi pour ce client.</div>
          : <div style={{ display: "grid", gap: 8 }}>
              {notes.map((n) => (
                <div key={n.id} style={{ border: "1px solid var(--line)", borderRadius: 9, padding: "10px 12px", background: "var(--surface)" }}>
                  <div style={{ fontSize: 13.5, color: "var(--ink)", whiteSpace: "pre-wrap" }}>{n.body}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-faint)", marginTop: 6 }}>
                    {n.authorName || "—"} · {fmtDate(n.createdAt)}
                  </div>
                </div>
              ))}
            </div>}
      </div>

      {/* ---- Appels passes ---- */}
      <div>
        <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)", marginBottom: 8, display: "flex", alignItems: "center", gap: 7 }}>
          <I.phone s={15} /> Appels precedents <span style={{ color: "var(--ink-faint)", fontWeight: 500 }}>({fiches.length})</span>
        </div>
        {fiches.length === 0
          ? <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>Aucun appel precedent enregistre.</div>
          : <div style={{ display: "grid", gap: 8 }}>
              {fiches.map((f) => {
                const ch = (findChannel(f.canal) || findChannel(DEFAULT_CHANNEL));
                const code = f.conclusion ? findCode(op.codes, f.conclusion.code) : null;
                return (
                  <div key={f.id} style={{ border: "1px solid var(--line)", borderRadius: 9, padding: "10px 12px", background: "var(--surface)" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12.5 }}>
                        <span style={{ fontWeight: 600, color: f.type === "entrant" ? "#2a6fdb" : "#6c6764" }}>
                          {f.type === "entrant" ? "Entrant" : "Sortant"}
                        </span>
                        <span style={{ color: ch.color, fontWeight: 600 }}>{ch.label}</span>
                        {code && <span className={"badge tone-" + (code.tone || "neutral")}>{code.label}</span>}
                      </div>
                      <span style={{ fontSize: 11, color: "var(--ink-faint)" }}>
                        {fmtDate(f.qualifiedFull || f.createdAt)}{f.agentName ? " · " + f.agentName : ""}
                      </span>
                    </div>
                    {(f.fields.motif || f.fields.commentaire) && (
                      <div style={{ marginTop: 8, fontSize: 12.5, color: "var(--ink-soft)", display: "grid", gap: 3 }}>
                        {f.fields.motif && <div><b style={{ color: "var(--ink)" }}>Motif :</b> {f.fields.motif}</div>}
                        {f.fields.commentaire && <div><b style={{ color: "var(--ink)" }}>Commentaire :</b> {f.fields.commentaire}</div>}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>}
      </div>
    </div>
  );
}

function EditCell({ label, value, onChange }) {
  return (
    <label style={{ display: "block" }}>
      <span style={{ display: "block", fontSize: 11, fontWeight: 600, color: "var(--ink-faint)", marginBottom: 4, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</span>
      <input value={value || ""} onChange={(e) => onChange(e.target.value)}
        style={{ width: "100%", padding: "8px 11px", borderRadius: 8, border: "1px solid var(--line-strong)", background: "var(--surface)", color: "var(--ink)", fontSize: 13.5, boxSizing: "border-box" }} />
    </label>
  );
}

Object.assign(window, { ClientHistory });
