import { gitBranchList } from "@/client";
import { FileBrowser } from "@/components/repository/file-browser";
import { RepoHeader } from "@/components/repository/header";
import { Button } from "@/components/ui/button";
import { useQuery } from "@tanstack/react-query";
import { GitBranch, Loader2 } from "lucide-react";
import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import { useRepo } from "@/contexts";
import type { BranchInfoResponse } from "@/client";

export const RepoFiles = () => {
  const repo = useRepo();
  const [searchParams, setSearchParams] = useSearchParams();
  const [showBranchDropdown, setShowBranchDropdown] = useState(false);

  const currentPath = searchParams.get("path") || "";
  const currentBranch = searchParams.get("branch") || repo?.default_branch || "main";

  const { data: branches = [], isLoading: branchesLoading } = useQuery({
    queryKey: ["repo-branches", repo?.namespace, repo?.repo_name],
    queryFn: async () => {
      if (!repo?.namespace || !repo?.repo_name) return [];
      const resp = await gitBranchList({ path: { namespace: repo.namespace, repo: repo.repo_name } });
      return resp.data?.data ?? [];
    },
    enabled: !!repo?.namespace && !!repo?.repo_name,
    staleTime: 60 * 1000,
  });

  const branchList = (branches as BranchInfoResponse[]).map((b) => ({
    name: b.name.replace("refs/heads/", ""),
    isHead: b.is_head,
  }));

  const handleBranchChange = (branchName: string) => {
    const params = new URLSearchParams(searchParams);
    params.set("branch", branchName);
    params.delete("path"); // Reset path when changing branch
    setSearchParams(params);
  };

  const branchCount = branchList.length;

  return (
    <>
      <div className="p-6 pb-0 max-w-6xl mx-auto space-y-6">
        <RepoHeader />
      </div>
      <div className="p-6 pt-0 max-w-6xl mx-auto space-y-6">
        <div className="border-b border-border pb-4">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex items-center gap-3">
              {branchesLoading ? (
                <div className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                  <span className="text-sm text-muted-foreground">Loading branches...</span>
                </div>
              ) : (
                <>
                  <GitBranch className="h-4 w-4 text-muted-foreground" />
                  <div className="relative">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setShowBranchDropdown(!showBranchDropdown)}
                      className="w-[180px] justify-start"
                    >
                      {currentBranch}
                    </Button>

                    {showBranchDropdown && (
                      <div className="absolute left-0 top-full mt-1 w-[180px] bg-background border rounded-md shadow-lg z-10 max-h-60 overflow-y-auto">
                        {branchList.map((branch) => (
                          <button
                            key={branch.name}
                            onClick={() => {
                              handleBranchChange(branch.name);
                              setShowBranchDropdown(false);
                            }}
                            className={`w-full px-3 py-2 text-left text-sm hover:bg-muted flex items-center gap-2 ${
                              currentBranch === branch.name ? "bg-muted" : ""
                            }`}
                          >
                            <GitBranch className="h-4 w-4" />
                            <span className="truncate">{branch.name}</span>
                            {branch.isHead && (
                              <span className="ml-auto text-xs text-muted-foreground">HEAD</span>
                            )}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                  <span className="text-sm text-muted-foreground">
                    {branchCount} {branchCount === 1 ? "branch" : "branches"}
                  </span>
                </>
              )}
            </div>
          </div>
        </div>

        <FileBrowser
          key={`${currentBranch}-${currentPath}`}
          branch={currentBranch}
          initialPath={currentPath}
        />
      </div>
    </>
  );
};
