import {
  attemptAddOffer,
  attemptEditOffer,
  attemptFetchOffers,
  attemptFetchOneOffer,
  attemptRemoveOffer,
} from "../../request/offersRequest";
import {
  OFFERS_FETCH,
  OFFERS_PROFILE_FETCH,
  OFFER_ADD,
  OFFER_EDIT,
  OFFER_REMOVE,
  ONE_OFFER_FETCH,
} from "../actions/offers/offersActionConstants";
import {
  setOffers,
  setProfileOffers,
  fetchOneOfferSuccess,
  addOfferSuccess,
  fetchMineOffersSuccess,
  fetchProfileOffersSuccess,
  removeOfferSuccess,
  editOfferSuccess,
  fetchOffersSuccess,
  fetchOffersError,
  fetchMoreOffersSuccess,
  fetchMoreOffersError,
  addOfferError,
  fetchOneOfferError,
  fetchMineOffersError,
  fetchProfileOffersError,
  removeOfferError,
  editOfferError,
} from "../actions/offers/offersActions";
import { all, takeLatest, call, put, select } from "@redux-saga/core/effects";
import {
  attemptFetchProfileOffers,
  attemptFetchMoreOffers,
} from "../../request/offersRequest";
import { convertQueryStringForBackend } from "../../util/helpers/queryHelpers";
// import { setQueryString } from "../actions/filters/filtersActions";
import {
  OFFERS_FETCH_MORE,
  OFFERS_MINE_FETCH,
} from "../actions/offers/offersActionConstants";
import {
  addOffers,
  addPinnedOffers,
  clearOffers,
  setMineOffers,
  setNoMoreOffersStatus,
  setPinnedOffers,
  setTotalOffers,
} from "../actions/offers/offersActions";
import { selectUserId } from "../selectors/loginSelectors";
import {
  selectOffers,
  selectPinnedOffers,
  selectTotalOffers,
} from "../selectors/offersSelectors";
import history from "../utils/history";
import { NOT_FOUND_PAGE } from "../../constants/pages";

function* fetchOffers(payload) {
  try {
    yield put(clearOffers());
    const newQueryString = new URLSearchParams(
      convertQueryStringForBackend(payload.payload.queryString)
    );
    const data = yield call(
      attemptFetchOffers,
      "?" + newQueryString.toString()
    );
    console.log("data::::::::: ", data.data);
    yield put(setTotalOffers(data.data.total));
    yield put(setOffers(data.data.items.regularOffers));
    yield put(setPinnedOffers(data.data.items.pinnedOffers));
    yield put(fetchOffersSuccess());
  } catch (e) {
    yield put(fetchOffersError());
    yield call(console.log, e);
  }
}
function* fetchMoreOffers(payload) {
  try {
    const data = yield call(
      attemptFetchMoreOffers,
      payload.payload?.page,
      payload.payload?.queryString
    );
    // if (payload.payload.queryString) {
    //   yield put(setQueryString(payload.payload.queryString));
    // }
    const oldOffers = yield select(selectOffers);
    const oldPinnedOffers = yield select(selectPinnedOffers);
    const totalNumberOfOffers = yield select(selectTotalOffers);
    if (oldOffers.length + oldPinnedOffers.length < totalNumberOfOffers) {
      yield put(addOffers(data.data.items.regularOffers));
      yield put(addPinnedOffers(data.data.items.pinnedOffers));
    }
    if (
      data.data.items.pinnedOffers.length +
        data.data.items.regularOffers.length <
        10 ||
      data.data.items.pinnedOffers.length +
        data.data.items.regularOffers.length >
        data.data.total
    ) {
      yield put(setNoMoreOffersStatus(true));
    }
    yield put(fetchMoreOffersSuccess());
  } catch (e) {
    yield put(fetchMoreOffersError());
    console.log(e);
  }
}

function* createOffer(payload) {
  try {
    console.log(payload.payload);
    yield call(attemptAddOffer, payload.payload.values.offerData);
    yield put(addOfferSuccess());
    if (payload.payload.handleApiResponseSuccess) {
      yield call(payload.payload.handleApiResponseSuccess);
    }
  } catch (e) {
    yield put(addOfferError());
    console.log(e);
  }
}

function* fetchOneOffer(payload) {
  try {
    const data = yield call(attemptFetchOneOffer, payload.payload);
    yield put(fetchOneOfferSuccess(data.data));
  } catch (e) {
    console.log(e.response.status);
    if (e.response.status === 400) {
      yield call(history.push, NOT_FOUND_PAGE);
    }
    yield put(fetchOneOfferError());
  }
}

// function* createOffer(payload) {
function* fetchMineOffers() {
  try {
    const userId = yield select(selectUserId);
    const data = yield call(attemptFetchProfileOffers, userId);
    yield put(setMineOffers(data.data));
    yield put(fetchMineOffersSuccess());
  } catch (e) {
    yield put(fetchMineOffersError());
    console.log(e);
  }
}

function* fetchProfileOffers(payload) {
  try {
    const userId = payload.payload;
    if (!userId || userId?.length === 0)
      throw new Error("User id is not defined!");
    const data = yield call(attemptFetchProfileOffers, userId);
    yield put(setProfileOffers(data.data));
    yield put(fetchProfileOffersSuccess());
  } catch (e) {
    console.log(e);
    if (e.response.status === 400) {
      yield call(history.push, NOT_FOUND_PAGE);
    }
    yield put(fetchProfileOffersError());
  }
}

function* removeOffer(payload) {
  try {
    const offerId = payload.payload.offerId;
    yield call(attemptRemoveOffer, offerId);
    yield put(removeOfferSuccess());
    if (payload.payload.handleApiResponseSuccess) {
      yield call(payload.payload.handleApiResponseSuccess);
    }
  } catch (e) {
    yield put(removeOfferError());
    console.log(e);
  }
}

function* editOffer(payload) {
  try {
    const offerId = payload.payload.offerId;
    const editedData = payload.payload.offerData;
    yield call(attemptEditOffer, offerId, editedData);
    yield put(editOfferSuccess());
    if (payload.payload.handleApiResponseSuccess) {
      yield call(payload.payload.handleApiResponseSuccess);
    }
  } catch (e) {
    yield put(editOfferError());
    console.log(e);
  }
}

export default function* offersSaga() {
  yield all([
    takeLatest(OFFERS_FETCH, fetchOffers),
    takeLatest(OFFER_ADD, createOffer),
    takeLatest(ONE_OFFER_FETCH, fetchOneOffer),
    takeLatest(OFFERS_FETCH_MORE, fetchMoreOffers),
    takeLatest(OFFERS_MINE_FETCH, fetchMineOffers),
    takeLatest(OFFERS_PROFILE_FETCH, fetchProfileOffers),
    takeLatest(OFFER_REMOVE, removeOffer),
    takeLatest(OFFER_EDIT, editOffer),
  ]);
}
