import BanUserForm from '@form/user/admin-ban-user-form';
import useHasPermission from '@hooks/use-has-permission';
import usePreventAutoFocus from '@hooks/use-prevent-auto-focus';
import { m } from '@paraglide/messages';
import { LockIcon } from '@phosphor-icons/react';
import { useRouteContext } from '@tanstack/react-router';
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 { createContext, useContext, useState } from 'react';
import BanUserConfirm from './ban-user-confirm-dialog';

type ChangeUserStatusProps = {
  data: UserWithRole;
};

type SubmitValue = {
  id: string;
  banReason: string;
  banExp: number;
};

type BanContextProps = {
  open: boolean;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
  openConfirm: boolean;
  setOpenConfirm: React.Dispatch<React.SetStateAction<boolean>>;
  submitData: SubmitValue;
  setSubmitData: React.Dispatch<React.SetStateAction<SubmitValue>>;
};

const BanContext = createContext<BanContextProps | null>(null);

const BanUserAction = ({ data }: ChangeUserStatusProps) => {
  const { session } = useRouteContext({ from: '__root__' });
  const isCurrentUser = session?.user.id === data.id;
  const { hasPermission, isLoading } = useHasPermission('user', 'ban');
  const [_open, _setOpen] = useState(false);
  const [_openConfirm, _setOpenConfirm] = useState(false);
  const [_confirmData, _setConfirmData] = useState<SubmitValue>({
    id: '',
    banReason: '',
    banExp: 0,
  });
  const prevent = usePreventAutoFocus();

  if (isCurrentUser || isLoading) return null;

  if (hasPermission) {
    return (
      <BanContext
        value={{
          open: _open,
          setOpen: _setOpen,
          openConfirm: _openConfirm,
          setOpenConfirm: _setOpenConfirm,
          submitData: _confirmData,
          setSubmitData: _setConfirmData,
        }}
      >
        <Dialog open={_open} onOpenChange={_setOpen}>
          <Tooltip>
            <TooltipTrigger asChild>
              <DialogTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="rounded-full cursor-pointer text-red-500 hover:bg-red-100 hover:text-red-600"
                >
                  <LockIcon size={16} />
                  <span className="sr-only">{m.ui_ban_btn()}</span>
                </Button>
              </DialogTrigger>
            </TooltipTrigger>
            <TooltipContent className="bg-red-500 [&_svg]:bg-red-500 [&_svg]:fill-red-500 text-white">
              <Label>{m.ui_ban_btn()}</Label>
            </TooltipContent>
          </Tooltip>
          <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-red-600">
                <LockIcon size={16} />
                {m.ui_ban_btn()}
              </DialogTitle>
              <DialogDescription className="sr-only">
                {m.ui_change_role_btn()}
              </DialogDescription>
            </DialogHeader>
            <BanUserForm data={data} />
          </DialogContent>
        </Dialog>
        <BanUserConfirm data={data} />
      </BanContext>
    );
  }
  return null;
};

export default BanUserAction;

export function useBanContext() {
  const context = useContext(BanContext);

  if (!context) {
    throw new Error('SHOULD_HAVE_PROVIDER');
  }

  return context;
}
