import { motion } from "framer-motion";
import { useModalStore } from "../../context/zustand-store/appStore";
import { Grid } from "../Grid/Grid";
import Button from "../Button/Button";
import { useToast } from "../../hooks/useToast";
import { useApiMutation } from "../../utils/useApiRequest";
import Typography from "../Typography/Typography";

type Props = {
  api?: string;
  getData?: () => void;
  method?: "post" | "put" | "delete" | "patch";
  title?: string;
  isAlert?: boolean;
  payload?: any;
};

export const BooleanQuestion = ({
  api = "",
  getData,
  method = "post",
  title = "",
  isAlert = false,
  payload = {},
}: Props) => {
  const { closeModal } = useModalStore();
  const showToast = useToast();

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

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

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

  return (
    <Grid
      container
      xs="full"
      column
      className="flex justify-center items-start"
    >
      {title && (
        <Typography variant="body2" className="text-start mb-2">
          {title}
        </Typography>
      )}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="w-full max-w-md p-2"
      >
        <Grid container className="flex-row space-y-0 space-x-4">
          <Button
            onClick={() => {
              onSubmit();
            }}
            fullWidth
            className={`${
              isAlert
                ? "bg-[#eb5757] hover:bg-[#d44e4e]"
                : "bg-primary-600 hover:bg-primary-500"
            } text-white py-3 rounded-lg transition-all duration-300 transform hover:scale-[1.02] shadow-md`}
          >
            بله
          </Button>
          <Button
            onClick={() => closeModal()}
            fullWidth
            className={`${
              isAlert
                ? "bg-gray-200 text-gray-700 hover:bg-gray-100"
                : "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>
  );
};
