import AdminCreateUserForm from '@form/user/admin-create-user-form';
import useHasPermission from '@hooks/use-has-permission';
import usePreventAutoFocus from '@hooks/use-prevent-auto-focus';
import { m } from '@paraglide/messages';
import { PlusIcon } from '@phosphor-icons/react';
import { Button } from '@ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@ui/dialog';
import { useState } from 'react';

const AddNewUserButton = () => {
  const { hasPermission, isLoading } = useHasPermission('user', 'create');
  const [_open, _setOpen] = useState(false);
  const prevent = usePreventAutoFocus();

  if (isLoading) return null;

  if (hasPermission) {
    return (
      <Dialog open={_open} onOpenChange={_setOpen}>
        <DialogTrigger asChild>
          <Button type="button" variant="default" className="cursor-pointer">
            <PlusIcon />
            {m.nav_add_new()}
          </Button>
        </DialogTrigger>
        <DialogContent
          className="max-w-80 xl:max-w-xl"
          {...prevent}
          onPointerDownOutside={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-3 text-lg font-bold text-primary">
              <PlusIcon size={16} />
              {m.nav_add_new()}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {m.nav_add_new()}
            </DialogDescription>
          </DialogHeader>
          <AdminCreateUserForm onSubmit={_setOpen} />
        </DialogContent>
      </Dialog>
    );
  }

  return null;
};

export default AddNewUserButton;
