// ============================================================================
// public/screens/call-history.jsx — Call History (Phase 5)
// ----------------------------------------------------------------------------
// Paginated table with filters + call detail side panel with transcript.
// ============================================================================

function CallHistoryScreen() {
  const [calls, setCalls]       = React.useState(null);
  const [pagination, setPag]    = React.useState({ page: 1, limit: 25, total: 0, pages: 0 });
  const [stats, setStats]       = React.useState(null);
  const [filters, setFilters]   = React.useState({ search: "", status: "", outcome: "", interest: "", quality: "" });
  const [detail, setDetail]     = React.useState(null); // full call detail object
  const [detailLoading, setDL]  = React.useState(false);

  const load = React.useCallback(async (page = 1) => {
    const params = new URLSearchParams();
    params.set("page", page);
    params.set("limit", 25);
    if (filters.search)   params.set("search", filters.search);
    if (filters.status)   params.set("status", filters.status);
    if (filters.outcome)  params.set("outcome", filters.outcome);
    if (filters.interest) params.set("interest", filters.interest);
    if (filters.quality)  params.set("quality", filters.quality);

    const r = await VoaisAPI.get("/api/calls?" + params.toString());
    if (r.ok && r.data?.ok) {
      setCalls(r.data.calls);
      setPag(r.data.pagination);
    }
  }, [filters]);

  const loadStats = React.useCallback(async () => {
    const r = await VoaisAPI.get("/api/calls/stats");
    if (r.ok && r.data?.ok) setStats(r.data.stats);
  }, []);

  React.useEffect(() => { load(1); loadStats(); }, [load, loadStats]);

  // Open call detail
  const openDetail = async (callId) => {
    setDL(true);
    const r = await VoaisAPI.get("/api/calls/" + callId);
    if (r.ok && r.data?.ok) {
      setDetail({ call: r.data.call, transcript: r.data.transcript, events: r.data.events });
    }
    setDL(false);
  };

  // Retry
  const handleRetry = async (callId) => {
    if (!confirm("Retry this call?")) return;
    const r = await VoaisAPI.post("/api/calls/" + callId + "/retry");
    if (r.ok) { alert("Retry queued."); load(pagination.page); }
    else alert(r.data?.msg || "Retry failed.");
  };

  // Export
  const handleExport = () => {
    const base = (window.VOAIS_API_BASE || "");
    const sess = VoaisAPI.getSession();
    window.open(base + "/api/calls/export?token=" + (sess?.token || ""), "_blank");
  };

  const updateFilter = (key, val) => setFilters(prev => ({ ...prev, [key]: val }));

  if (calls === null) return <DashboardSkeleton/>;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>

      {/* KPI cards */}
      {stats && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 }}>
          <KpiMini label="Calls today" value={stats.today.total}/>
          <KpiMini label="Answered" value={stats.today.answered} color="var(--ok)"/>
          <KpiMini label="Hot leads" value={stats.today.hot_leads} color="var(--accent)"/>
          <KpiMini label="Minutes today" value={stats.today.minutes}/>
          <KpiMini label="7d connect rate" value={stats.week.connect_rate + "%"}/>
          <KpiMini label="Active now" value={stats.active_now} color="var(--warn)"/>
        </div>
      )}

      {/* Filters row */}
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
        <div style={{ position: "relative", flex: 1, minWidth: 180 }}>
          <I.search size={14} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)" }}/>
          <input className="input" placeholder="Search calls..." value={filters.search}
            onChange={e => updateFilter("search", e.target.value)}
            onKeyDown={e => { if (e.key === "Enter") load(1); }}
            style={{ paddingLeft: 32 }}/>
        </div>
        <select className="select" value={filters.status} onChange={e => { updateFilter("status", e.target.value); }} style={{ width: 130 }}>
          <option value="">All status</option>
          <option value="completed">Completed</option>
          <option value="failed">Failed</option>
          <option value="in_progress">In progress</option>
          <option value="initiated">Initiated</option>
        </select>
        <select className="select" value={filters.interest} onChange={e => { updateFilter("interest", e.target.value); }} style={{ width: 130 }}>
          <option value="">All interest</option>
          <option value="interested">Interested</option>
          <option value="not_interested">Not interested</option>
          <option value="unclear">Unclear</option>
          <option value="callback">Callback</option>
        </select>
        <select className="select" value={filters.quality} onChange={e => { updateFilter("quality", e.target.value); }} style={{ width: 110 }}>
          <option value="">All quality</option>
          <option value="hot">Hot</option>
          <option value="warm">Warm</option>
          <option value="cold">Cold</option>
        </select>
        <Btn kind="ghost" size="sm" icon={<I.search size={13}/>} onClick={() => load(1)}>Search</Btn>
        <Btn kind="ghost" size="sm" icon={<I.download size={13}/>} onClick={handleExport}>Export CSV</Btn>
      </div>

      {/* Table */}
      <Card padded={false}>
        <div style={{ overflowX: "auto" }}>
          <table className="data-table" style={{ width: "100%", fontSize: 13 }}>
            <thead>
              <tr>
                <th style={{ paddingLeft: 16 }}>Call</th>
                <th>Number</th>
                <th>Agent</th>
                <th>Status</th>
                <th>Outcome</th>
                <th>Interest</th>
                <th>Score</th>
                <th>Duration</th>
                <th>When</th>
              </tr>
            </thead>
            <tbody>
              {calls.map(c => {
                const statusTone = c.status === "completed" ? "green" : c.status === "failed" ? "red" : c.status === "in_progress" ? "blue" : "gray";
                const qualTone = c.lead_quality === "hot" ? "red" : c.lead_quality === "warm" ? "yellow" : "gray";
                return (
                  <tr key={c.id} onClick={() => openDetail(c.id)} style={{ cursor: "pointer" }}>
                    <td style={{ paddingLeft: 16 }}>
                      <div style={{ fontWeight: 500 }}>{c.code || "—"}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{c.direction}</div>
                    </td>
                    <td>{c.number || "—"}</td>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        {c.agent_gradient && <div style={{ width: 20, height: 20, borderRadius: 6, background: c.agent_gradient, flexShrink: 0 }}/>}
                        <span>{c.agent_name || "—"}</span>
                      </div>
                    </td>
                    <td><Badge tone={statusTone}>{c.status}</Badge></td>
                    <td>{c.outcome || "—"}</td>
                    <td>{c.interest ? <Badge tone={c.interest === "interested" ? "green" : c.interest === "not_interested" ? "red" : "gray"}>{c.interest}</Badge> : "—"}</td>
                    <td>
                      {c.lead_score != null ? (
                        <span style={{ fontWeight: 600, color: c.lead_score >= 80 ? "var(--ok)" : c.lead_score >= 50 ? "var(--warn)" : "var(--ink-3)" }}>
                          {c.lead_score}
                        </span>
                      ) : "—"}
                    </td>
                    <td className="tabular">{c.duration_s ? formatDuration(c.duration_s) : "—"}</td>
                    <td style={{ fontSize: 11, color: "var(--ink-3)" }}>{timeAgo(c.started_at)}</td>
                  </tr>
                );
              })}
              {calls.length === 0 && (
                <tr><td colSpan={9} style={{ textAlign: "center", padding: 32, color: "var(--ink-3)" }}>No calls found.</td></tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {pagination.pages > 1 && (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "12px 16px", borderTop: "1px solid var(--line)" }}>
            <Btn kind="ghost" size="sm" disabled={pagination.page <= 1}
              onClick={() => load(pagination.page - 1)}>Prev</Btn>
            <span style={{ fontSize: 12, color: "var(--ink-3)" }}>
              Page {pagination.page} of {pagination.pages} ({pagination.total} calls)
            </span>
            <Btn kind="ghost" size="sm" disabled={pagination.page >= pagination.pages}
              onClick={() => load(pagination.page + 1)}>Next</Btn>
          </div>
        )}
      </Card>

      {/* Call Detail Drawer */}
      {detail && (
        <CallDetailDrawer detail={detail} loading={detailLoading}
          onClose={() => setDetail(null)}
          onRetry={() => handleRetry(detail.call.id)}/>
      )}
    </div>
  );
}

// ── KPI mini card ───────────────────────────────────────────────────────
function KpiMini({ label, value, color }) {
  return (
    <div style={{ padding: "12px 14px", background: "var(--surface-2)", borderRadius: 10 }}>
      <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{label}</div>
      <div style={{ fontSize: 20, fontWeight: 600, color: color || "var(--ink-1)", marginTop: 2 }} className="tabular">{value}</div>
    </div>
  );
}

// ── Call Detail Drawer ──────────────────────────────────────────────────
function CallDetailDrawer({ detail, loading, onClose, onRetry }) {
  const { call, transcript, events } = detail;
  const [tab, setTab] = React.useState("transcript");

  return (
    <Modal title={`Call ${call.code || call.call_uuid?.slice(0, 12)}`} onClose={onClose} width={640}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>

        {/* Call summary header */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Number</div>
            <div style={{ fontWeight: 500 }}>{call.number || "—"}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Agent</div>
            <div style={{ fontWeight: 500 }}>{call.agent_name || "—"}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Duration</div>
            <div style={{ fontWeight: 500 }}>{call.duration_s ? formatDuration(call.duration_s) : "—"}</div>
          </div>
        </div>

        {/* Badges row */}
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <Badge tone={call.status === "completed" ? "green" : "red"}>{call.status}</Badge>
          {call.outcome && <Badge tone="gray">{call.outcome}</Badge>}
          {call.interest && <Badge tone={call.interest === "interested" ? "green" : "red"}>{call.interest}</Badge>}
          {call.lead_quality && <Badge tone={call.lead_quality === "hot" ? "red" : "yellow"}>{call.lead_quality}</Badge>}
          {call.lead_score != null && <Badge tone="blue">Score: {call.lead_score}</Badge>}
          {call.sentiment && <Badge tone="gray">{call.sentiment}</Badge>}
        </div>

        {/* Summary */}
        {call.summary && (
          <div style={{ padding: "10px 12px", background: "var(--surface-2)", borderRadius: 8, fontSize: 13, lineHeight: 1.6 }}>
            {call.summary}
          </div>
        )}

        {/* Tabs */}
        <Tabs value={tab} onChange={setTab} options={[
          { value: "transcript", label: "Transcript", count: transcript.length },
          { value: "events",     label: "Events",     count: events.length },
          { value: "info",       label: "Details" },
        ]}/>

        {/* Transcript */}
        {tab === "transcript" && (
          <div style={{ maxHeight: 340, overflowY: "auto", display: "flex", flexDirection: "column", gap: 6 }}>
            {transcript.length === 0 && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No transcript available.</div>
            )}
            {transcript.map((t, i) => (
              <div key={i} style={{
                padding: "8px 12px", borderRadius: 10, fontSize: 13, lineHeight: 1.6,
                background: t.role === "agent" ? "var(--accent-soft)" : "var(--surface-2)",
                alignSelf: t.role === "agent" ? "flex-start" : "flex-end",
                maxWidth: "85%",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: t.role === "agent" ? "var(--accent)" : "var(--ink-3)" }}>
                    {t.role === "agent" ? (call.agent_name || "AI") : "Caller"}
                  </span>
                  {t.ts_ms != null && <span style={{ fontSize: 10, color: "var(--ink-3)" }}>{formatDuration(Math.round(t.ts_ms / 1000))}</span>}
                  {t.intent_tag && <Badge tone="blue">{t.intent_tag}</Badge>}
                </div>
                {t.content}
              </div>
            ))}
          </div>
        )}

        {/* Events timeline */}
        {tab === "events" && (
          <div style={{ maxHeight: 340, overflowY: "auto" }}>
            {events.length === 0 && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No events logged.</div>
            )}
            {events.map((ev, i) => (
              <div key={i} style={{ display: "flex", gap: 10, padding: "6px 0", borderBottom: "1px solid var(--line)" }}>
                <div style={{ width: 8, height: 8, borderRadius: "50%", flexShrink: 0, marginTop: 5,
                  background: ev.severity === "error" ? "var(--err)" : ev.severity === "warn" ? "var(--warn)" : "var(--ink-3)" }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{ev.event}</div>
                  {ev.message && <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{ev.message}</div>}
                </div>
                <div style={{ fontSize: 10, color: "var(--ink-3)", flexShrink: 0 }}>
                  {new Date(ev.created_at).toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Details tab */}
        {tab === "info" && (
          <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "6px 14px", fontSize: 13 }}>
            <span style={{ color: "var(--ink-3)" }}>Call UUID:</span><span style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{call.call_uuid}</span>
            <span style={{ color: "var(--ink-3)" }}>Direction:</span><span>{call.direction}</span>
            <span style={{ color: "var(--ink-3)" }}>Mode:</span><span>{call.mode}</span>
            <span style={{ color: "var(--ink-3)" }}>Language:</span><span>{call.language}</span>
            <span style={{ color: "var(--ink-3)" }}>LLM:</span><span>{call.llm_provider} / {call.llm_model || "—"}</span>
            <span style={{ color: "var(--ink-3)" }}>Campaign:</span><span>{call.campaign_name || "—"}</span>
            <span style={{ color: "var(--ink-3)" }}>Contact:</span><span>{call.contact_name || "—"} ({call.contact_phone || "—"})</span>
            <span style={{ color: "var(--ink-3)" }}>Started:</span><span>{call.started_at ? new Date(call.started_at).toLocaleString("en-IN") : "—"}</span>
            <span style={{ color: "var(--ink-3)" }}>Answered:</span><span>{call.answered_at ? new Date(call.answered_at).toLocaleString("en-IN") : "—"}</span>
            <span style={{ color: "var(--ink-3)" }}>Ended:</span><span>{call.ended_at ? new Date(call.ended_at).toLocaleString("en-IN") : "—"}</span>
            <span style={{ color: "var(--ink-3)" }}>Hangup cause:</span><span>{call.hangup_cause || "—"}</span>
            <span style={{ color: "var(--ink-3)" }}>Cost:</span><span>{call.cost_inr != null ? "₹" + Number(call.cost_inr).toFixed(2) : "—"}</span>
            {call.recording_url && <>
              <span style={{ color: "var(--ink-3)" }}>Recording:</span>
              <audio controls src={call.recording_url} style={{ height: 32, width: "100%" }}/>
            </>}
          </div>
        )}

        {/* Actions */}
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 4 }}>
          {(call.status === "failed" || call.status === "completed") && (
            <Btn kind="ghost" size="sm" icon={<I.reply size={13}/>} onClick={onRetry}>Retry call</Btn>
          )}
          <Btn kind="ghost" size="sm" onClick={onClose}>Close</Btn>
        </div>
      </div>
    </Modal>
  );
}


// ── Helpers ──────────────────────────────────────────────────────────────
function formatDuration(sec) {
  if (!sec || sec <= 0) return "0s";
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return m > 0 ? `${m}m ${s}s` : `${s}s`;
}

function timeAgo(dateStr) {
  if (!dateStr) return "—";
  const d = new Date(dateStr);
  const now = Date.now();
  const diff = Math.floor((now - d.getTime()) / 1000);
  if (diff < 60) return "just now";
  if (diff < 3600) return Math.floor(diff / 60) + "m ago";
  if (diff < 86400) return Math.floor(diff / 3600) + "h ago";
  if (diff < 604800) return Math.floor(diff / 86400) + "d ago";
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short" });
}

window.CallHistoryScreen = CallHistoryScreen;
