"use client";

import { use } from "react";
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { ExternalLink, Landmark } from "lucide-react";
import { shareAPI } from "@/lib/api";
import { AIBriefCard } from "@/components/bills/AIBriefCard";
import { billLabel } from "@/lib/utils";

export default function SharedBriefPage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = use(params);

  const { data, isLoading, isError } = useQuery({
    queryKey: ["share-brief", token],
    queryFn: () => shareAPI.getBrief(token),
    retry: false,
  });

  return (
    <div className="min-h-screen bg-background">
      {/* Minimal header */}
      <header className="border-b border-border bg-card px-6 py-3 flex items-center gap-2">
        <Landmark className="w-5 h-5 text-primary" />
        <Link href="/" className="font-semibold text-sm hover:opacity-70 transition-opacity">
          PocketVeto
        </Link>
      </header>

      <div className="max-w-2xl mx-auto px-4 py-8 space-y-6">
        {isLoading && (
          <div className="text-center py-20 text-muted-foreground text-sm">Loading…</div>
        )}

        {isError && (
          <div className="text-center py-20">
            <p className="text-muted-foreground">Brief not found or link is invalid.</p>
          </div>
        )}

        {data && (
          <>
            {/* Bill label + title */}
            <div>
              <div className="flex items-center gap-2 mb-1">
                <span className="font-mono text-sm font-semibold text-muted-foreground bg-muted px-2 py-0.5 rounded">
                  {billLabel(data.bill.bill_type, data.bill.bill_number)}
                </span>
              </div>
              <h1 className="text-xl font-bold leading-snug">
                {data.bill.short_title || data.bill.title || "Untitled Bill"}
              </h1>
            </div>

            {/* Full brief */}
            <AIBriefCard brief={data.brief} />

            {/* CTAs */}
            <div className="flex flex-col sm:flex-row gap-3 pt-2">
              <Link
                href={`/bills/${data.bill.bill_id}`}
                className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-md border border-border hover:bg-accent transition-colors"
              >
                View full bill page <ExternalLink className="w-3.5 h-3.5" />
              </Link>
              <Link
                href="/register"
                className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
              >
                Track this bill on PocketVeto →
              </Link>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
