import { useParams } from "react-router";
import { useQuery } from "@tanstack/react-query";
import { client } from "@/client";
import { BookOpen } from "lucide-react";

const SKELETON_WIDTHS = Array.from({ length: 8 }, () => 30 + Math.floor(Math.random() * 60));

export default function ReadmePage() {
  const { projectName = "", repoName = "" } = useParams();

  const { data: readme, isLoading } = useQuery({
    queryKey: ["repo", projectName, repoName, "readme"],
    queryFn: async () => {
      const res = await client.gitGetReadme(projectName, repoName);
      return res.data;
    },
    enabled: Boolean(projectName) && Boolean(repoName),
    retry: false,
  });

  if (isLoading) {
    return <div className="space-y-3">{SKELETON_WIDTHS.map((w, i) => <div className="h-4 animate-pulse rounded bg-muted/50" key={i} style={{ width: `${w}%` }} />)}</div>;
  }

  if (!readme?.html) {
    return (
      <div className="py-12 text-center">
        <BookOpen className="mx-auto size-5 text-muted-foreground/20" />
        <p className="mt-2 text-[13px] text-muted-foreground">No README found</p>
      </div>
    );
  }

  return (
    <div className="max-w-3xl">
      <div className="rounded-md border border-border overflow-hidden">
        <div className="flex items-center gap-2 bg-muted/50 px-4 py-2 border-b border-border">
          <BookOpen className="size-4 text-muted-foreground" />
          <span className="font-heading text-[13px] font-medium text-foreground">README.md</span>
        </div>
        <div
          className="px-6 py-4 text-[14px] leading-relaxed [&_h1]:text-lg [&_h1]:font-bold [&_h1]:font-heading [&_h1]:mb-3 [&_h1]:mt-6 [&_h1:first-child]:mt-0 [&_h2]:text-base [&_h2]:font-bold [&_h2]:font-heading [&_h2]:mb-2 [&_h2]:mt-5 [&_h3]:text-[15px] [&_h3]:font-bold [&_h3]:mb-2 [&_h3]:mt-4 [&_h4]:text-[14px] [&_h4]:font-bold [&_h4]:mb-1 [&_h4]:mt-3 [&_p]:mb-3 [&_p:last-child]:mb-0 [&_a]:text-primary [&_a]:underline [&_a:hover]:opacity-80 [&_ul]:list-disc [&_ul]:pl-6 [&_ul]:mb-3 [&_ol]:list-decimal [&_ol]:pl-6 [&_ol]:mb-3 [&_li]:mb-1 [&_code]:rounded-sm [&_code]:bg-muted [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[12px] [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-4 [&_pre]:mb-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-[12px] [&_blockquote]:border-l-2 [&_blockquote]:border-primary/30 [&_blockquote]:pl-4 [&_blockquote]:py-0.5 [&_blockquote]:mb-3 [&_blockquote]:text-muted-foreground [&_img]:rounded-md [&_img]:max-w-full [&_img]:my-3 [&_hr]:border-border [&_hr]:my-4 [&_table]:w-full [&_table]:border-collapse [&_table]:mb-3 [&_th]:border [&_th]:border-border [&_th]:px-3 [&_th]:py-2 [&_th]:bg-muted/50 [&_th]:text-left [&_th]:font-heading [&_th]:text-[13px] [&_td]:border [&_td]:border-border [&_td]:px-3 [&_td]:py-2"
          dangerouslySetInnerHTML={{ __html: readme.html }}
        />
      </div>
    </div>
  );
}