import useHasPermission from '@/hooks/use-has-permission';
import usePreventAutoFocus from '@/hooks/use-prevent-auto-focus';
import { m } from '@/paraglide/messages';
import { leaveHouse } from '@/service/house.api';
import { FootprintsIcon } from '@phosphor-icons/react';
import { useMutation } from '@tanstack/react-query';
import { Button } from '@ui/button';
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@ui/dialog';
import { Label } from '@ui/label';
import { Skeleton } from '@ui/skeleton';
import { Spinner } from '@ui/spinner';
import { Tooltip, TooltipContent, TooltipTrigger } from '@ui/tooltip';
import { useState } from 'react';
import { toast } from 'sonner';

type LeaveHouseProps = {
  activeHouseId: string;
};

const LeaveHouseAction = ({ activeHouseId }: LeaveHouseProps) => {
  const [_open, _setOpen] = useState(false);
  const prevent = usePreventAutoFocus();
  const { hasPermission, isLoading } = useHasPermission('house', 'leave', true);

  const { mutate: leaveHouseMutation, isPending } = useMutation({
    mutationFn: leaveHouse,
    onSuccess: () => {
      toast.success(m.houses_page_message_leave_house_success(), {
        richColors: true,
      });
    },
    onError: (error: ReturnError) => {
      const code = error.code as Parameters<
        typeof m.backend_message
      >[0]['code'];
      toast.error(m.backend_message({ code }), {
        richColors: true,
      });
    },
  });

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

  const onConfirm = async () => {
    leaveHouseMutation({ data: { id: activeHouseId } });
  };

  if (!hasPermission) return null;

  return (
    <Dialog open={_open} onOpenChange={_setOpen}>
      <Tooltip>
        <TooltipTrigger asChild>
          <DialogTrigger asChild>
            <Button
              type="button"
              variant="ghost"
              size="icon-lg"
              className="rounded-full cursor-pointer bg-red-500 text-white hover:bg-red-100 hover:text-red-600"
            >
              <FootprintsIcon size={16} />
              <span className="sr-only">{m.ui_leave_btn()}</span>
            </Button>
          </DialogTrigger>
        </TooltipTrigger>
        <TooltipContent className="bg-red-500 [&_svg]:bg-red-500 [&_svg]:fill-red-500 text-white">
          <Label>{m.ui_leave_btn()}</Label>
        </TooltipContent>
      </Tooltip>
      <DialogContent
        className="max-w-100 xl:max-w-xl"
        showCloseButton={false}
        {...prevent}
        onPointerDownOutside={(e) => e.preventDefault()}
        onEscapeKeyDown={(e) => e.preventDefault()}
      >
        <DialogHeader>
          <DialogTitle className="flex items-center gap-3 text-lg font-bold text-red-500">
            <div className="rounded-full bg-red-100 p-3">
              <FootprintsIcon size={30} />
            </div>
            {m.houses_page_ui_dialog_alert_leave_title()}
          </DialogTitle>
          <DialogDescription className="text-red-500 text-sm">
            {m.houses_page_ui_dialog_alert_leave_description()}
          </DialogDescription>
        </DialogHeader>
        <DialogFooter className="bg-muted/50 -mx-4 -mb-4 rounded-b-xl border-t p-4">
          <DialogClose asChild>
            <Button variant="outline" type="button">
              {m.ui_cancel_btn()}
            </Button>
          </DialogClose>
          <Button
            variant="destructive"
            type="button"
            onClick={onConfirm}
            disabled={isPending}
          >
            {isPending && <Spinner data-icon="inline-start" />}
            {m.ui_confirm_btn()}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default LeaveHouseAction;
