import { useState, useCallback } from "react";
import { Dialog, DialogContent, DialogTitle, DialogHeader } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

interface GoToLineDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onGoToLine: (line: number) => void;
  maxLine?: number;
}

export function GoToLineDialog({ open, onOpenChange, onGoToLine, maxLine }: GoToLineDialogProps) {
  const [value, setValue] = useState("");

  const handleGo = useCallback(() => {
    const line = parseInt(value, 10);
    if (!isNaN(line) && line > 0) {
      onGoToLine(line);
      onOpenChange(false);
      setValue("");
    }
  }, [value, onGoToLine, onOpenChange]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[300px] gap-3">
        <DialogHeader>
          <DialogTitle>Go to Line</DialogTitle>
        </DialogHeader>
        <div className="flex gap-2">
          <Input
            type="number"
            min={1}
            max={maxLine}
            placeholder={maxLine ? `Line (1-${maxLine})` : "Line number"}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") handleGo();
            }}
            autoFocus
          />
          <Button onClick={handleGo} size="default">
            Go
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
