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

export function ChangePage() {
  const { owner, name, hash } = useParams({ from: "/$owner/$name/change/$hash" });

  const { data: change, isLoading } = useQuery({
    queryKey: ["repo", owner, name, "change", hash],
    queryFn: () => api.repos.change(owner, name, hash),
  });

  return (
    <div className="max-w-5xl mx-auto px-6 py-8">
      <div className="flex items-center gap-2 text-[15px] mb-6">
        <Link to="/$owner/$name" params={{ owner, name }} className="text-[#0071e3] hover:underline">
          {owner}/{name}
        </Link>
        <span className="text-[#6e6e73]">/</span>
        <Link to="/$owner/$name/changes" params={{ owner, name }} className="text-[#0071e3] hover:underline">
          Changes
        </Link>
        <span className="text-[#6e6e73]">/</span>
        <code className="font-mono text-[13px] text-[#1d1d1f]">{hash.slice(0, 8)}</code>
      </div>

      {isLoading ? (
        <div className="text-center py-20 text-[#6e6e73]">Loading…</div>
      ) : !change ? (
        <div className="text-center py-20 text-[#6e6e73]">Change not found</div>
      ) : (
        <div className="flex flex-col gap-4">
          <Card>
            <CardBody>
              <h1 className="text-[18px] font-semibold text-[#1d1d1f] mb-3">
                {change.message || "(no message)"}
              </h1>
              <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-[#6e6e73]">
                <span>{change.authors.map((a) => a.name).join(", ")}</span>
                {change.timestamp && <span>{new Date(change.timestamp).toLocaleString()}</span>}
                <code className="font-mono bg-black/5 px-2 py-0.5 rounded text-[12px]">{hash}</code>
              </div>
            </CardBody>
          </Card>

          {change.diff && (
            <Card>
              <CardHeader>
                <span className="text-[13px] font-medium text-[#1d1d1f]">Diff</span>
              </CardHeader>
              <CardBody className="p-0 overflow-hidden">
                <pre className="overflow-x-auto p-5 text-[12px] leading-5 font-mono text-[#1d1d1f] bg-[#fafafa]">
                  {change.diff.split("\n").map((line, i) => (
                    <div
                      key={i}
                      className={
                        line.startsWith("+")
                          ? "bg-green-50 text-green-800"
                          : line.startsWith("-")
                            ? "bg-red-50 text-red-800"
                            : ""
                      }
                    >
                      {line}
                    </div>
                  ))}
                </pre>
              </CardBody>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}