// ============================================================================
// public/features/tasks/tasks.jsx — Tasks dashboard (replaces Flow Builder)
// ----------------------------------------------------------------------------
// One place to see every task across all agents: what the task collects, which
// AI/agent it's attached to, the API endpoint it calls, and — per run — the
// exact request sent, the data collected, and the response received.
// Editing a task still lives in the agent editor's Tasks tab.
// ============================================================================

function tasksHost(url) { try { return new URL(url).host; } catch { return url || "—"; } }
function tasksFmtTime(s) { if (!s) return "—"; try { return new Date(s).toLocaleString("en-IN", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }); } catch { return s; } }
function tasksStatusTone(s) { return s === "delivered" ? "green" : s === "failed" ? "red" : s === "skipped" ? "yellow" : "gray"; }

function TasksScreen({ go }) {
  const [tasks, setTasks]       = React.useState(null);
  const [runs, setRuns]         = React.useState([]);
  const [filterTask, setFilter] = React.useState(null);   // task_id | null
  const [expanded, setExpanded] = React.useState(null);   // run id
  const [error, setError]       = React.useState(null);

  const loadTasks = React.useCallback(() => {
    VoaisAPI.get("/api/tasks").then((r) => {
      if (r.ok && r.data?.ok) setTasks(r.data.tasks || []);
      else setError(r.data?.msg || "Failed to load tasks.");
    });
  }, []);
  const loadRuns = React.useCallback((taskId) => {
    const q = taskId ? `?task_id=${taskId}&limit=100` : "?limit=100";
    VoaisAPI.get("/api/tasks/runs" + q).then((r) => { if (r.ok && r.data?.ok) setRuns(r.data.runs || []); });
  }, []);
  React.useEffect(() => { loadTasks(); }, [loadTasks]);
  React.useEffect(() => { loadRuns(filterTask); setExpanded(null); }, [filterTask, loadRuns]);

  if (tasks === null && !error) return <DashboardSkeleton/>;

  const filteredTaskName = filterTask ? (tasks.find((t) => t.id === filterTask) || {}).name : null;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Badge tone="blue" dot>{tasks?.length || 0} tasks</Badge>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>
          Data your agents collect on calls, and the API requests they fire afterward.
        </div>
      </div>

      {error && <div className="auth-banner err"><I.alert size={14}/><span>{error}</span></div>}

      {tasks && tasks.length === 0 && !error && (
        <Card>
          <div style={{ padding: "40px 24px", textAlign: "center", maxWidth: 560, margin: "0 auto" }}>
            <div style={{ width: 64, height: 64, borderRadius: 16, margin: "0 auto 18px", display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)" }}>
              <I.tasks size={28}/>
            </div>
            <h2 style={{ fontSize: 20, fontWeight: 600, margin: "8px 0 10px" }}>No tasks yet</h2>
            <p style={{ color: "var(--ink-3)", fontSize: 13.5, lineHeight: 1.6, margin: "0 0 18px" }}>
              A task lets an agent collect specific data on a call (name, booking ID, a new time…) and, after the call,
              POST it to your API. Open an agent → <b>Tasks</b> to create one.
            </p>
            <Btn kind="primary" icon={<I.agents size={14}/>} onClick={() => go && go("agents")}>Go to Agents</Btn>
          </div>
        </Card>
      )}

      {/* Task cards */}
      {tasks && tasks.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gap: "var(--gap-grid)" }}>
          {tasks.map((t) => (
            <Card key={t.id}>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <div style={{ fontSize: 15, fontWeight: 600 }}>{t.name}</div>
                  {!t.active && <Badge tone="gray">inactive</Badge>}
                  <div style={{ flex: 1 }}/>
                  <Btn kind="ghost" size="sm" onClick={() => go && go("agent_edit:" + t.agent_id)}>Configure</Btn>
                </div>
                {t.description && <div style={{ fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5 }}>{t.description}</div>}

                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
                  <Badge tone="blue"><I.agents size={11}/> {t.agent_name || "—"}</Badge>
                  {t.agent_provider && <Badge tone="gray">{t.agent_provider}</Badge>}
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "4px 10px", fontSize: 12 }}>
                  <span style={{ color: "var(--ink-3)" }}>Collects</span>
                  <span>{(t.fields || []).map((f) => f.key + (f.required ? "*" : "")).join(", ") || "—"}</span>
                  <span style={{ color: "var(--ink-3)" }}>API</span>
                  <span style={{ fontFamily: "var(--mono, monospace)" }}>{t.api_method} {tasksHost(t.api_url)}{t.auth_mode !== "none" ? " · auth" : ""}</span>
                </div>

                <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 2 }}>
                  <Badge tone="green">{t.runs_delivered} delivered</Badge>
                  {t.runs_failed > 0 && <Badge tone="red">{t.runs_failed} failed</Badge>}
                  {t.runs_skipped > 0 && <Badge tone="yellow">{t.runs_skipped} skipped</Badge>}
                  <div style={{ flex: 1 }}/>
                  <Btn kind="ghost" size="sm" onClick={() => setFilter(filterTask === t.id ? null : t.id)}>
                    {filterTask === t.id ? "Showing runs" : "View runs"}
                  </Btn>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* Runs log */}
      {tasks && tasks.length > 0 && (
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Task runs</div>
            {filteredTaskName && <Badge tone="blue">{filteredTaskName} <span style={{ cursor: "pointer", marginLeft: 4 }} onClick={() => setFilter(null)}>✕</span></Badge>}
            <div style={{ flex: 1 }}/>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{runs.length} shown</div>
          </div>

          {!runs.length ? (
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", padding: "16px 0" }}>
              No runs yet — they appear here after calls where a task collects data.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column" }}>
              {runs.map((r) => (
                <div key={r.id} style={{ borderTop: "1px solid var(--line)" }}>
                  <div onClick={() => setExpanded((e) => e === r.id ? null : r.id)}
                    style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 2px", cursor: "pointer", fontSize: 12.5 }}>
                    <Badge tone={tasksStatusTone(r.status)}>{r.status}</Badge>
                    <span style={{ fontWeight: 600 }}>{r.task_name || r.task_key}</span>
                    <span style={{ color: "var(--ink-3)" }}>{r.agent_name}</span>
                    <div style={{ flex: 1 }}/>
                    {r.last_status_code != null && <span style={{ color: "var(--ink-3)" }}>HTTP {r.last_status_code}</span>}
                    <span style={{ color: "var(--ink-3)", minWidth: 120, textAlign: "right" }}>{tasksFmtTime(r.created_at)}</span>
                    <I.chevD size={13} style={{ color: "var(--ink-3)", transform: expanded === r.id ? "rotate(180deg)" : "none", transition: "transform .15s" }}/>
                  </div>
                  {expanded === r.id && <RunDetail run={r}/>}
                </div>
              ))}
            </div>
          )}
        </Card>
      )}
    </div>
  );
}

function RunDetail({ run }) {
  const block = (label, node) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>{label}</div>
      {node}
    </div>
  );
  const pre = (obj) => (
    <pre style={{ margin: 0, fontSize: 11.5, lineHeight: 1.5, background: "var(--surface-2)", borderRadius: 8, padding: 10, overflowX: "auto", fontFamily: "var(--mono, monospace)" }}>
      {typeof obj === "string" ? obj : JSON.stringify(obj || {}, null, 2)}
    </pre>
  );
  return (
    <div style={{ padding: "6px 2px 16px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
      {block("Connected AI", (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <Badge tone="blue"><I.agents size={11}/> {run.agent_name || "—"}</Badge>
          {run.agent_provider && <Badge tone="gray">{run.agent_provider}</Badge>}
          {run.agent_model && <Badge tone="gray">{run.agent_model}</Badge>}
        </div>
      ))}
      {block("Outcome", (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", fontSize: 12 }}>
          <Badge tone={tasksStatusTone(run.status)}>{run.status}</Badge>
          {run.last_status_code != null && <Badge tone="gray">HTTP {run.last_status_code}</Badge>}
          {run.attempts > 1 && <Badge tone="gray">{run.attempts} attempts</Badge>}
          {run.error && <span style={{ color: "var(--err)" }}>{run.error}</span>}
        </div>
      ))}
      {block("Collected data", pre(run.collected))}
      {block("API request", (
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ fontSize: 11.5, fontFamily: "var(--mono, monospace)", color: "var(--ink-2)", wordBreak: "break-all" }}>
            {run.request_method || "POST"} {run.request_url || "—"}
          </div>
          {pre(run.request)}
        </div>
      ))}
      <div style={{ gridColumn: "1 / -1" }}>
        {block("Response", pre(run.last_response || "(no response body)"))}
      </div>
    </div>
  );
}

window.TasksScreen = TasksScreen;
