import { useQuery } from "@tanstack/react-query";
import { Link, useParams, useSearch } from "@tanstack/react-router";
import { Card, CardBody, CardHeader } from "../components/ui/Card";

interface FileSearch {
  channel?: string;
  path?: string;
}

export function FilePage() {
  const { owner, name } = useParams({ from: "/$owner/$name/file" });
  const { channel = "main", path = "" } = useSearch({ from: "/$owner/$name/file" }) as FileSearch;

  const { data: content, isLoading } = useQuery({
    queryKey: ["repo", owner, name, "file", channel, path],
    queryFn: async () => {
      const res = await fetch(`/api/repos/${owner}/${name}/file?channel=${channel}&path=${encodeURIComponent(path)}`, {
        credentials: "include",
      });
      if (!res.ok) throw new Error("File not found");
      return res.text();
    },
    enabled: !!path,
  });

  const fileName = path.split("/").pop() ?? path;

  return (
    <div className="max-w-5xl mx-auto px-6 py-8">
      <div className="flex items-center gap-2 text-[15px] mb-6 flex-wrap">
        <Link to="/$owner/$name" params={{ owner, name }} className="text-[#0071e3] hover:underline">
          {owner}/{name}
        </Link>
        {path.split("/").filter(Boolean).map((seg, i, arr) => (
          <span key={seg} className="flex items-center gap-2">
            <span className="text-[#6e6e73]">/</span>
            {i < arr.length - 1 ? (
              <Link
                to="/$owner/$name"
                params={{ owner, name }}
                search={{ channel, path: arr.slice(0, i + 1).join("/") }}
                className="text-[#0071e3] hover:underline"
              >
                {seg}
              </Link>
            ) : (
              <span className="font-semibold text-[#1d1d1f]">{seg}</span>
            )}
          </span>
        ))}
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <span className="text-[13px] font-medium text-[#1d1d1f] font-mono">{fileName}</span>
            <span className="text-[12px] text-[#6e6e73]">channel: {channel}</span>
          </div>
        </CardHeader>
        <CardBody className="p-0">
          {isLoading ? (
            <div className="p-5 text-[13px] text-[#6e6e73]">Loading…</div>
          ) : (
            <pre className="overflow-x-auto p-5 text-[13px] leading-5 font-mono text-[#1d1d1f] bg-[#fafafa] rounded-b-[14px]">
              {content}
            </pre>
          )}
        </CardBody>
      </Card>
    </div>
  );
}