"use client";

import { useEffect, useState } from "react";
import { Button, ButtonLink } from "@/components/ui/Button";
import PRStateBadge from "@/components/PRStateBadge";
import { useHistoryData } from "@/lib/hooks/use-history-data";
import { pad2, toUtc8Date } from "@/app/observe/lib/formatters";

const PAGE_SIZE = 15;

const headerCellClass =
  "px-5 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted";
const bodyCellClass = "px-5 py-2.5";
const createdHeaderCellClass =
  "pl-5 pr-1 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted";
const createdBodyCellClass = "pl-5 pr-1 py-2.5";
const titleHeaderCellClass =
  "pl-0.5 pr-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted";
const titleBodyCellClass = "pl-0.5 pr-4 py-2.5";
const actionHeaderCellClass =
  "pl-2 pr-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted";
const actionBodyCellClass = "pl-2 pr-4 py-2.5";

function formatCreatedAt(value: string): string {
  const timestamp = Date.parse(value);
  if (!Number.isFinite(timestamp)) return value;
  const utc8 = toUtc8Date(timestamp);
  return [
    `${utc8.getUTCFullYear()}-${pad2(utc8.getUTCMonth() + 1)}-${pad2(utc8.getUTCDate())}`,
    `${pad2(utc8.getUTCHours())}:${pad2(utc8.getUTCMinutes())}`,
    "UTC+8",
  ].join(" ");
}

function HistorySkeleton() {
  return (
    <div className="space-y-4 animate-pulse">
      <div className="flex items-center justify-between">
        <div className="h-6 w-48 bg-surface-1 rounded" />
        <div className="h-9 w-36 bg-surface-1 rounded-lg" />
      </div>
      <div className="bg-surface-0 border border-surface-2 rounded-lg overflow-hidden">
        <div className="h-10 bg-surface-1" />
        {Array.from({ length: 5 }).map((_, i) => (
          <div key={i} className="h-10 border-b border-surface-2/50" />
        ))}
      </div>
    </div>
  );
}

export default function HistoryPage() {
  const { prs, loading, error, refetch } = useHistoryData();
  const [page, setPage] = useState(1);

  useEffect(() => {
    setPage(1);
  }, [prs.length]);

  const totalPages = Math.max(1, Math.ceil(prs.length / PAGE_SIZE));
  const pagedPrs = prs.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  if (loading) return <HistorySkeleton />;

  if (error) {
    return (
      <div className="bg-danger-muted border border-danger/20 rounded-lg p-4 flex items-start gap-3">
        <div className="w-5 h-5 rounded-full bg-danger/20 flex items-center justify-center shrink-0 mt-0.5">
          <span className="text-danger text-xs font-bold">!</span>
        </div>
        <div>
          <p className="text-sm text-danger font-medium">{error}</p>
          <Button
            onClick={() => {
              void refetch();
            }}
            variant="danger"
            size="sm"
            className="mt-2"
          >
            Try again
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <section>
        <h2 className="text-xl font-semibold tracking-tight">
          Operation History
        </h2>
      </section>

      <section>
      {prs.length === 0 ? (
        <div className="bg-surface-0 rounded-lg border border-surface-2 p-8 text-center">
          <p className="text-text-muted text-sm">
            No bump PRs found.
          </p>
          <p className="text-text-muted text-xs mt-1">
            Make sure you have <code className="font-mono bg-surface-1 px-1.5 py-0.5 rounded text-accent">gh</code> CLI authenticated and access to the repo.
          </p>
        </div>
      ) : (
        <div className="bg-surface-0 rounded-lg border border-surface-2 overflow-x-auto">
          <table className="w-full min-w-[640px] text-sm">
            <thead>
              <tr className="border-b border-surface-2">
                <th className={headerCellClass}>
                  PR
                </th>
                <th className={headerCellClass}>
                  Author
                </th>
                <th className={headerCellClass}>
                  State
                </th>
                <th className={createdHeaderCellClass}>
                  Created
                </th>
                <th className={titleHeaderCellClass}>
                  Title
                </th>
                <th className={actionHeaderCellClass}>
                  Actions
                </th>
              </tr>
            </thead>
            <tbody>
              {pagedPrs.map((pr) => {
                const observeHref = pr.regions?.length
                  ? `/observe?regions=${encodeURIComponent(pr.regions.join(","))}&component=acs`
                  : null;
                const agentsHref = pr.regions?.length
                  ? `/agents?regions=${encodeURIComponent(pr.regions.join(","))}`
                  : null;

                return (
                  <tr
                    key={pr.number}
                    className="border-b border-surface-2/50 last:border-0 hover:bg-surface-1 transition-colors"
                  >
                    <td className={bodyCellClass}>
                      <a
                        href={pr.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="font-mono text-[13px] text-accent hover:underline"
                      >
                        #{pr.number}
                      </a>
                    </td>
                    <td className={`${bodyCellClass} text-text-secondary`}>
                      {pr.author}
                    </td>
                    <td className={bodyCellClass}>
                      <PRStateBadge state={pr.state} />
                    </td>
                    <td className={createdBodyCellClass}>
                      <time
                        dateTime={pr.createdAt || undefined}
                        title={pr.createdAt || undefined}
                        className="font-mono text-[13px] bg-surface-1 px-2 py-0.5 rounded border border-surface-2/70 text-accent whitespace-nowrap"
                      >
                        {formatCreatedAt(pr.createdAt)}
                      </time>
                    </td>
                    <td className={`${titleBodyCellClass} truncate text-text-secondary`}>
                      {pr.title}
                    </td>
                    <td className={actionBodyCellClass}>
                      {observeHref && agentsHref ? (
                        <div className="inline-flex items-center overflow-hidden rounded-md border border-accent/30">
                          <ButtonLink
                            href={observeHref}
                            variant="subtle"
                            size="xs"
                            className="rounded-none border-y-0 border-l-0 border-r border-accent/20"
                          >
                            Observe
                          </ButtonLink>
                          <ButtonLink
                            href={agentsHref}
                            variant="subtle"
                            size="xs"
                            className="rounded-none border-0"
                          >
                            Agents
                          </ButtonLink>
                        </div>
                      ) : (
                        <span className="text-text-muted">-</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
      {totalPages > 1 && (
        <div className="flex items-center justify-end pt-3">
          <div className="inline-flex items-center rounded-lg border border-surface-2 bg-surface-0 text-xs">
            <button
              type="button"
              disabled={page <= 1}
              onClick={() => setPage((p) => p - 1)}
              className="px-3 py-1.5 text-text-secondary hover:text-text-primary hover:bg-surface-1 disabled:opacity-40 disabled:pointer-events-none transition-colors rounded-l-lg"
            >
              Prev
            </button>
            <div className="px-3 py-1.5 border-x border-surface-2 text-text-muted tabular-nums select-none">
              {page} / {totalPages}
            </div>
            <button
              type="button"
              disabled={page >= totalPages}
              onClick={() => setPage((p) => p + 1)}
              className="px-3 py-1.5 text-text-secondary hover:text-text-primary hover:bg-surface-1 disabled:opacity-40 disabled:pointer-events-none transition-colors rounded-r-lg"
            >
              Next
            </button>
          </div>
        </div>
      )}
      </section>
    </div>
  );
}
