import CreateNewHouseForm from '@form/house/admin-create-house-form';
import useHasPermission from '@hooks/use-has-permission';
import usePreventAutoFocus from '@hooks/use-prevent-auto-focus';
import { cn } from '@lib/utils';
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';
import { Skeleton } from '../ui/skeleton';

type CreateNewHouseProp = {
  isPersonal?: boolean;
  className?: string;
};

const CreateNewHouse = ({
  className,
  isPersonal = false,
}: CreateNewHouseProp) => {
  const { hasPermission, isLoading } = useHasPermission('house', '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>
        <CreateNewHouseForm onSubmit={_setOpen} isPersonal={isPersonal} />
      </DialogContent>
    </Dialog>
  );
};

export default CreateNewHouse;
