import axios, { AxiosResponse } from "axios";
import moment from "moment";
import { AnyAction } from "redux";
import { ThunkAction, ThunkDispatch } from "redux-thunk";

import {
    GET_PERMIT_FORM_DATA_FAILED,
    GET_PERMIT_FORM_DATA_REQUEST,
    GET_PERMIT_FORM_DATA_SUCCESS,
    SUBMIT_PERMIT_FAILED,
    SUBMIT_PERMIT_REQUEST,
    SUBMIT_PERMIT_SUCCESS,
} from "./types";

import config from '../../config/config';
import { axiosErrorMessage } from "../../utils/helper";
import { RootState } from "../store";
import { addHistory } from "./historyScreenActions";

// Thunk Type
type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  AnyAction
>;

/**
 * ✅ Fetch Permit Form Data
 */
export const getPermitFormData = (): AppThunk<Promise<void>> => {
  return async (dispatch: ThunkDispatch<RootState, unknown, AnyAction>) => {
    dispatch({ type: GET_PERMIT_FORM_DATA_REQUEST });

    try {
      const res: AxiosResponse<any> = await axios.get(
        `${config.apiserver}/api/v1/permit-management/get-permit-templateforms`
      );
      dispatch({
        type: GET_PERMIT_FORM_DATA_SUCCESS,
        payload: res.data,
      });
    } catch (error: any) {
      console.log("GET_PERMIT_FORM_DATA_FAILED", error);
      axiosErrorMessage(
        "Something went wrong while fetching permit form data. Try to sync again",
        error
      );
      dispatch({
        type: GET_PERMIT_FORM_DATA_FAILED,
        payload: error,
      });
    }
  };
};

/**
 * ✅ Submit Permit Form
 */
export const submitPermit = (data: any): AppThunk => {
  return async (): Promise<AnyAction> => {
    const {
      title,
      body,
      field_job_details,
      field_job_location,
      field_start_date,
      field_end_date,
      field_invited_contractor,
      webform,
    } = data;

    const localFormat = "YYYY-MM-DD";

    const postData = {
      title,
      body,
      field_start_date: moment.utc(field_start_date).format(localFormat),
      field_end_date: moment.utc(field_end_date).format(localFormat),
      field_job_details,
      field_job_location: field_job_location[0]?.toString() || "",
      field_invited_contractor,
      webform: webform[0]?.toString() || "",
    };

    const formattedDate = moment().format("DD-MM-YYYY");
    const formattedTime = moment().format("h:mm:ss a");

    addHistory({
      title: `${title} has submitted on ${formattedDate} at ${formattedTime}`,
      data: postData,
      url: `${config.apiserver}/api/v1/permit_management/create-permit`,
    });

    return {
      type: SUBMIT_PERMIT_REQUEST,
      payload: {},
      meta: {
        offline: {
          effect: {
            url: `${config.apiserver}/api/v1/permit_management/create-permit`,
            method: "POST",
            data: postData,
            headers: {
              "Content-Type": "application/json",
              Accept: "application/json",
            },
          },
          commit: { type: SUBMIT_PERMIT_SUCCESS, meta: {} },
          rollback: {
            type: SUBMIT_PERMIT_FAILED,
            meta: {
              title,
              url: `${config.apiserver}/api/v1/permit_management/create-permit`,
              data: postData,
            },
          },
        },
      },
    };
  };
};
