import { gitBranchList, pullRequestCreate, generatePrDescription } from "@/client";
import { RepoHeader } from "@/components/repository/header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useMutation, useQuery } from "@tanstack/react-query";
import { GitBranch, GitMerge, Loader2, Sparkles } from "lucide-react";
import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import type { BranchInfoResponse } from "@/client";

export const RepoPullRequestNew = () => {
  const { namespace, repoName } = useParams<{ namespace: string; repoName: string }>();
  const navigate = useNavigate();

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [baseBranch, setBaseBranch] = useState("");
  const [headBranch, setHeadBranch] = useState("");
  const [isDraft, setIsDraft] = useState(false);

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

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

  const defaultBranch = branchList.find((b) => b.isHead)?.name || branchList[0]?.name || "";

  // Set default values once branches are loaded
  if (!baseBranch && defaultBranch) {
    setBaseBranch(defaultBranch);
  }

  const generateMutation = useMutation({
    mutationFn: async () => {
      if (!namespace || !repoName) return;
      const resp = await generatePrDescription({
        path: { namespace, repo: repoName },
        body: { pr_number: undefined },
      });
      return resp.data?.markdown_body;
    },
    onSuccess: (body) => {
      if (body) {
        setDescription(body);
        toast.success("AI description generated");
      }
    },
    onError: () => toast.error("Failed to generate description"),
  });

  const createMutation = useMutation({
    mutationFn: async () => {
      if (!namespace || !repoName) return;
      if (!title.trim()) {
        throw new Error("Title is required");
      }
      if (!baseBranch || !headBranch) {
        throw new Error("Both base and head branches are required");
      }
      await pullRequestCreate({
        path: { namespace, repo: repoName },
        body: {
          title: title.trim(),
          body: description.trim() || null,
          base: baseBranch,
          head: headBranch,
          draft: isDraft,
        },
      });
    },
    onSuccess: () => {
      toast.success("Pull request created successfully");
      navigate(`/repository/${namespace}/${repoName}/pulls`);
    },
    onError: (error: Error) => {
      toast.error(error.message || "Failed to create pull request");
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createMutation.mutate();
  };

  if (branchesLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-6 w-6 animate-spin" />
      </div>
    );
  }

  return (
    <>
      <div className="p-6 pb-0 max-w-3xl mx-auto space-y-6">
        <RepoHeader />
      </div>
      <div className="p-6 pt-0 max-w-3xl mx-auto space-y-6">
        <div className="flex items-center gap-3">
          <GitMerge className="h-6 w-6 text-muted-foreground" />
          <h1 className="text-2xl font-bold">New Pull Request</h1>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Branch selectors */}
          <div className="border rounded-lg bg-card p-6 space-y-4">
            <h2 className="font-medium">Branches</h2>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="base-branch">Base branch</Label>
                <div className="relative">
                  <GitBranch className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <select
                    id="base-branch"
                    value={baseBranch}
                    onChange={(e) => setBaseBranch(e.target.value)}
                    className="w-full pl-9 pr-3 py-2 text-sm border rounded-md bg-background"
                    required
                  >
                    <option value="">Select base branch</option>
                    {branchList.map((branch) => (
                      <option key={branch.name} value={branch.name}>
                        {branch.name}
                      </option>
                    ))}
                  </select>
                </div>
                <p className="text-xs text-muted-foreground">
                  The branch you want to merge your changes into
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="head-branch">Compare branch</Label>
                <div className="relative">
                  <GitBranch className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <select
                    id="head-branch"
                    value={headBranch}
                    onChange={(e) => setHeadBranch(e.target.value)}
                    className="w-full pl-9 pr-3 py-2 text-sm border rounded-md bg-background"
                    required
                  >
                    <option value="">Select compare branch</option>
                    {branchList
                      .filter((b) => b.name !== baseBranch)
                      .map((branch) => (
                        <option key={branch.name} value={branch.name}>
                          {branch.name}
                        </option>
                      ))}
                  </select>
                </div>
                <p className="text-xs text-muted-foreground">
                  The branch that contains your changes
                </p>
              </div>
            </div>
          </div>

          {/* PR Details */}
          <div className="border rounded-lg bg-card p-6 space-y-4">
            <h2 className="font-medium">Pull Request Details</h2>

            <div className="space-y-2">
              <Label htmlFor="pr-title">Title</Label>
              <Input
                id="pr-title"
                placeholder="Enter a title for your pull request"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                required
              />
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="pr-description">Description (optional)</Label>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-7 text-xs text-muted-foreground hover:text-foreground gap-1"
                  onClick={() => generateMutation.mutate()}
                  disabled={
                    generateMutation.isPending ||
                    !baseBranch ||
                    !headBranch ||
                    !namespace ||
                    !repoName
                  }
                  title="Generate description using AI based on the diff"
                >
                  {generateMutation.isPending ? (
                    <Loader2 className="h-3 w-3 animate-spin" />
                  ) : (
                    <Sparkles className="h-3 w-3" />
                  )}
                  Generate with AI
                </Button>
              </div>
              <Textarea
                id="pr-description"
                placeholder="Describe your changes and motivation"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                rows={6}
              />
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center justify-between">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(`/repository/${namespace}/${repoName}/pulls`)}
            >
              Cancel
            </Button>
            <div className="flex items-center gap-3">
              <Button
                type="button"
                variant="outline"
                onClick={() => setIsDraft(!isDraft)}
              >
                {isDraft ? "Mark as ready" : "Create as draft"}
              </Button>
              <Button
                type="submit"
                disabled={createMutation.isPending || !title.trim() || !baseBranch || !headBranch}
              >
                {createMutation.isPending ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Creating...
                  </>
                ) : (
                  <>
                    <GitMerge className="h-4 w-4 mr-2" />
                    Create pull request
                  </>
                )}
              </Button>
            </div>
          </div>
        </form>
      </div>
    </>
  );
};
