"use client";

import { useEffect, useState } from "react";

interface BotSession {
  id: string;
  threadTs: string;
  channel: string;
  model: string;
  provider: string;
  summary: string | null;
  persistUntil: string | null;
  totalCost: number;
  messageCount: number;
  createdAt: string;
  lastActivity: string;
  containerName: string | null;
}

function timeAgo(date: string) {
  const seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
  if (seconds < 60) return "just now";
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
  return `${Math.floor(seconds / 86400)}d ago`;
}

export default function SessionsPage() {
  const [sessions, setSessions] = useState<BotSession[]>([]);
  const [loading, setLoading] = useState(true);

  async function load() {
    const res = await fetch("/api/sessions");
    setSessions(await res.json());
    setLoading(false);
  }

  useEffect(() => { load(); }, []);

  async function releaseSession(id: string) {
    if (!confirm("Release this session? This will stop the container and delete the workspace.")) return;
    await fetch(`/api/sessions/${id}`, { method: "DELETE" });
    await load();
  }

  if (loading) return <div><p className="text-muted">Loading...</p></div>;

  return (
    <div>
      <h1 className="mb-6">My Sessions</h1>

      {sessions.length === 0 ? (
        <p className="text-muted">No active sessions. Start a conversation with the bot in Slack!</p>
      ) : (
        sessions.map((s) => (
          <div key={s.id} className="card mb-4">
            <div className="flex justify-between items-center mb-4">
              <div>
                <strong>{s.summary || "Untitled session"}</strong>
                <span className="text-muted text-sm" style={{ marginLeft: "0.75rem" }}>
                  {s.model}/{s.provider}
                </span>
              </div>
              <div className="flex gap-2 items-center">
                {s.containerName && <span className="badge badge-success">Running</span>}
                {s.persistUntil && <span className="badge badge-warning">Persisted</span>}
                <button className="btn btn-danger" onClick={() => releaseSession(s.id)}>Release</button>
              </div>
            </div>
            <div className="flex gap-4 text-sm text-muted">
              <span>{s.messageCount} messages</span>
              <span>${s.totalCost.toFixed(4)}</span>
              <span>Active {timeAgo(s.lastActivity)}</span>
              <span>Started {new Date(s.createdAt).toLocaleDateString()}</span>
            </div>
          </div>
        ))
      )}
    </div>
  );
}
