"use client";

export const dynamic = "force-dynamic";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { AlertTriangle, ArrowLeft, Loader2, MessagesSquare } from "lucide-react";

import { ApiError } from "@/api/mutator";
import { SessionHeroHeader } from "@/components/claude/SessionHeroHeader";
import { SessionMessageThread } from "@/components/claude/SessionMessageThread";
import { SessionTimelineNav } from "@/components/claude/SessionTimelineNav";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { Button } from "@/components/ui/button";
import {
  getClaudeSession,
  getSessionMessages,
  type SessionMessage,
} from "@/lib/api/claude-code";

const PAGE_SIZE = 200;

function LoadingState() {
  return (
    <div className="space-y-5">
      <div className="h-48 animate-pulse rounded-2xl bg-[color:var(--surface-muted)]" />
      {Array.from({ length: 4 }).map((_, index) => (
        <div
          key={index}
          className="h-40 animate-pulse rounded-2xl bg-[color:var(--surface-muted)]"
        />
      ))}
    </div>
  );
}

function ErrorState({ isNotFound }: { isNotFound: boolean }) {
  return (
    <div className="flex min-h-[520px] items-center justify-center px-4">
      <div className="max-w-lg rounded-2xl border border-[color:var(--border)] bg-[color:var(--surface)] p-8 text-center shadow-sm">
        <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-rose-500/15 text-rose-300 ring-1 ring-rose-400/20">
          <AlertTriangle className="h-6 w-6" />
        </div>
        <h1 className="mt-5 text-xl font-semibold text-[color:var(--text)]">
          {isNotFound ? "Session not found" : "Session unavailable"}
        </h1>
        <p className="mt-2 text-sm leading-6 text-[color:var(--text-muted)]">
          {isNotFound
            ? "This Claude Code session could not be found in the local history."
            : "The backend could not load this Claude Code session. Check the API server and try again."}
        </p>
        <Link href="/claude-code">
          <Button className="mt-6">
            <ArrowLeft className="h-4 w-4" />
            Back to Claude Code
          </Button>
        </Link>
      </div>
    </div>
  );
}

export default function ClaudeSessionDetailPage() {
  const params = useParams<{ id: string }>();
  const sessionId = decodeURIComponent(params.id);

  const sessionQuery = useQuery({
    queryKey: ["claude-code", "session", sessionId],
    queryFn: () => getClaudeSession(sessionId),
    enabled: Boolean(sessionId),
    refetchOnMount: "always",
  });

  const messagesQuery = useInfiniteQuery({
    queryKey: ["claude-code", "session", sessionId, "messages"],
    queryFn: ({ pageParam }) =>
      getSessionMessages({
        sessionId,
        limit: PAGE_SIZE,
        offset: pageParam,
      }),
    initialPageParam: 0,
    getNextPageParam: (lastPage, pages) => {
      if (!lastPage.has_more) return undefined;
      return pages.reduce((total, page) => total + page.messages.length, 0);
    },
    enabled: Boolean(sessionId),
    refetchOnMount: "always",
  });

  const messages: SessionMessage[] =
    messagesQuery.data?.pages.flatMap((page) => page.messages) ?? [];
  const total = messagesQuery.data?.pages[0]?.total ?? 0;
  const error = sessionQuery.error ?? messagesQuery.error;
  const isNotFound = error instanceof ApiError && error.status === 404;

  return (
    <DashboardPageLayout
      signedOut={{
        message: "Sign in to view Claude Code session details.",
        forceRedirectUrl: `/claude-code/sessions/${encodeURIComponent(sessionId)}`,
        signUpForceRedirectUrl: `/claude-code/sessions/${encodeURIComponent(sessionId)}`,
      }}
      title="Claude Code session"
      description="Conversation trace, thinking blocks, and tool activity."
      contentClassName="p-0 md:p-0"
      headerClassName="sr-only"
    >
      {sessionQuery.isLoading ? (
        <div className="p-4 md:p-8">
          <LoadingState />
        </div>
      ) : sessionQuery.isError || messagesQuery.isError ? (
        <ErrorState isNotFound={isNotFound} />
      ) : sessionQuery.data ? (
        <>
          <SessionHeroHeader session={sessionQuery.data} />
          <div className="px-4 py-6 md:px-8">
            <div className="mx-auto flex max-w-[1480px] items-start gap-6">
              <main className="min-w-0 flex-1">
                {messagesQuery.isLoading ? (
                  <LoadingState />
                ) : (
                  <>
                    <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                      <div>
                        <h2 className="font-heading text-lg font-semibold text-[color:var(--text)]">
                          Conversation
                        </h2>
                        <p className="text-sm text-[color:var(--text-muted)]">
                          Showing {messages.length.toLocaleString()} of{" "}
                          {total.toLocaleString()} messages
                        </p>
                      </div>
                      {messagesQuery.hasNextPage ? (
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => messagesQuery.fetchNextPage()}
                          disabled={messagesQuery.isFetchingNextPage}
                        >
                          {messagesQuery.isFetchingNextPage ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <MessagesSquare className="h-4 w-4" />
                          )}
                          Load more
                        </Button>
                      ) : null}
                    </div>
                    <SessionMessageThread messages={messages} />
                    {messagesQuery.hasNextPage ? (
                      <div className="mt-6 flex justify-center">
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => messagesQuery.fetchNextPage()}
                          disabled={messagesQuery.isFetchingNextPage}
                        >
                          {messagesQuery.isFetchingNextPage ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <MessagesSquare className="h-4 w-4" />
                          )}
                          Load more messages
                        </Button>
                      </div>
                    ) : null}
                  </>
                )}
              </main>
              <SessionTimelineNav messages={messages} />
            </div>
          </div>
        </>
      ) : null}
    </DashboardPageLayout>
  );
}
