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 { useCreateRole, 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 CreateRoleDialog({ open, onOpenChange, connectionId }: Props) {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [login, setLogin] = useState(true);
  const [superuser, setSuperuser] = useState(false);
  const [createdb, setCreatedb] = useState(false);
  const [createrole, setCreaterole] = useState(false);
  const [inherit, setInherit] = useState(true);
  const [replication, setReplication] = useState(false);
  const [connectionLimit, setConnectionLimit] = useState(-1);
  const [validUntil, setValidUntil] = useState("");
  const [inRoles, setInRoles] = useState<string[]>([]);

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

  const [prevOpen, setPrevOpen] = useState(false);
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (open) {
      setName("");
      setPassword("");
      setLogin(true);
      setSuperuser(false);
      setCreatedb(false);
      setCreaterole(false);
      setInherit(true);
      setReplication(false);
      setConnectionLimit(-1);
      setValidUntil("");
      setInRoles([]);
    }
  }

  const handleCreate = () => {
    if (!name.trim()) {
      toast.error("Role name is required");
      return;
    }
    createMutation.mutate(
      {
        connectionId,
        params: {
          name: name.trim(),
          password: password || undefined,
          login,
          superuser,
          createdb,
          createrole,
          inherit,
          replication,
          connection_limit: connectionLimit,
          valid_until: validUntil || undefined,
          in_roles: inRoles,
        },
      },
      {
        onSuccess: () => {
          toast.success(`Role "${name}" created`);
          onOpenChange(false);
        },
        onError: (err) => {
          toast.error("Failed to create role", { description: String(err) });
        },
      }
    );
  };

  const toggleInRole = (roleName: string) => {
    setInRoles((prev) =>
      prev.includes(roleName)
        ? prev.filter((r) => r !== roleName)
        : [...prev, roleName]
    );
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>Create Role</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_role"
            />
          </div>
          <div className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Password</label>
            <Input
              className="col-span-3"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Optional"
            />
          </div>

          <div className="grid grid-cols-4 items-start gap-3">
            <label className="text-right text-sm text-muted-foreground pt-1">Privileges</label>
            <div className="col-span-3 grid grid-cols-2 gap-2">
              {([
                ["LOGIN", login, setLogin],
                ["SUPERUSER", superuser, setSuperuser],
                ["CREATEDB", createdb, setCreatedb],
                ["CREATEROLE", createrole, setCreaterole],
                ["INHERIT", inherit, setInherit],
                ["REPLICATION", replication, setReplication],
              ] as const).map(([label, value, setter]) => (
                <label key={label} className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    checked={value}
                    onChange={(e) => (setter as (v: boolean) => void)(e.target.checked)}
                    className="rounded border-input"
                  />
                  {label}
                </label>
              ))}
            </div>
          </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 className="grid grid-cols-4 items-center gap-3">
            <label className="text-right text-sm text-muted-foreground">Valid Until</label>
            <Input
              className="col-span-3"
              type="datetime-local"
              value={validUntil}
              onChange={(e) => setValidUntil(e.target.value)}
            />
          </div>

          {roles && roles.length > 0 && (
            <div className="grid grid-cols-4 items-start gap-3">
              <label className="text-right text-sm text-muted-foreground pt-1">Member Of</label>
              <div className="col-span-3 flex flex-wrap gap-1.5">
                {roles.map((r) => (
                  <button
                    key={r.name}
                    type="button"
                    className={`rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
                      inRoles.includes(r.name)
                        ? "border-primary bg-primary text-primary-foreground"
                        : "border-border text-muted-foreground hover:text-foreground"
                    }`}
                    onClick={() => toggleInRole(r.name)}
                  >
                    {r.name}
                  </button>
                ))}
              </div>
            </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>
  );
}
