import { m } from '@/paraglide/messages';
import useHasPermission from '@hooks/use-has-permission';
import usePreventAutoFocus from '@hooks/use-prevent-auto-focus';
import { cn } from '@lib/utils';
import { PlusIcon } from '@phosphor-icons/react';
import { Button } from '@ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@ui/dialog';
import { Skeleton } from '@ui/skeleton';
import { useState } from 'react';
import CreateNewBoxForm from '../form/box/create-new-box-form';

type CreateNewBoxProps = {
  className?: string;
};

const CreateBoxAction = ({ className }: CreateNewBoxProps) => {
  const { hasPermission, isLoading } = useHasPermission('box', 'create');
  const [_open, _setOpen] = useState(false);
  const prevent = usePreventAutoFocus();

  if (isLoading) {
    return <Skeleton className={cn('h-7 w-23', className)} />;
  }

  if (!hasPermission) return null;

  return (
    <Dialog open={_open} onOpenChange={_setOpen}>
      <DialogTrigger asChild>
        <Button type="button" variant="default" className={cn(className)}>
          <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>
        <CreateNewBoxForm />
      </DialogContent>
    </Dialog>
  );
};

export default CreateBoxAction;
