import { createStore } from "vuex";
import {
  datetimeToISO,
  dateToISO,
  ISOToDate,
} from "ChillMainAssets/chill/js/date";
import { findSocialActionsBySocialIssue } from "ChillPersonAssets/vuejs/_api/SocialWorkSocialAction.js";
// import { create } from 'ChillPersonAssets/vuejs/_api/AccompanyingCourseWork.js';
import { fetchResults, makeFetch } from "ChillMainAssets/lib/api/apiMethods";

const debug = process.env.NODE_ENV !== "production";

const store = createStore({
  strict: debug,
  state: {
    accompanyingCourse: window.accompanyingCourse,
    socialIssues: window.accompanyingCourse.socialIssues,
    socialIssuePicked: null,
    socialIssuesOther: [],
    socialActionsReachables: [],
    socialActionPicked: null,
    personsPicked: window.accompanyingCourse.participations
      .filter((p) => p.endDate == null)
      .map((p) => p.person),
    personsReachables: window.accompanyingCourse.participations
      .filter((p) => p.endDate == null)
      .map((p) => p.person),
    startDate: dateToISO(new Date()),
    endDate: null,
    isLoadingSocialActions: false,
    isPostingWork: false,
    errors: [],
  },
  getters: {
    hasSocialActionPicked(state) {
      return null !== state.socialActionPicked;
    },
    hasSocialIssuePicked(state) {
      return null !== state.socialIssuePicked;
    },
    isLoadingSocialActions(state) {
      return state.isLoadingSocialActions;
    },
    isPostingWork(state) {
      return state.isPostingWork;
    },
    buildPayloadCreate(state) {
      let payload = {
        type: "accompanying_period_work",
        socialAction: {
          type: "social_work_social_action",
          id: state.socialActionPicked.id,
        },
        startDate: {
          datetime: datetimeToISO(ISOToDate(state.startDate)),
        },
        persons: [],
      };

      for (let i in state.personsPicked) {
        payload.persons.push({
          id: state.personsPicked[i].id,
          type: "person",
        });
      }

      if (null !== state.endDate) {
        payload.endDate = {
          datetime: datetimeToISO(ISOToDate(state.endDate)),
        };
      }

      return payload;
    },
    hasErrors(state) {
      return state.errors.length > 0;
    },
  },
  mutations: {
    setSocialActionsReachables(state, actions) {
      state.socialActionsReachables = actions;
    },
    setSocialAction(state, socialAction) {
      state.socialActionPicked = socialAction;
    },
    setSocialIssue(state, socialIssueId) {
      if (socialIssueId === null) {
        state.socialIssuePicked = null;
      } else {
        let mapped = state.socialIssues.find((e) => e.id === socialIssueId);
        state.socialIssuePicked = mapped;
      }
    },
    addIssueInList(state, issue) {
      state.socialIssues.push(issue);
    },
    updateIssuesOther(state, payload) {
      state.socialIssuesOther = payload;
    },
    removeIssueInOther(state, issue) {
      state.socialIssuesOther = state.socialIssuesOther.filter(
        (i) => i.id !== issue.id,
      );
    },
    updateSelected(state, payload) {
      state.socialIssueSelected = payload;
    },
    setIsLoadingSocialActions(state, s) {
      state.isLoadingSocialActions = s;
    },
    setPostingWork(state) {
      state.isPostingWork = true;
    },
    setPostingWorkDone(state) {
      state.isPostingWork = false;
    },
    setStartDate(state, date) {
      state.startDate = date;
    },
    setEndDate(state, date) {
      console.log(date);
      state.endDate = date;
    },
    setPersonsPickedIds(state, ids) {
      state.personsPicked = state.personsReachables.filter((p) =>
        ids.includes(p.id),
      );
    },
    addErrors(state, { errors, cancel_posting }) {
      state.errors = errors;
      if (cancel_posting) {
        state.isPostingWork = false;
      }
    },
  },
  actions: {
    pickSocialIssue({ commit }, socialIssueId) {
      commit("setIsLoadingSocialActions", true);
      commit("setSocialAction", null);
      commit("setSocialActionsReachables", []);
      commit("setSocialIssue", null);

      findSocialActionsBySocialIssue(socialIssueId)
        .then((response) => {
          commit("setSocialIssue", socialIssueId);
          commit("setSocialActionsReachables", response.results);
          commit("setIsLoadingSocialActions", false);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    submit({ commit, getters, state }) {
      let payload = getters.buildPayloadCreate;
      const url = `/api/1.0/person/accompanying-course/${state.accompanyingCourse.id}/work.json`;
      commit("setPostingWork");

      return makeFetch("POST", url, payload)
        .then((response) => {
          window.location.assign(
            `/fr/person/accompanying-period/work/${response.id}/edit`,
          );
        })
        .catch((error) => {
          commit("setPostingWorkDone");
          throw error;
        });
    },
    fetchOtherSocialIssues({ commit }) {
      const url = `/api/1.0/person/social-work/social-issue.json`;
      return fetchResults(url)
        .then((response) => {
          commit("updateIssuesOther", response); // Directly commit the array of issues
        })
        .catch((error) => {
          throw error;
        });
    },
  },
});

store.dispatch("fetchOtherSocialIssues");

export { store };
