import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useSaveQuery } from "@/hooks/use-saved-queries";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  sql: string;
  connectionId: string;
}

export function SaveQueryDialog({ open, onOpenChange, sql, connectionId }: Props) {
  const [name, setName] = useState("");
  const saveMutation = useSaveQuery();

  const [prevOpen, setPrevOpen] = useState(false);
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (open) setName("");
  }

  const handleSave = () => {
    if (!name.trim()) {
      toast.error("Query name is required");
      return;
    }
    saveMutation.mutate(
      {
        id: crypto.randomUUID(),
        name: name.trim(),
        sql,
        connection_id: connectionId,
        created_at: new Date().toISOString(),
      },
      {
        onSuccess: () => {
          toast.success(`Query "${name}" saved`);
          onOpenChange(false);
        },
        onError: (err) => {
          toast.error("Failed to save query", { description: String(err) });
        },
      }
    );
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[400px]">
        <DialogHeader>
          <DialogTitle>Save Query</DialogTitle>
        </DialogHeader>

        <div className="grid gap-3 py-4">
          <div className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Name</label>
            <Input
              className="col-span-3"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="My query"
              onKeyDown={(e) => e.key === "Enter" && handleSave()}
              autoFocus
            />
          </div>
          <div className="grid grid-cols-4 items-start gap-3">
            <label className="text-right text-sm text-muted-foreground pt-1">SQL</label>
            <pre className="col-span-3 rounded bg-muted p-2 text-xs max-h-32 overflow-auto font-mono">
              {sql.length > 200 ? sql.slice(0, 200) + "..." : sql}
            </pre>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={saveMutation.isPending}>
            {saveMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
