import { gitStar, gitUnstar, gitWatch, gitUnwatch } from "@/client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useRepo } from "@/contexts";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Copy, Eye, GitBranch, Globe, Lock, Star } from "lucide-react";
import { Link } from "react-router-dom";
import { toast } from "sonner";

export const RepoHeader = () => {
  const repo = useRepo();
  const queryClient = useQueryClient();

  if (!repo) return null;

  const { namespace, repo_name, description, is_private } = repo;
  const is_star = repo.is_star;
  const is_watch = repo.is_watch;

  const starMutation = useMutation({
    mutationFn: async (doStar: boolean) => {
      if (doStar) {
        await gitStar({ path: { namespace, repo: repo_name } });
      } else {
        await gitUnstar({ path: { namespace, repo: repo_name } });
      }
    },
    onSuccess: (_, doStar) => {
      toast.success(doStar ? "Starred" : "Unstarred");
      queryClient.invalidateQueries({ queryKey: ["repoStar", namespace, repo_name] });
      queryClient.invalidateQueries({ queryKey: ["projectRepos", namespace] });
    },
    onError: () => {
      toast.error("Action failed");
    },
  });

  const watchMutation = useMutation({
    mutationFn: async (doWatch: boolean) => {
      if (doWatch) {
        await gitWatch({ path: { namespace, repo: repo_name }, body: {} });
      } else {
        await gitUnwatch({ path: { namespace, repo: repo_name } });
      }
    },
    onSuccess: (_, doWatch) => {
      toast.success(doWatch ? "Watching" : "Not watching");
      queryClient.invalidateQueries({ queryKey: ["repoWatch", namespace, repo_name] });
      queryClient.invalidateQueries({ queryKey: ["projectRepos", namespace] });
    },
    onError: () => {
      toast.error("Action failed");
    },
  });

  const cloneUrl = repo.ssh_clone_url;
  const httpUrl = repo.https_clone_url;

  const copyUrl = (url: string, label: string) => {
    navigator.clipboard.writeText(url);
    toast.success(`${label} URL copied`);
  };

  return (
    <div className="flex items-start justify-between gap-6 pb-6">
      <div>
        <div className="flex items-center gap-2">
          <Breadcrumb>
            <BreadcrumbList>
              <BreadcrumbItem>
                <Link
                  to={`/project/${namespace}`}
                  className="transition-colors hover:text-foreground"
                >
                  {namespace}
                </Link>
              </BreadcrumbItem>
              <BreadcrumbSeparator />
              <BreadcrumbItem>
                <BreadcrumbPage className="font-semibold">
                  <span className="text-xl">{repo_name}</span>
                </BreadcrumbPage>
              </BreadcrumbItem>
            </BreadcrumbList>
          </Breadcrumb>
          <Badge variant="outline" className="flex items-center gap-1 h-fit">
            {is_private ? (
              <>
                <Lock className="h-3 w-3" />
                Private
              </>
            ) : (
              <>
                <Globe className="h-3 w-3" />
                Public
              </>
            )}
          </Badge>
        </div>
        {description && (
          <p className="text-muted-foreground mt-2 max-w-3xl">{description}</p>
        )}
      </div>

      <div className="flex items-center gap-2 shrink-0">
        <Button
          size="sm"
          variant={is_star ? "secondary" : "outline"}
          className="flex items-center gap-1"
          onClick={() => starMutation.mutate(!is_star)}
          disabled={starMutation.isPending}
        >
          <Star className={`h-4 w-4 ${is_star ? "fill-yellow-500 text-yellow-500" : ""}`} />
          <span>{repo.star_count > 0 ? repo.star_count : ""}</span>
          <span>{is_star ? "Starred" : "Star"}</span>
        </Button>

        <Button
          size="sm"
          variant={is_watch ? "secondary" : "outline"}
          className="flex items-center gap-1"
          onClick={() => watchMutation.mutate(!is_watch)}
          disabled={watchMutation.isPending}
        >
          <Eye className={`h-4 w-4 ${is_watch ? "fill-blue-500 text-blue-500" : ""}`} />
          <span>{repo.watch_count > 0 ? repo.watch_count : ""}</span>
          <span>{is_watch ? "Watching" : "Watch"}</span>
        </Button>

        <Popover>
          <PopoverTrigger className="shrink-0 justify-center border border-transparent bg-clip-padding font-medium inline-flex items-center rounded-lg text-sm whitespace-nowrap transition-all outline-none select-none h-7 gap-1 px-2.5 hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground">
            <GitBranch className="h-4 w-4" />
            <span>Clone</span>
          </PopoverTrigger>
          <PopoverContent className="w-80 p-0">
            <div className="p-4 space-y-3">
              <h4 className="font-medium text-sm">Clone</h4>
              <div>
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm flex items-center gap-2">
                    <Copy className="h-4 w-4" />
                    SSH
                  </span>
                  <Button size="sm" variant="ghost" className="h-7 w-16 text-xs" onClick={() => copyUrl(cloneUrl, "SSH")}>
                    Copy
                  </Button>
                </div>
                <div className="text-xs text-muted-foreground font-mono bg-muted p-2 rounded break-all">
                  {cloneUrl}
                </div>
              </div>
              <div>
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm flex items-center gap-2">
                    <Copy className="h-4 w-4" />
                    HTTPS
                  </span>
                  <Button size="sm" variant="ghost" className="h-7 w-16 text-xs" onClick={() => copyUrl(httpUrl, "HTTPS")}>
                    Copy
                  </Button>
                </div>
                <div className="text-xs text-muted-foreground font-mono bg-muted p-2 rounded break-all">
                  {httpUrl}
                </div>
              </div>
            </div>
          </PopoverContent>
        </Popover>
      </div>
    </div>
  );
};
