import { gitTagCreate, gitTagDelete, gitTagList } from "@/client";
import type { TagInfoResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Loader2,
  Plus,
  Tag,
  Trash2,
} from "lucide-react";
import { useState } from "react";
import { useParams } from "react-router-dom";
import { toast } from "sonner";
import {getApiErrorMessage} from '@/lib/api-error';

export function RepoSettingsTags() {
  const queryClient = useQueryClient();
  const { namespace, repoName } = useParams<{ namespace: string; repoName: string }>();
  const ns = namespace!;
  const rn = repoName!;
  const [tagName, setTagName] = useState("");
  const [commitSha, setCommitSha] = useState("");
  const [isCreating, setIsCreating] = useState(false);

  const { data: tagsData, isLoading: tagsLoading } = useQuery({
    queryKey: ["repo-tags", ns, rn],
    queryFn: async () => {
      const resp = await gitTagList({ path: { namespace: ns, repo: rn } });
      return resp.data?.data ?? [];
    },
    enabled: !!ns && !!rn,
    staleTime: 30 * 1000,
  });

  const createMutation = useMutation({
    mutationFn: async () => {
      if (!tagName.trim()) throw new Error("Tag name is required");
      if (!commitSha.trim()) throw new Error("Commit SHA is required");
      await gitTagCreate({
        path: { namespace: ns, repo: rn },
        body: { name: tagName, target: commitSha },
      });
    },
    onSuccess: () => {
      toast.success("Tag created successfully");
      queryClient.invalidateQueries({ queryKey: ["repo-tags", ns, rn] });
      setTagName("");
      setCommitSha("");
      setIsCreating(false);
    },
    onError: (error: Error) => {
      toast.error(error.message || "Failed to create tag");
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (tagName: string) => {
      await gitTagDelete({ path: { namespace: ns, repo: rn, name: tagName } });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["repo-tags", ns, rn] });
    },
    onError: (err: unknown) => {
      toast.error(getApiErrorMessage(err, "Failed to delete tag"));
    },
  });

  const tags: TagInfoResponse[] = tagsData ?? [];

  return (
    <div className="space-y-4">
      {/* Tag list */}
      <div className="border rounded-lg bg-card">
        <div className="p-4 border-b">
          <h2 className="text-sm font-semibold">Tags</h2>
          <p className="text-xs text-muted-foreground mt-0.5">{tags.length} tag{tags.length !== 1 ? "s" : ""} in this repository</p>
        </div>
        {tagsLoading ? (
          <div className="p-8 flex justify-center">
            <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
          </div>
        ) : tags.length === 0 ? (
          <div className="p-8 text-center text-muted-foreground text-sm">No tags yet</div>
        ) : (
          <div className="divide-y">
            {tags.map((tag) => (
              <div key={tag.name} className="flex items-center gap-3 px-4 py-3 hover:bg-muted/50">
                <Tag className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                <span className="font-mono text-sm flex-1 truncate">{tag.name}</span>
                <span className="text-xs text-muted-foreground font-mono">{tag.oid.substring(0, 7)}</span>
                {tag.is_annotated && <span className="text-xs text-muted-foreground">annotated</span>}
                <Button
                  size="sm"
                  variant="ghost"
                  className="text-destructive hover:text-destructive flex-shrink-0"
                  onClick={() => deleteMutation.mutate(tag.name)}
                  disabled={deleteMutation.isPending}
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Create tag */}
      <div className="border rounded-lg bg-card">
        <div className="p-4 border-b flex items-center justify-between">
          <div>
            <h2 className="text-sm font-semibold">Create Tag</h2>
            <p className="text-xs text-muted-foreground mt-0.5">Create an annotated tag to mark a specific commit</p>
          </div>
          {!isCreating && (
            <Button onClick={() => setIsCreating(true)} size="sm">
              <Plus className="h-3.5 w-3.5 mr-1" />
              New Tag
            </Button>
          )}
        </div>
        <div className="p-4 space-y-3">
          {isCreating ? (
            <>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs">Tag Name</Label>
                  <Input
                    value={tagName}
                    onChange={(e) => setTagName(e.target.value)}
                    placeholder="v1.0.0"
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs">Commit SHA</Label>
                  <Input
                    value={commitSha}
                    onChange={(e) => setCommitSha(e.target.value)}
                    placeholder="abc1234..."
                    className="mt-1"
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <Button
                  size="sm"
                  onClick={() => createMutation.mutate()}
                  disabled={createMutation.isPending || !tagName.trim() || !commitSha.trim()}
                >
                  {createMutation.isPending && <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />}
                  Create
                </Button>
                <Button size="sm" variant="outline" onClick={() => setIsCreating(false)}>
                  Cancel
                </Button>
              </div>
            </>
          ) : (
            <p className="text-sm text-muted-foreground">Click "New Tag" to create a tag.</p>
          )}
        </div>
      </div>
    </div>
  );
}
