import { useState, type FormEvent } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { GitPullRequest, ArrowRight, ArrowLeft } from "lucide-react";

export default function PullCreatePage() {
  const { projectName = "", repoName = "" } = useParams();
  const navigate = useNavigate();
  const qc = useQueryClient();

  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [sourceBranch, setSourceBranch] = useState("");
  const [targetBranch, setTargetBranch] = useState("");
  const [draft, setDraft] = useState(false);
  const [error, setError] = useState("");

  const { data: branches = [] } = useQuery({
    queryKey: ["repo", projectName, repoName, "branches"],
    queryFn: async () => {
      const res = await client.gitListBranches(projectName, repoName);
      return res.data.branches;
    },
    enabled: Boolean(projectName) && Boolean(repoName),
    retry: false,
  });

  const createPr = useMutation({
    mutationFn: async () => {
      const res = await client.pullRequestCreatePr(projectName, repoName, {
        title,
        body: body || null,
        source_branch: sourceBranch,
        target_branch: targetBranch || undefined,
        draft: draft || null,
      });
      return res.data;
    },
    onSuccess: (data) => {
      qc.invalidateQueries({ queryKey: ["repo", projectName, repoName, "pulls"] });
      navigate(`/${projectName}/repo/${repoName}/pulls/${data.number}`);
    },
    onError: (err: Error) => {
      setError(err.message);
    },
  });

  const handleSubmit = (event: FormEvent) => {
    event.preventDefault();
    if (!sourceBranch) { setError("Source branch is required."); return; }
    setError("");
    createPr.mutate();
  };

  return (
    <div className="mx-auto max-w-5xl px-8 py-10">
      <Link className="inline-flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground transition-colors mb-4" to={`/${projectName}/repo/${repoName}`}>
        <ArrowLeft className="size-3.5" />
        Back to repository
      </Link>
      <div className="flex items-center gap-2">
        <GitPullRequest className="size-4 text-muted-foreground" />
        <h1 className="font-heading text-lg font-bold text-foreground">New pull request</h1>
      </div>

      <form className="mt-6 grid grid-cols-[1fr_240px] gap-6" onSubmit={handleSubmit}>
        {/* Main */}
        <div className="space-y-4">
          {/* Branch selector */}
          <div className="flex items-center gap-2 rounded-md border border-border px-3 py-2.5">
            <Select value={sourceBranch} onValueChange={(v) => setSourceBranch(v ?? "")}>
              <SelectTrigger className="h-8 text-[12px] w-auto min-w-[140px]">
                <SelectValue placeholder="source branch" />
              </SelectTrigger>
              <SelectContent>
                {branches.filter((b) => b.name !== targetBranch).map((b) => (
                  <SelectItem key={b.name} value={b.name}>{b.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <ArrowRight className="size-3.5 text-muted-foreground shrink-0" />
            <Select value={targetBranch} onValueChange={(v) => setTargetBranch(v ?? "")}>
              <SelectTrigger className="h-8 text-[12px] w-auto min-w-[140px]">
                <SelectValue placeholder="target branch" />
              </SelectTrigger>
              <SelectContent>
                {branches.filter((b) => b.name !== sourceBranch).map((b) => (
                  <SelectItem key={b.name} value={b.name}>{b.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Input
              className="mt-1.5 h-9 text-[14px] font-heading font-semibold"
              placeholder="Pull request title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
              autoFocus
            />
          </div>
          <div>
            <Textarea
              className="mt-1.5 min-h-[200px] text-[13px]"
              placeholder="Describe your changes... Markdown is supported"
              value={body}
              onChange={(e) => setBody(e.target.value)}
            />
          </div>

          {error && <p className="text-[12px] text-destructive">{error}</p>}

          <div className="flex items-center gap-3">
            <Button className="h-9 px-4 text-[13px]" disabled={createPr.isPending || !sourceBranch || !title.trim()} type="submit">
              {createPr.isPending ? "Creating..." : "Create pull request"}
            </Button>
            <Link className="inline-flex items-center h-9 px-4 text-[13px] rounded-md border border-border text-muted-foreground hover:text-foreground transition-colors" to={`/${projectName}/repo/${repoName}`}>Cancel</Link>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-4">
          <div>
            <label className="flex items-center gap-2 cursor-pointer">
              <input checked={draft} className="size-3.5 rounded border-border accent-primary" onChange={(e) => setDraft(e.target.checked)} type="checkbox" />
              <span className="text-[13px] text-foreground">Draft PR</span>
            </label>
            <p className="text-[11px] text-muted-foreground mt-0.5">Cannot be merged until marked ready.</p>
          </div>
        </div>
      </form>
    </div>
  );
}