// components/home.jsx — HomeTab: Quick Action bar, health/budget/queue cards, recent activity.
// Depends on: React (useState, useEffect, useCallback), Card, StatusBadge, CostBar, get, post

// ── useQuickDo — shared submit logic ─────────────────────────

function useQuickDo({ projectId, onCreated }) {
  const [task, setTask] = useState("");
  const [tool, setTool] = useState("auto");
  const [submitting, setSubmitting] = useState(false);
  const [feedback, setFeedback] = useState(null);

  const submit = async () => {
    if (!task.trim() || submitting) return;
    setSubmitting(true);
    setFeedback(null);
    const payload = { task: task.trim() };
    if (projectId) payload.project_id = projectId;
    if (tool !== "auto") payload.tool = tool;
    try {
      const r = await post("/dashboard/tickets", payload);
      if (r?.id) {
        const toolInfo = r.assigned_tool ? ` -> ${r.assigned_tool.tool}` : "";
        setFeedback({ ok: true, text: `${r.id} created${toolInfo}` });
        setTask("");
        if (onCreated) onCreated(r);
      } else {
        setFeedback({ ok: false, text: "Failed to create ticket" });
      }
    } catch (e) {
      setFeedback({ ok: false, text: String(e) });
    }
    setSubmitting(false);
    setTimeout(() => setFeedback(null), 4000);
  };

  const onKey = (e) => { if (e.key === "Enter") submit(); };
  const canSubmit = task.trim() && !submitting;
  return { task, setTask, tool, setTool, submitting, feedback, submit, onKey, canSubmit };
}

// ── QuickDoFeedback — feedback text ──────────────────────────

function QuickDoFeedback({ feedback, className }) {
  if (!feedback) return null;
  const color = feedback.ok ? "text-emerald-600" : "text-red-500";
  return <span className={`${color} ${className || "text-xs"}`}>{feedback.text}</span>;
}

// ── QuickDoCompact — inline version for Tasks tab ────────────

function QuickDoCompact({ projectId, onCreated }) {
  const q = useQuickDo({ projectId, onCreated });
  return (
    <div className="flex gap-2 items-center">
      <input value={q.task} onChange={e => q.setTask(e.target.value)} onKeyDown={q.onKey}
        placeholder="Quick task..." className="flex-1 px-3 py-1.5 border rounded text-sm" />
      <select value={q.tool} onChange={e => q.setTool(e.target.value)}
        className="px-2 py-1.5 border rounded text-sm text-gray-600">
        <option value="auto">Auto</option>
        <option value="aider">Aider</option>
        <option value="claude-code">Claude Code</option>
        <option value="human">Human</option>
      </select>
      <button onClick={q.submit} disabled={!q.canSubmit}
        className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50 whitespace-nowrap">
        {q.submitting ? "..." : "Go"}
      </button>
      <QuickDoFeedback feedback={q.feedback} />
    </div>
  );
}

// ── QuickDo — full version with gradient card ────────────────

function QuickDo({ projectId, onCreated, compact }) {
  if (compact) return <QuickDoCompact projectId={projectId} onCreated={onCreated} />;

  const q = useQuickDo({ projectId, onCreated });
  return (
    <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-5">
      <h3 className="text-sm font-semibold text-blue-900 mb-3">Quick Action</h3>
      <div className="flex gap-3 items-center">
        <input value={q.task} onChange={e => q.setTask(e.target.value)} onKeyDown={q.onKey}
          placeholder="What to do?  e.g. fix crash in /health endpoint"
          className="flex-1 px-4 py-2.5 border border-blue-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-300 focus:outline-none" autoFocus />
        <select value={q.tool} onChange={e => q.setTool(e.target.value)}
          className="px-3 py-2.5 border border-blue-200 rounded-lg text-sm text-gray-600">
          <option value="auto">Tool: Auto</option>
          <option value="aider">Aider</option>
          <option value="claude-code">Claude Code</option>
          <option value="human">Human</option>
          <option value="windsurf">Windsurf</option>
          <option value="cursor">Cursor</option>
        </select>
        <button onClick={q.submit} disabled={!q.canSubmit}
          className="px-5 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 whitespace-nowrap">
          {q.submitting ? "Creating..." : "Go"}
        </button>
      </div>
      <QuickDoFeedback feedback={q.feedback} className="mt-2 text-sm" />
    </div>
  );
}

// ── HealthCard ────────────────────────────────────────────────

function HealthCard({ health, connected }) {
  const checks = health?.checks || {};
  const total = Object.keys(checks).length;
  const ok = Object.values(checks).filter(v => v === true || v?.status === "ok").length;
  const alerts = total - ok;
  return (
    <div className="bg-white rounded-lg border p-4">
      <h4 className="text-xs font-medium text-gray-500 mb-2">Health</h4>
      <div className="flex items-center gap-2 mb-1">
        <span className={`text-lg font-bold ${connected ? "text-emerald-600" : "text-red-500"}`}>
          {connected ? "✅" : "❌"}
        </span>
        <span className="text-sm font-medium text-gray-900">{connected ? "All OK" : "Disconnected"}</span>
      </div>
      <div className="text-xs text-gray-500">{ok}/{total} checks</div>
      {alerts > 0 && <div className="text-xs text-red-500 mt-1">{alerts} alert{alerts > 1 ? "s" : ""}</div>}
    </div>
  );
}

// ── BudgetMiniCard ───────────────────────────────────────────

function BudgetMiniCard({ budget, costs }) {
  const dailyUsed = costs?.daily_total_usd || 0;
  const monthlyUsed = costs?.monthly_total_usd || 0;
  const monthlyLimit = budget?.monthly_limit_usd || 60;
  const remaining = monthlyLimit - monthlyUsed;
  return (
    <div className="bg-white rounded-lg border p-4">
      <h4 className="text-xs font-medium text-gray-500 mb-2">Budget</h4>
      <div className="space-y-1">
        <div className="flex justify-between">
          <span className="text-xs text-gray-500">Today</span>
          <span className="text-sm font-mono font-bold text-gray-900">${dailyUsed.toFixed(2)}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-xs text-gray-500">Month</span>
          <span className="text-sm font-mono font-bold text-gray-900">${monthlyUsed.toFixed(2)}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-xs text-gray-500">Remaining</span>
          <span className={`text-sm font-mono font-bold ${remaining > 10 ? "text-emerald-600" : "text-amber-600"}`}>
            ${remaining.toFixed(0)}
          </span>
        </div>
      </div>
    </div>
  );
}

// ── QueueMiniCard ────────────────────────────────────────────

function QueueMiniCard() {
  const [queue, setQueue] = useState(null);

  useEffect(() => {
    const load = async () => {
      const data = await get("/dashboard/tools/queue");
      if (data) setQueue(data);
    };
    load();
    const timer = setInterval(load, 10000);
    return () => clearInterval(timer);
  }, []);

  const qs = queue?.queue_size || 0;
  const running = (queue?.by_status?.running) || 0;
  const done = (queue?.by_status?.done) || 0;
  return (
    <div className="bg-white rounded-lg border p-4">
      <h4 className="text-xs font-medium text-gray-500 mb-2">Queue</h4>
      <div className="space-y-1">
        <div className="flex justify-between">
          <span className="text-xs text-gray-500">Running</span>
          <span className="text-sm font-bold text-gray-900">{running}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-xs text-gray-500">Queued</span>
          <span className="text-sm font-bold text-gray-900">{qs}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-xs text-gray-500">Done</span>
          <span className="text-sm font-bold text-emerald-600">{done}</span>
        </div>
      </div>
    </div>
  );
}

// ── RecentActivity helpers ───────────────────────────────────

const _JOB_ICONS = { done: "ok", failed: "x", running: ">", queued: "o" };

function _jobIcon(status) { return _JOB_ICONS[status] || "?"; }

function _fmtTime(ts) {
  if (!ts) return "";
  const ms = (typeof ts === "number" && ts < 1e12) ? ts * 1000 : ts;
  return new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

function _ticketToEvent(t) {
  return {
    ts: t.created_at || 0,
    icon: "T",
    text: `${t.id?.slice(0, 12) || "?"} "${t.title || t.task || "?"}"`,
    sub: t.status,
  };
}

function _jobToEvent(j) {
  return {
    ts: j.started_at || j.created_at || 0,
    icon: _jobIcon(j.status),
    text: `${j.tool || "?"} ${j.status} ${j.ticket_id?.slice(0, 12) || ""}`,
    sub: j.duration_s > 0 ? `${j.duration_s}s` : "",
  };
}

// ── ActivityRow ──────────────────────────────────────────────

function ActivityRow({ event }) {
  return (
    <div className="flex items-center gap-3 text-sm">
      <span className="text-xs text-gray-400 w-12 text-right font-mono">{_fmtTime(event.ts)}</span>
      <span className="w-4 text-center">{event.icon}</span>
      <span className="text-gray-700 truncate flex-1">{event.text}</span>
      {event.sub && <span className="text-xs text-gray-400">{event.sub}</span>}
    </div>
  );
}

// ── RecentActivity ───────────────────────────────────────────

function RecentActivity() {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    const load = async () => {
      const [ticketData, jobData] = await Promise.all([
        get("/dashboard/tickets?limit=10"),
        get("/dashboard/tools/queue"),
      ]);
      const tickets = (ticketData?.tickets || []).map(_ticketToEvent);
      const jobs = (jobData?.recent_jobs || []).map(_jobToEvent);
      const merged = [...tickets, ...jobs].sort((a, b) => b.ts - a.ts).slice(0, 10);
      setEvents(merged);
    };
    load();
    const timer = setInterval(load, 10000);
    return () => clearInterval(timer);
  }, []);

  return (
    <Card title="Recent Activity">
      {events.length === 0 ? (
        <p className="text-sm text-gray-400">No recent activity. Use Quick Action above to start.</p>
      ) : (
        <div className="space-y-1.5">
          {events.map((e, i) => <ActivityRow key={`${e.ts}-${i}`} event={e} />)}
        </div>
      )}
    </Card>
  );
}

// ── HomeTab (main) ───────────────────────────────────────────

function HomeTab({ health, connected, budget, costs }) {
  return (
    <div className="space-y-6">
      <QuickDo />
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <HealthCard health={health} connected={connected} />
        <BudgetMiniCard budget={budget} costs={costs} />
        <QueueMiniCard />
      </div>
      <RecentActivity />
    </div>
  );
}
