import AdminSetPasswordForm from '@form/user/admin-set-password-form';
import useHasPermission from '@hooks/use-has-permission';
import usePreventAutoFocus from '@hooks/use-prevent-auto-focus';
import { m } from '@paraglide/messages';
import { KeyIcon } from '@phosphor-icons/react';
import { Button } from '@ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@ui/dialog';
import { Label } from '@ui/label';
import { Tooltip, TooltipContent, TooltipTrigger } from '@ui/tooltip';
import { UserWithRole } from 'better-auth/plugins';
import { useState } from 'react';

type UpdatePasswordProps = {
  data: UserWithRole;
};

const SetPasswordAction = ({ data }: UpdatePasswordProps) => {
  const [_open, _setOpen] = useState(false);
  const prevent = usePreventAutoFocus();
  const { hasPermission, isLoading } = useHasPermission('user', 'set-password');

  if (isLoading) return null;

  if (hasPermission) {
    return (
      <Dialog open={_open} onOpenChange={_setOpen}>
        <Tooltip>
          <TooltipTrigger asChild>
            <DialogTrigger asChild>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="rounded-full cursor-pointer text-stone-500 hover:bg-stone-100 hover:text-stone-600"
              >
                <KeyIcon size={16} />
                <span className="sr-only">{m.ui_update_password_btn()}</span>
              </Button>
            </DialogTrigger>
          </TooltipTrigger>
          <TooltipContent className="bg-stone-500 [&_svg]:bg-stone-500 [&_svg]:fill-stone-500 text-white">
            <Label>{m.ui_update_password_btn()}</Label>
          </TooltipContent>
        </Tooltip>
        <DialogContent
          className="max-w-80 xl:max-w-sm"
          {...prevent}
          onPointerDownOutside={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-3 text-lg font-bold text-stone-600">
              <KeyIcon size={20} />
              {m.ui_update_password_btn()}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {m.ui_update_password_btn()}
            </DialogDescription>
          </DialogHeader>
          <AdminSetPasswordForm data={data} onSubmit={_setOpen} />
        </DialogContent>
      </Dialog>
    );
  }
};

export default SetPasswordAction;
