import EditHouseForm from '@form/house/admin-edit-house-form';
import useHasPermission from '@hooks/use-has-permission';
import usePreventAutoFocus from '@hooks/use-prevent-auto-focus';
import { authClient } from '@lib/auth-client';
import { m } from '@paraglide/messages';
import { PenIcon } 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 { Skeleton } from '@ui/skeleton';
import { Tooltip, TooltipContent, TooltipTrigger } from '@ui/tooltip';
import { useState } from 'react';

type EditUserHouseProps = {
  data: ReturnType<typeof authClient.useActiveOrganization>['data'];
};

const EditUserHouseAction = ({ data }: EditUserHouseProps) => {
  const [_open, _setOpen] = useState(false);
  const prevent = usePreventAutoFocus();
  const { hasPermission, isLoading } = useHasPermission(
    'house',
    'update',
    true,
  );

  if (isLoading) {
    return <Skeleton className="h-8 w-8 rounded-full" />;
  }

  if (!hasPermission) return null;

  return (
    <Dialog open={_open} onOpenChange={_setOpen}>
      <Tooltip>
        <TooltipTrigger asChild>
          <DialogTrigger asChild>
            <Button
              type="button"
              size="icon-lg"
              className="rounded-full cursor-pointer bg-blue-500 text-white hover:bg-blue-100 hover:text-blue-600"
            >
              <PenIcon size={16} />
              <span className="sr-only">{m.ui_edit_house_btn()}</span>
            </Button>
          </DialogTrigger>
        </TooltipTrigger>
        <TooltipContent className="bg-blue-500 [&_svg]:bg-blue-500 [&_svg]:fill-blue-500 text-white">
          <Label>{m.ui_edit_house_btn()}</Label>
        </TooltipContent>
      </Tooltip>
      <DialogContent
        className="max-w-100 xl:max-w-2xl"
        {...prevent}
        onPointerDownOutside={(e) => e.preventDefault()}
      >
        <DialogHeader>
          <DialogTitle className="flex items-center gap-3 text-lg font-bold text-blue-600">
            <PenIcon size={16} />
            {m.ui_edit_house_btn()}
          </DialogTitle>
          <DialogDescription className="sr-only">
            {m.ui_edit_house_btn()}
          </DialogDescription>
        </DialogHeader>
        <EditHouseForm
          data={data as HouseWithMembers}
          onSubmit={_setOpen}
          mutateKey="currentUser"
        />
      </DialogContent>
    </Dialog>
  );
};

export default EditUserHouseAction;
