import axios from "axios";
import { useCallback, useContext, useReducer, useState } from "react";
import { ReloadDataTableContext } from "../contexts/ReloadDatatableContext";
import useUser from "./useUser";
import Notifications from "@/core/components/notifications";
import useDirection from "./useDirection";
import { useTranslations } from "next-intl";

const initialValues = {
  url: "",
  rowID: "",
  values: {},
};

const reducer = (state, action) => {
  switch (action.type) {
    case "CONFIRM_DATA":
      return {
        ...state,
        url: action.url,
        rowID: action.rowID,
      };
    case "REJECT_DATA":
      return {
        ...state,
        url: action.url,
        rowID: action.rowID,
        values: {},
      };
    default:
      return state;
  }
};

const useDataTable = () => {
  const { setReloadDataTable } = useContext(ReloadDataTableContext);
  const [state, dispatch] = useReducer(reducer, initialValues);
  const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
  const [openRejectDialog, setOpenRejectDialog] = useState(false);
  const [rowId, setRowId] = useState(null);
  const { directionApp } = useDirection();
  const t = useTranslations();

  const { token } = useUser();

  const confirmData = useCallback(async (url, rowID) => {
    dispatch({ type: "CONFIRM_DATA", url: url, rowID: rowID });
    axios
      .post(`${url}/${rowID}`, null, {
        headers: { authorization: `Bearer ${token}` },
      })
      .then(() => {
        setReloadDataTable(true);
      })
      .catch((error) => {
        Notifications(directionApp, error.response, t);
      });
  }, []);

  const rejectData = useCallback(async (url, rowID, values) => {
    dispatch({ type: "REJECT_DATA", url: url, rowID: rowID, values: values });
    axios
      .post(`${url}/${rowID}`,values, {
        headers: { authorization: `Bearer ${token}` },
      })
      .then(() => {
        setReloadDataTable(true);
      })
      .catch((error) => {
        Notifications(directionApp, error.response, t);
      });
  }, []);

  //Confirm Data
  const handleOpenConfirmDialog = (row) => {
    setRowId(row.getValue("id"));
    setOpenConfirmDialog(true);
  };

  const handleCloseConfirmDialog = () => {
    setOpenConfirmDialog(false);
  };
  //End Confirm Data

  // Reject Data
  const handleOpenRejectDialog = (row) => {
    setRowId(row.getValue("id"));
    setOpenRejectDialog(true);
  };

  const handleCloseRejectDialog = () => {
    setOpenRejectDialog(false);
  };
  // End Reject Data

  const contextValue = {
    handleOpenConfirmDialog,
    handleCloseConfirmDialog,
    handleOpenRejectDialog,
    handleCloseRejectDialog,
    rowId,
    openConfirmDialog,
    openRejectDialog,
    rejectData,
    confirmData,
  };
  return contextValue;
};

export default useDataTable;
