import { branchProtectionCreate, branchProtectionDelete, branchProtectionList } from "@/client";
import type { BranchProtectionResponse } 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 {
  GitBranch,
  Loader2,
  Plus,
  Shield,
  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 RepoSettingsBranches() {
  const queryClient = useQueryClient();
  const { namespace, repoName } = useParams<{ namespace: string; repoName: string }>();
  const ns = namespace!;
  const rn = repoName!;
  const [isCreating, setIsCreating] = useState(false);
  const [branch, setBranch] = useState("");
  const [requiredApprovals, setRequiredApprovals] = useState(0);
  const [forbidForcePush, setForbidForcePush] = useState(true);

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

  const createMutation = useMutation({
    mutationFn: async () => {
      if (!branch.trim()) throw new Error("Branch name is required");
      await branchProtectionCreate({
        path: { namespace: ns, repo: rn },
        body: {
          branch: branch.trim(),
          required_approvals: requiredApprovals,
          forbid_force_push: forbidForcePush,
        },
      });
    },
    onSuccess: () => {
      toast.success("Branch protection rule created");
      queryClient.invalidateQueries({ queryKey: ["branch-protections", ns, rn] });
      setBranch("");
      setRequiredApprovals(0);
      setForbidForcePush(true);
      setIsCreating(false);
    },
    onError: (err: unknown) => {
      toast.error(getApiErrorMessage(err, "Failed to create rule"));
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      await branchProtectionDelete({ path: { namespace: ns, repo: rn, id } });
    },
    onSuccess: () => {
      toast.success("Rule deleted");
      queryClient.invalidateQueries({ queryKey: ["branch-protections", ns, rn] });
    },
    onError: (err: unknown) => {
      toast.error(getApiErrorMessage(err, "Failed to delete rule"));
    },
  });

  const protectionRules: BranchProtectionResponse[] = rules ?? [];

  return (
    <div className="space-y-4">
      {/* Rules list */}
      <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">Protection Rules</h2>
            <p className="text-xs text-muted-foreground mt-0.5">{protectionRules.length} rule{protectionRules.length !== 1 ? "s" : ""}</p>
          </div>
          {!isCreating && (
            <Button onClick={() => setIsCreating(true)} size="sm">
              <Plus className="h-3.5 w-3.5 mr-1" />
              Add Rule
            </Button>
          )}
        </div>
        {isLoading ? (
          <div className="p-8 flex justify-center">
            <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
          </div>
        ) : protectionRules.length === 0 && !isCreating ? (
          <div className="p-8 text-center text-muted-foreground text-sm">
            <Shield className="h-8 w-8 mx-auto mb-2 opacity-50" />
            No branch protection rules
          </div>
        ) : (
          <div className="divide-y">
            {protectionRules.map((rule) => (
              <div key={rule.id} className="flex items-center gap-3 px-4 py-3 hover:bg-muted/50">
                <GitBranch className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-sm font-mono">{rule.branch}</p>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {rule.forbid_force_push && (
                      <span className="text-xs px-1.5 py-0.5 rounded bg-orange-500/10 text-orange-600 border border-orange-500/20">no force push</span>
                    )}
                    {rule.required_approvals > 0 && (
                      <span className="text-xs px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-600 border border-blue-500/20">{rule.required_approvals} approvals</span>
                    )}
                    {rule.forbid_deletion && (
                      <span className="text-xs px-1.5 py-0.5 rounded bg-red-500/10 text-red-600 border border-red-500/20">no deletion</span>
                    )}
                  </div>
                </div>
                <Button
                  size="sm"
                  variant="ghost"
                  className="text-destructive hover:text-destructive flex-shrink-0"
                  onClick={() => deleteMutation.mutate(rule.id)}
                  disabled={deleteMutation.isPending}
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Create rule */}
      {isCreating && (
        <div className="border rounded-lg bg-card">
          <div className="p-4 border-b">
            <h2 className="text-sm font-semibold">New Protection Rule</h2>
          </div>
          <div className="p-4 space-y-4">
            <div>
              <Label className="text-xs">Branch Pattern</Label>
              <Input
                value={branch}
                onChange={(e) => setBranch(e.target.value)}
                placeholder="main"
                className="mt-1"
              />
              <p className="text-xs text-muted-foreground mt-1">Branch name or pattern (e.g. release-*)</p>
            </div>
            <div>
              <Label className="text-xs">Required Approvals</Label>
              <Input
                type="number"
                min={0}
                value={requiredApprovals}
                onChange={(e) => setRequiredApprovals(Number(e.target.value))}
                className="mt-1 w-32"
              />
            </div>
            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="forbidForcePush"
                checked={forbidForcePush}
                onChange={(e) => setForbidForcePush(e.target.checked)}
                className="h-4 w-4 rounded"
              />
              <label htmlFor="forbidForcePush" className="text-sm">Forbid force push</label>
            </div>
            <div className="flex gap-2">
              <Button
                size="sm"
                onClick={() => createMutation.mutate()}
                disabled={createMutation.isPending || !branch.trim()}
              >
                {createMutation.isPending && <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />}
                Create Rule
              </Button>
              <Button size="sm" variant="outline" onClick={() => setIsCreating(false)}>
                Cancel
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
