"use client";

export const dynamic = "force-dynamic";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import {
  ArrowUpRight,
  Bot,
  Clock3,
  Coins,
  Filter,
  MessagesSquare,
  Search,
  TerminalSquare,
} from "lucide-react";

import { useAuth } from "@/auth/clerk";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { listClaudeSessions, type ClaudeSession } from "@/lib/api/claude-code";
import { formatRelativeTimestamp, formatTimestamp, truncateText } from "@/lib/formatters";

function formatCost(value: number) {
  return new Intl.NumberFormat(undefined, {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: value < 1 ? 4 : 2,
  }).format(value);
}

function sessionHref(session: ClaudeSession) {
  return `/claude-code/sessions/${encodeURIComponent(session.session_id)}`;
}

export default function ClaudeCodePage() {
  const { isSignedIn } = useAuth();
  const router = useRouter();
  const [search, setSearch] = useState("");
  const [activeOnly, setActiveOnly] = useState(false);

  const sessionsQuery = useQuery({
    queryKey: ["claude-code", "sessions", activeOnly],
    queryFn: () => listClaudeSessions({ activeOnly, limit: 300 }),
    enabled: Boolean(isSignedIn),
    refetchInterval: 30_000,
    refetchOnMount: "always",
  });

  const sessions = useMemo(
    () => sessionsQuery.data?.sessions ?? [],
    [sessionsQuery.data?.sessions],
  );
  const stats = sessionsQuery.data?.stats;
  const normalizedSearch = search.trim().toLowerCase();

  const filteredSessions = useMemo(() => {
    if (!normalizedSearch) return sessions;
    return sessions.filter((session) => {
      const haystack = [
        session.title,
        session.project_dir,
        session.cwd,
        session.git_branch,
        ...session.models,
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
      return haystack.includes(normalizedSearch);
    });
  }, [normalizedSearch, sessions]);

  const openSession = (session: ClaudeSession) => {
    router.push(sessionHref(session));
  };

  return (
    <DashboardPageLayout
      signedOut={{
        message: "Sign in to view local Claude Code sessions.",
        forceRedirectUrl: "/claude-code",
        signUpForceRedirectUrl: "/claude-code",
      }}
      title="Claude Code"
      description="Inspect local agent sessions, costs, tools, and conversation history."
      headerActions={
        <Button
          type="button"
          variant={activeOnly ? "primary" : "outline"}
          onClick={() => setActiveOnly((value) => !value)}
        >
          <Filter className="h-4 w-4" />
          Active only
        </Button>
      }
      contentClassName="space-y-6"
    >
      <section className="overflow-hidden rounded-2xl border border-[color:var(--border)] bg-[color:var(--surface)] shadow-sm">
        <div className="relative border-b border-[color:var(--border)] px-5 py-6 md:px-6">
          <div className="absolute inset-x-0 top-0 h-1 bg-[linear-gradient(90deg,#06b6d4,#8b5cf6,#22c55e)]" />
          <div className="flex flex-col gap-5 xl:flex-row xl:items-end xl:justify-between">
            <div className="min-w-0">
              <div className="flex items-center gap-3">
                <span className="flex h-11 w-11 items-center justify-center rounded-xl bg-cyan-500/15 text-cyan-300 ring-1 ring-cyan-400/20">
                  <TerminalSquare className="h-5 w-5" />
                </span>
                <div>
                  <h2 className="font-heading text-xl font-semibold text-[color:var(--text)]">
                    Session command center
                  </h2>
                  <p className="mt-1 text-sm text-[color:var(--text-muted)]">
                    Open a session to read the exact conversation, tool calls, and
                    thinking trail.
                  </p>
                </div>
              </div>
            </div>

            <div className="grid min-w-0 grid-cols-2 gap-3 md:grid-cols-4 xl:min-w-[640px]">
              <div className="rounded-xl border border-[color:var(--border)] bg-[color:var(--bg)] p-3">
                <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[color:var(--text-muted)]">
                  Sessions
                </p>
                <p className="mt-2 truncate text-xl font-semibold text-[color:var(--text)]">
                  {(stats?.session_count ?? 0).toLocaleString()}
                </p>
              </div>
              <div className="rounded-xl border border-[color:var(--border)] bg-[color:var(--bg)] p-3">
                <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[color:var(--text-muted)]">
                  Active
                </p>
                <p className="mt-2 truncate text-xl font-semibold text-[color:var(--text)]">
                  {(stats?.active_sessions ?? 0).toLocaleString()}
                </p>
              </div>
              <div className="rounded-xl border border-[color:var(--border)] bg-[color:var(--bg)] p-3">
                <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[color:var(--text-muted)]">
                  Tokens
                </p>
                <p className="mt-2 truncate text-xl font-semibold text-[color:var(--text)]">
                  {(stats?.total_tokens ?? 0).toLocaleString()}
                </p>
              </div>
              <div className="rounded-xl border border-[color:var(--border)] bg-[color:var(--bg)] p-3">
                <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[color:var(--text-muted)]">
                  Spend
                </p>
                <p className="mt-2 truncate text-xl font-semibold text-[color:var(--text)]">
                  {formatCost(stats?.total_cost_usd ?? 0)}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="flex flex-col gap-3 border-b border-[color:var(--border)] px-5 py-4 md:flex-row md:items-center md:px-6">
          <div className="relative flex-1">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[color:var(--text-muted)]" />
            <Input
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              placeholder="Search sessions, projects, models, branches..."
              className="pl-10"
            />
          </div>
          <p className="text-sm text-[color:var(--text-muted)]">
            Showing {filteredSessions.length.toLocaleString()} of{" "}
            {sessions.length.toLocaleString()}
          </p>
        </div>

        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-[color:var(--border)]">
            <thead className="bg-[color:var(--surface-muted)]">
              <tr>
                <th className="px-5 py-3 text-left text-xs font-bold uppercase tracking-[0.16em] text-[color:var(--text-muted)]">
                  Session
                </th>
                <th className="px-5 py-3 text-left text-xs font-bold uppercase tracking-[0.16em] text-[color:var(--text-muted)]">
                  Model
                </th>
                <th className="px-5 py-3 text-left text-xs font-bold uppercase tracking-[0.16em] text-[color:var(--text-muted)]">
                  Usage
                </th>
                <th className="px-5 py-3 text-left text-xs font-bold uppercase tracking-[0.16em] text-[color:var(--text-muted)]">
                  Last active
                </th>
                <th className="px-5 py-3 text-right text-xs font-bold uppercase tracking-[0.16em] text-[color:var(--text-muted)]">
                  Open
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[color:var(--border)]">
              {sessionsQuery.isLoading ? (
                Array.from({ length: 5 }).map((_, index) => (
                  <tr key={index}>
                    <td colSpan={5} className="px-5 py-4">
                      <div className="h-16 animate-pulse rounded-xl bg-[color:var(--surface-muted)]" />
                    </td>
                  </tr>
                ))
              ) : sessionsQuery.isError ? (
                <tr>
                  <td colSpan={5} className="px-5 py-16 text-center">
                    <Bot className="mx-auto h-10 w-10 text-rose-300" />
                    <h3 className="mt-4 text-lg font-semibold text-[color:var(--text)]">
                      Claude Code sessions unavailable
                    </h3>
                    <p className="mx-auto mt-2 max-w-md text-sm text-[color:var(--text-muted)]">
                      The backend could not read local session data. Check the API
                      server and try again.
                    </p>
                  </td>
                </tr>
              ) : filteredSessions.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-5 py-16 text-center">
                    <MessagesSquare className="mx-auto h-10 w-10 text-[color:var(--text-muted)]" />
                    <h3 className="mt-4 text-lg font-semibold text-[color:var(--text)]">
                      No Claude Code sessions found
                    </h3>
                    <p className="mx-auto mt-2 max-w-md text-sm text-[color:var(--text-muted)]">
                      Sessions appear here after Claude Code writes local JSONL history
                      under your configured projects directory.
                    </p>
                  </td>
                </tr>
              ) : (
                filteredSessions.map((session) => (
                  <tr
                    key={session.session_id}
                    tabIndex={0}
                    role="link"
                    className="cursor-pointer transition hover:bg-[color:var(--surface-muted)] focus-visible:bg-[color:var(--surface-muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[color:var(--accent)]"
                    onClick={() => openSession(session)}
                    onKeyDown={(event) => {
                      if (event.key === "Enter") openSession(session);
                    }}
                  >
                    <td className="max-w-[420px] px-5 py-4">
                      <div className="flex min-w-0 items-start gap-3">
                        <span className="mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-cyan-500/15 text-cyan-300 ring-1 ring-cyan-400/20">
                          <TerminalSquare className="h-4 w-4" />
                        </span>
                        <div className="min-w-0">
                          <div className="flex flex-wrap items-center gap-2">
                            <p className="break-words text-sm font-semibold text-[color:var(--text)]">
                              {session.title || truncateText(session.session_id, 20)}
                            </p>
                            {session.is_active ? (
                              <Badge variant="success">Active</Badge>
                            ) : null}
                          </div>
                          <p className="mt-1 break-words text-xs text-[color:var(--text-muted)]">
                            {session.cwd ?? session.project_dir}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <div className="max-w-[220px] space-y-1">
                        {(session.models.length > 0
                          ? session.models
                          : ["Unknown model"]
                        ).map((model) => (
                          <span
                            key={model}
                            className="block truncate rounded-full bg-[color:var(--surface-muted)] px-2.5 py-1 font-mono text-xs text-[color:var(--text-muted)]"
                          >
                            {model}
                          </span>
                        ))}
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <div className="space-y-1 text-sm">
                        <p className="flex items-center gap-2 font-semibold text-[color:var(--text)]">
                          <Coins className="h-4 w-4 text-[color:var(--text-muted)]" />
                          {formatCost(session.cost_usd)}
                        </p>
                        <p className="text-xs text-[color:var(--text-muted)]">
                          {session.tokens.total.toLocaleString()} tokens ·{" "}
                          {session.message_count.toLocaleString()} turns
                        </p>
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <p className="flex items-center gap-2 text-sm font-semibold text-[color:var(--text)]">
                        <Clock3 className="h-4 w-4 text-[color:var(--text-muted)]" />
                        {formatRelativeTimestamp(session.last_message_at)}
                      </p>
                      <p className="mt-1 text-xs text-[color:var(--text-muted)]">
                        {formatTimestamp(session.last_message_at)}
                      </p>
                    </td>
                    <td className="px-5 py-4 text-right">
                      <Link
                        href={sessionHref(session)}
                        className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[color:var(--border)] text-[color:var(--text-muted)] transition hover:border-[color:var(--accent)] hover:text-[color:var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--accent)]"
                        aria-label={`Open ${session.title ?? session.session_id}`}
                        onClick={(event) => event.stopPropagation()}
                      >
                        <ArrowUpRight className="h-4 w-4" />
                      </Link>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>
    </DashboardPageLayout>
  );
}
