<template>
  <div>
    <div class="m-md-3">
      <DateInputs
        :startDate="startDate"
        :endDate="endDate"
        :maxDate="maxDate"
        :warningInterval="warningInterval"
        @update:startDate="updateStartDate"
        @update:endDate="updateEndDate"
        @update:maxDate="updateMaxDate"
        @update:warningInterval="updateWarningInterval"
      />

      <TimeSpentInput
        :timeSpent="timeSpent"
        :timeSpentChoices="timeSpentChoices"
        @update:timeSpent="updateTimeSpent"
      />

      <CommentInput :comment="comment" @update:comment="updateComment" />

      <DocumentsList
        v-if="evaluation.documents.length > 0"
        :documents="evaluation.documents"
        :docAnchorId="docAnchorId"
        :evaluation="evaluation"
        :accompanyingPeriodId="store.state.work.accompanyingPeriod.id"
        @inputDocumentTitle="onInputDocumentTitle"
        @removeDocument="removeDocument"
        @duplicateDocument="duplicateDocument"
        @duplicate-document-to-evaluation="duplicateDocumentToEvaluation"
        @move-document-to-evaluation="moveDocumentToEvaluation"
        @statusDocumentChanged="onStatusDocumentChanged"
        @goToGenerateNotification="goToGenerateDocumentNotification"
      />

      <DocumentActions
        :evaluation="evaluation"
        :templates="getTemplatesAvailables"
        @addDocument="addDocument"
      />
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useStore } from "vuex";
import DateInputs from "./DateInputs.vue";
import TimeSpentInput from "./TimeSpentInput.vue";
import CommentInput from "./CommentInput.vue";
import DocumentsList from "./DocumentsList.vue";
import DocumentActions from "./DocumentActions.vue";
import {
  trans,
  EVALUATION_DOCUMENT_DUPLICATE_SUCCESS,
  EVALUATION_DOCUMENT_MOVE_SUCCESS,
} from "translator";
import { useToast } from "vue-toast-notification";
import { buildLinkCreate as buildLinkCreateNotification } from "ChillMainAssets/lib/entity-notification/api";

const props = defineProps(["evaluation", "docAnchorId"]);
const store = useStore();

const $toast = useToast();

const timeSpentValues = [
  60,
  120,
  180,
  240,
  300,
  600,
  900,
  1200,
  1500,
  1800,
  2700,
  3600,
  4500,
  5400,
  6300,
  7200,
  9000,
  10800,
  12600,
  14400,
  16200,
  18000,
  19800,
  21600,
  23400,
  25200,
  27000,
  28800,
  43200,
  57600,
  72000,
  86400,
  100800,
  115200,
  129600,
  144000, // goes from 1 minute to 40 hours
];

const formatDuration = (seconds, locale) => {
  const currentLocale = locale || navigator.language || "fr";

  const totalHours = Math.floor(seconds / 3600);
  const remainingMinutes = Math.floor((seconds % 3600) / 60);

  if (totalHours >= 8) {
    const days = Math.floor(totalHours / 8);
    const remainingHours = totalHours % 8;

    const parts = [];

    if (days > 0) {
      parts.push(
        new Intl.NumberFormat(currentLocale, {
          style: "unit",
          unit: "day",
          unitDisplay: "long",
        }).format(days),
      );
    }

    if (remainingHours > 0) {
      parts.push(
        new Intl.NumberFormat(currentLocale, {
          style: "unit",
          unit: "hour",
          unitDisplay: "long",
        }).format(remainingHours),
      );
    }

    return parts.join(" ");
  }

  // For less than 8 hours, use hour and minute format
  const parts = [];

  if (totalHours > 0) {
    parts.push(
      new Intl.NumberFormat(currentLocale, {
        style: "unit",
        unit: "hour",
        unitDisplay: "long",
      }).format(totalHours),
    );
  }

  if (remainingMinutes > 0) {
    parts.push(
      new Intl.NumberFormat(currentLocale, {
        style: "unit",
        unit: "minute",
        unitDisplay: "long",
      }).format(remainingMinutes),
    );
  }

  console.log(parts);
  console.log(parts.join(" "));

  return parts.join(" ");
};

const timeSpentChoices = computed(() => {
  const locale = "fr";
  return timeSpentValues.map((value) => ({
    text: formatDuration(value, locale),
    value: parseInt(value),
  }));
});

const startDate = computed({
  get() {
    return props.evaluation.startDate;
  },
  set(v) {
    store.commit("setEvaluationStartDate", {
      key: props.evaluation.key,
      date: v,
    });
  },
});

const endDate = computed({
  get() {
    return props.evaluation.endDate;
  },
  set(v) {
    store.commit("setEvaluationEndDate", {
      key: props.evaluation.key,
      date: v,
    });
  },
});

const maxDate = computed({
  get() {
    return props.evaluation.maxDate;
  },
  set(v) {
    store.commit("setEvaluationMaxDate", {
      key: props.evaluation.key,
      date: v,
    });
  },
});

const warningInterval = computed({
  get() {
    return props.evaluation.warningInterval;
  },
  set(v) {
    store.commit("setEvaluationWarningInterval", {
      key: props.evaluation.key,
      days: v,
    });
  },
});

const timeSpent = computed({
  get() {
    return props.evaluation.timeSpent;
  },
  set(v) {
    store.commit("setEvaluationTimeSpent", {
      key: props.evaluation.key,
      time: v,
    });
  },
});

const comment = computed({
  get() {
    return props.evaluation.comment;
  },
  set(v) {
    store.commit("setEvaluationComment", {
      key: props.evaluation.key,
      comment: v,
    });
  },
});

const getTemplatesAvailables = computed(() => {
  return store.getters.getTemplatesAvailablesForEvaluation(
    props.evaluation.evaluation,
  );
});

// const getAccompanyingPeriod = computed(() => store.work)
function updateStartDate(value) {
  startDate.value = value;
}

function updateEndDate(value) {
  endDate.value = value;
}

function updateMaxDate(value) {
  maxDate.value = value;
}

function updateWarningInterval(value) {
  warningInterval.value = value;
}

function updateTimeSpent(value) {
  timeSpent.value = parseInt(value);
}

function updateComment(value) {
  comment.value = value;
}

function onInputDocumentTitle(event) {
  const id = Number(event.target.id);
  const key = Number(event.target.dataset.key) + 1;
  const title = event.target.value;
  store.commit("updateDocumentTitle", {
    id: id,
    key: key,
    evaluationKey: props.evaluation.key,
    title: title,
  });
}

function addDocument({ stored_object, stored_object_version, file_name }) {
  let document = {
    type: "accompanying_period_work_evaluation_document",
    storedObject: stored_object,
    title: file_name,
  };
  store.commit("addDocument", {
    key: props.evaluation.key,
    document,
    stored_object_version,
  });
}

function removeDocument(document) {
  if (
    window.confirm(
      'Êtes-vous sûr·e de vouloir supprimer le document qui a pour titre "' +
        document.title +
        '" ?',
    )
  ) {
    store.commit("removeDocument", {
      key: props.evaluation.key,
      document: document,
    });
  }
}

function duplicateDocument(document) {
  store.dispatch("duplicateDocument", {
    evaluation_key: props.evaluation.key,
    document: document,
  });
}

function duplicateDocumentToEvaluation({ evaluation, document }) {
  store
    .dispatch("duplicateDocumentToEvaluation", {
      evaluation: evaluation,
      document: document,
    })
    .then(() => {
      $toast.open({
        message: trans(EVALUATION_DOCUMENT_DUPLICATE_SUCCESS),
      });
    })
    .catch((e) => {
      console.log(e);
    });
}

function moveDocumentToEvaluation({ evaluationDest, document }) {
  console.log("dest eval in formEvaluation", evaluationDest);
  store
    .dispatch("moveDocumentToEvaluation", {
      evaluationInitial: props.evaluation,
      evaluationDest: evaluationDest,
      document: document,
    })
    .then(() => {
      $toast.open({
        message: trans(EVALUATION_DOCUMENT_MOVE_SUCCESS),
      });
    })
    .catch((e) => {
      console.log(e);
    });
}

function onStatusDocumentChanged(newStatus) {
  store.commit("statusDocumentChanged", {
    key: props.evaluation.key,
    newStatus: newStatus,
  });
}

function goToGenerateDocumentNotification(document, tos) {
  const callback = (data) => {
    let evaluation = data.accompanyingPeriodWorkEvaluations.find(
      (e) => e.key === props.evaluation.key,
    );
    let updatedDocument = evaluation.documents.find(
      (d) => d.key === document.key,
    );
    window.location.assign(
      buildLinkCreateNotification(
        "Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluationDocument",
        updatedDocument.id,
        tos === true ? store.state.work.accompanyingPeriod.user.id : null,
        window.location.pathname +
          window.location.search +
          window.location.hash,
      ),
    );
  };
  store.dispatch("submit", callback).catch((e) => {
    console.log(e);
    throw e;
  });
}
</script>

<style lang="scss" scoped>
input.document-title {
  font-weight: bold;
  font-size: 1rem;
}

.bg-blink {
  color: #050000;
  padding: 10px;
  display: inline-block;
  border-radius: 5px;
  animation: blinkingBackground 2.2s infinite;
  animation-iteration-count: 2;
}

@keyframes blinkingBackground {
  0% {
    background-color: #ed776d;
  }
  50% {
    background-color: #ffffff;
  }
  100% {
    background-color: #ed776d;
  }
}
</style>
