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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useCreateDatabase, useRoles } from "@/hooks/use-management";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

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

export function CreateDatabaseDialog({ open, onOpenChange, connectionId }: Props) {
  const [name, setName] = useState("");
  const [owner, setOwner] = useState("__default__");
  const [template, setTemplate] = useState("__default__");
  const [encoding, setEncoding] = useState("UTF8");
  const [connectionLimit, setConnectionLimit] = useState(-1);

  const { data: roles } = useRoles(open ? connectionId : null);
  const createMutation = useCreateDatabase();

  const [prevOpen, setPrevOpen] = useState(false);
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (open) {
      setName("");
      setOwner("__default__");
      setTemplate("__default__");
      setEncoding("UTF8");
      setConnectionLimit(-1);
    }
  }

  const handleCreate = () => {
    if (!name.trim()) {
      toast.error("Database name is required");
      return;
    }
    createMutation.mutate(
      {
        connectionId,
        params: {
          name: name.trim(),
          owner: owner === "__default__" ? undefined : owner,
          template: template === "__default__" ? undefined : template,
          encoding,
          connection_limit: connectionLimit,
        },
      },
      {
        onSuccess: () => {
          toast.success(`Database "${name}" created`);
          onOpenChange(false);
        },
        onError: (err) => {
          toast.error("Failed to create database", { description: String(err) });
        },
      }
    );
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>Create Database</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_database"
            />
          </div>
          <div className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Owner</label>
            <Select value={owner} onValueChange={setOwner}>
              <SelectTrigger className="col-span-3">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__default__">Default</SelectItem>
                {roles?.map((r) => (
                  <SelectItem key={r.name} value={r.name}>
                    {r.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Template</label>
            <Select value={template} onValueChange={setTemplate}>
              <SelectTrigger className="col-span-3">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__default__">Default</SelectItem>
                <SelectItem value="template0">template0</SelectItem>
                <SelectItem value="template1">template1</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Encoding</label>
            <Select value={encoding} onValueChange={setEncoding}>
              <SelectTrigger className="col-span-3">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="UTF8">UTF8</SelectItem>
                <SelectItem value="LATIN1">LATIN1</SelectItem>
                <SelectItem value="SQL_ASCII">SQL_ASCII</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Conn Limit</label>
            <Input
              className="col-span-3"
              type="number"
              value={connectionLimit}
              onChange={(e) => setConnectionLimit(parseInt(e.target.value) || -1)}
            />
          </div>
        </div>

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