<template>
  <h2>{{ $t("pick_social_issue") }}</h2>

  <div id="awc_create_form">
    <div id="picking" class="">
      <p>{{ $t("pick_social_issue_linked_with_action") }}</p>
      <div v-for="si in socialIssues" :key="si.id">
        <input
          type="radio"
          :value="si.id"
          name="socialIssue"
          v-model="socialIssuePicked"
        /><span class="badge bg-chill-l-gray text-dark">{{ si.text }}</span>
      </div>
      <div class="my-3">
        <div class="col-11">
          <vue-multiselect
            name="otherIssues"
            label="text"
            track-by="id"
            open-direction="bottom"
            :close-on-select="true"
            :preserve-search="false"
            :reset-after="true"
            :hide-selected="true"
            :taggable="false"
            :multiple="false"
            :searchable="true"
            :allow-empty="true"
            :show-labels="false"
            :loading="issueIsLoading"
            :placeholder="$t('choose_other_social_issue')"
            :options="socialIssuesOther"
            @select="addIssueInList"
          />
        </div>
      </div>
      <div v-if="hasSocialIssuePicked" class="mb-3">
        <h2>{{ $t("pick_an_action") }}</h2>
        <div class="col-11">
          <vue-multiselect
            v-model="socialActionPicked"
            label="text"
            :options="socialActionsReachables"
            :searchable="true"
            :close-on-select="true"
            :show-labels="true"
            track-by="id"
          />
        </div>
      </div>

      <div v-if="isLoadingSocialActions">
        <i class="fa fa-circle-o-notch fa-spin fa-fw" />
      </div>

      <div v-if="hasSocialActionPicked" id="persons" class="mb-5">
        <h2>{{ $t("persons_involved") }}</h2>

        <ul>
          <li v-for="p in personsReachables" :key="p.id">
            <div class="form-check">
              <input
                type="checkbox"
                :value="p.id"
                v-model="personsPicked"
                class="form-check-input"
                :id="'person_check' + p.id"
              />
              <label class="form-check-label" :for="'person_check' + p.id">
                <person-text :person="p" />
              </label>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- <div v-if="hasSocialActionPicked" id="start_date">
      <p><label>{{ $t('startDate') }}</label> <input type="date" v-model="startDate" /></p>
    </div> -->
    <div class="row">
      <div v-if="hasSocialActionPicked" id="start_date" class="mb-3 row">
        <label class="col-form-label col-sm-4">{{ $t("startDate") }}</label>
        <div class="col-sm-8">
          <input class="form-control" type="date" v-model="startDate" />
        </div>
      </div>

      <!-- <div v-if="hasSocialActionPicked" id="end_date">
      <p><label>{{ $t('endDate') }}</label> <input type="date" v-model="endDate" /></p>
    </div> -->
      <div v-if="hasSocialActionPicked" id="end_date" class="mb-3 row">
        <label class="col-form-label col-sm-4">{{ $t("endDate") }}</label>
        <div class="col-sm-8">
          <input class="form-control" type="date" v-model="endDate" />
        </div>
      </div>
    </div>
    <div id="confirm">
      <div v-if="hasErrors">
        <p>{{ $t("form_has_errors") }}</p>

        <ul>
          <li v-for="e in errors" :key="e.id">
            {{ e }}
          </li>
        </ul>
      </div>

      <div>
        <ul class="record_actions">
          <li class="cancel">
            <button class="btn btn-cancel" @click="goToPrevious">
              {{ $t("action.cancel") }}
            </button>
          </li>
          <li v-if="hasSocialActionPicked">
            <button
              class="btn btn-save"
              v-show="!isPostingWork"
              @click="submit"
            >
              {{ $t("action.save") }}
            </button>
            <button class="btn btn-save" v-show="isPostingWork" disabled>
              {{ $t("action.save") }}
            </button>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import VueMultiselect from "vue-multiselect";
import PersonText from "ChillPersonAssets/vuejs/_components/Entity/PersonText.vue";

const i18n = {
  messages: {
    fr: {
      startDate: "Date de début",
      endDate: "Date de fin",
      form_has_errors: "Le formulaire comporte des erreurs",
      pick_social_issue: "Choisir une problématique sociale",
      pick_other_social_issue: "Veuillez choisir un autre problématique",
      pick_an_action: "Choisir une action d'accompagnement",
      pick_social_issue_linked_with_action:
        "Indiquez la problématique sociale liée à l'action d'accompagnement",
      persons_involved: "Usagers concernés",
      choose_other_social_issue: "Veuillez choisir un autre problématique",
    },
  },
};

export default {
  name: "App",
  components: {
    VueMultiselect,
    PersonText,
  },
  methods: {
    submit() {
      this.$store.dispatch("submit").catch(({ name, violations }) => {
        if (name === "ValidationException" || name === "AccessException") {
          violations.forEach((violation) =>
            this.$toast.open({ message: violation }),
          );
        } else {
          this.$toast.open({ message: "An error occurred" });
        }
      });
    },
    addIssueInList(value) {
      this.$store.commit("addIssueInList", value);
      this.$store.commit("removeIssueInOther", value);
      this.$store.dispatch("pickSocialIssue", value.id);
    },
    goToPrevious() {
      let params = new URLSearchParams(window.location.search);
      if (params.has("returnPath")) {
        window.location.replace(params.get("returnPath"));
      } else {
        return;
      }
    },
  },
  i18n,
  computed: {
    ...mapState([
      "socialIssues",
      "socialIssuesOther",
      "socialActionsReachables",
      "errors",
      "personsReachables",
    ]),
    ...mapGetters([
      "hasSocialIssuePicked",
      "hasSocialActionPicked",
      "isLoadingSocialActions",
      "isPostingWork",
      "hasErrors",
    ]),
    personsPicked: {
      get() {
        let s = this.$store.state.personsPicked.map((p) => p.id);

        return s;
      },
      set(v) {
        this.$store.commit("setPersonsPickedIds", v);
      },
    },
    socialIssuePicked: {
      get() {
        let s = this.$store.state.socialIssuePicked;

        if (s === null) {
          return null;
        }

        return s.id;
      },
      set(value) {
        this.$store.dispatch("pickSocialIssue", value);
      },
    },
    socialActionPicked: {
      get() {
        return this.$store.state.socialActionPicked;
      },
      set(value) {
        this.$store.commit("setSocialAction", value);
      },
    },
    startDate: {
      get() {
        return this.$store.state.startDate;
      },
      set(value) {
        this.$store.commit("setStartDate", value);
      },
    },
    endDate: {
      get() {
        return this.$store.state.endDate;
      },
      set(value) {
        this.$store.commit("setEndDate", value);
      },
    },
    setSocialIssue: {
      set() {
        this.$store.dispatch(
          "setSocialIssue",
          socialIssues[socialIssues.length - 1],
        );
      },
    },
  },
};
</script>

<style lang="scss" scoped>
@import "ChillMainAssets/module/bootstrap/shared";
@import "ChillPersonAssets/chill/scss/mixins";
@import "ChillMainAssets/chill/scss/chill_variables";
span.badge {
  @include badge_social($social-issue-color);
  font-size: 95%;
  margin-bottom: 5px;
  margin-right: 1em;
  margin-left: 1em;
}
</style>

<style lang="scss">
#awc_create_form {
  display: grid;
  grid-template-areas:
    "picking picking"
    "start_date end_date"
    "confirm confirm";
  grid-template-columns: 50% 50%;
  column-gap: 1.5rem;

  #picking {
    grid-area: picking;

    #persons {
      ul {
        padding: 0;

        list-style-type: none;
      }
    }
  }

  #start_date {
    grid-area: start_date;
  }

  #end_date {
    grid-area: end_date;
  }

  #confirm {
    grid-area: confirm;
  }
}
</style>
