"use client";

import { useRef, useState } from "react";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import type { ForgejoIssue } from "@/lib/api-forgejo";
import { postForgejoIssueComment } from "@/lib/api-forgejo";

type PostForgejoCommentDialogProps = {
  issue: ForgejoIssue | null;
  repositoryName: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
};

export function PostForgejoCommentDialog({
  issue,
  repositoryName,
  open,
  onOpenChange,
  onSuccess,
}: PostForgejoCommentDialogProps) {
  const [body, setBody] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  if (!issue) return null;

  const handleSubmit = async () => {
    if (!body.trim()) return;
    setIsSubmitting(true);
    setError(null);
    try {
      await postForgejoIssueComment(issue.id, body.trim());
      setBody("");
      onSuccess();
      onOpenChange(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to post comment");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        if (!isSubmitting) {
          setBody("");
          setError(null);
          onOpenChange(next);
        }
      }}
    >
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Post comment</DialogTitle>
          <DialogDescription>
            Comment on{" "}
            <span className="font-mono font-semibold text-strong">
              {repositoryName}#{issue.forgejo_issue_number}
            </span>
            . The comment will be posted directly to the connected Git provider.
          </DialogDescription>
        </DialogHeader>

        <div className="rounded-xl border border-[color:var(--border)] bg-[color:var(--surface-muted)] px-3 py-2">
          <p className="truncate text-sm font-medium text-strong">
            {issue.title}
          </p>
        </div>

        <Textarea
          ref={textareaRef}
          placeholder="Write your comment here…"
          value={body}
          onChange={(e) => setBody(e.target.value)}
          rows={5}
          disabled={isSubmitting}
          className="resize-none"
        />

        {error ? (
          <div className="rounded-lg border border-[color:rgba(248,113,113,0.35)] bg-[color:rgba(248,113,113,0.08)] p-3 text-xs text-[color:var(--danger)]">
            {error}
          </div>
        ) : null}

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isSubmitting}
          >
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={isSubmitting || !body.trim()}
          >
            {isSubmitting ? "Posting…" : "Post Comment"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
