import { ReactElement } from "react";
import { useModalStore } from "../../context/zustand-store/appStore";
import { useUserProfileStore } from "../../context/zustand-store/userStore";
import { useToast } from "../../hooks/useToast";
import { useApiMutation } from "../../utils/useApiRequest";
import Button from "../Button/Button";
import { Grid } from "../Grid/Grid";
import { Tooltip } from "../Tooltip/Tooltip";
import { motion } from "framer-motion";

type Props = {
  api?: string;
  title?: string;
  tooltipText?: string;
  getData?: () => void;
  page?: string;
  access?: string;
  method?: "delete" | "post" | "put" | "patch";
  icon?: ReactElement;
};

export const PopoverCustomModalOperation = ({
  api,
  title,
  method = "delete",
  tooltipText,
  getData,
  page = "",
  access = "",
  icon,
}: Props) => {
  const { openModal, closeModal } = useModalStore();
  const showToast = useToast();
  const { profile } = useUserProfileStore();

  const mutation = useApiMutation({
    api: api || "",
    method: method || "delete",
  });

  const ableToSeeButton = () => {
    if (!access || !page) {
      return true;
    } else {
      const finded = profile?.permissions?.find(
        (item: any) => item.page_name === page
      );
      if (finded && finded.page_access.includes(access)) {
        return true;
      } else {
        return false;
      }
    }
  };

  const onSubmit = async () => {
    try {
      await mutation.mutateAsync({});
      showToast("عملیات با موفقیت انجام شد", "success");

      closeModal();
      if (getData) {
        getData();
      }
    } catch (error: any) {
      if (error?.status === 400) {
        showToast(
          error?.response?.data?.detail ||
            error?.response?.data?.message + " !",
          "error"
        );
      } else {
        showToast("مشکلی پیش آمده است!", "error");
      }
      closeModal();
    }
  };

  if (!ableToSeeButton()) {
    return null;
  }

  return (
    <Tooltip title={tooltipText || ""} position="right">
      <Button
        icon={icon}
        onClick={() => {
          openModal({
            title: title || "آیا از انجام عملیات مطمئنید؟",
            content: (
              <Grid
                container
                xs="full"
                column
                className="flex justify-center items-center"
              >
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3 }}
                  className="w-full max-w-md p-4"
                >
                  <Grid container className="flex-row space-y-0 space-x-4">
                    <Button
                      onClick={() => {
                        onSubmit();
                      }}
                      fullWidth
                      className="bg-[#eb5757] hover:bg-[#d44e4e] text-white py-3 rounded-lg transition-all duration-300 transform hover:scale-[1.02] shadow-md"
                    >
                      بله
                    </Button>
                    <Button
                      onClick={() => closeModal()}
                      fullWidth
                      className="bg-gray-200 text-gray-700 hover:bg-gray-100 py-3 rounded-lg transition-all duration-300 transform hover:scale-[1.02] shadow-md"
                    >
                      خیر
                    </Button>
                  </Grid>
                </motion.div>
              </Grid>
            ),
          });
        }}
      />
    </Tooltip>
  );
};
