<template>
  <div class="card">
    <div class="card-header">
      <h5 class="card-title mb-0">
        {{ trans(CHILL_TICKET_LIST_FILTER_TITLE) }}
      </h5>
    </div>
    <div class="card-body">
      <form @submit.prevent="applyFilters">
        <div class="row">
          <!-- Filtre par usagé -->
          <div class="col-md-6 mb-3">
            <label class="form-label" for="personSelector">{{
              trans(CHILL_TICKET_LIST_FILTER_PERSONS_CONCERNED)
            }}</label>
            <persons-selector
              v-model="filters.byPerson"
              :suggested="availablePersons"
              :multiple="true"
              :types="['person']"
              id="personSelector"
              :label="trans(CHILL_TICKET_LIST_FILTER_BY_PERSON)"
              :disabled="ticketFilterParams?.byPerson ? true : false"
            />
          </div>

          <div class="col-md-6 mb-3">
            <label class="form-label" for="userSelector">{{
              trans(CHILL_TICKET_LIST_FILTER_CREATORS)
            }}</label>
            <persons-selector
              v-model="filters.byCreator"
              :suggested="[]"
              :multiple="true"
              :types="['user']"
              id="userSelector"
              :label="trans(CHILL_TICKET_LIST_FILTER_BY_CREATOR)"
              :disabled="ticketFilterParams?.byCreator ? true : false"
            />
          </div>

          <div class="col-md-6 mb-3">
            <label class="form-label" for="addresseeSelector">{{
              trans(CHILL_TICKET_LIST_FILTER_ADDRESSEES)
            }}</label>
            <addressee-selector-component
              v-model="filters.byAddressee"
              :suggested="[]"
              :label="trans(CHILL_TICKET_LIST_FILTER_BY_ADDRESSEES)"
              id="addresseeSelector"
              :disabled="ticketFilterParams?.byAddressee ? true : false"
            />
          </div>
          <div class="col-md-6 mb-3">
            <!-- Filtre par motifs -->
            <div class="row">
              <label class="form-label" for="motiveSelector">{{
                trans(CHILL_TICKET_LIST_FILTER_BY_MOTIVES)
              }}</label>
              <motive-selector
                v-model="selectedMotive"
                :motives="availableMotives"
                :allow-parent-selection="true"
                @remove="(motive) => removeMotive(motive)"
                id="motiveSelector"
                :disabled="ticketFilterParams?.byMotives ? true : false"
              />

              <div class="mb-2" style="min-height: 2em">
                <div class="d-flex flex-wrap gap-2">
                  <span
                    v-for="motive in filters.byMotives"
                    :key="motive.id"
                    class="badge bg-secondary d-flex align-items-center gap-1"
                  >
                    {{ getMotiveDisplayName(motive) }}
                    <button
                      type="button"
                      class="btn-close btn-close-white"
                      :aria-label="trans(CHILL_TICKET_LIST_FILTER_REMOVE)"
                      @click="removeMotive(motive)"
                      :disabled="ticketFilterParams?.byMotives ? true : false"
                    ></button>
                  </span>
                </div>
              </div>
            </div>
            <!-- Filtre par état actuel -->
            <div class="d-flex gap-3">
              <div>
                <label class="form-label pe-2" for="currentState">
                  {{ trans(CHILL_TICKET_LIST_FILTER_CURRENT_STATE) }}
                </label>
                <toggle-component
                  v-model="isClosedToggled"
                  :on-label="trans(CHILL_TICKET_LIST_FILTER_CLOSED)"
                  :off-label="trans(CHILL_TICKET_LIST_FILTER_OPEN)"
                  :classColor="{
                    on: 'bg-chill-red',
                    off: 'bg-chill-green',
                  }"
                  @update:model-value="handleStateToggle"
                  id="currentState"
                  :disabled="ticketFilterParams?.byCurrentState ? true : false"
                />
              </div>

              <!-- Filtre par état d'urgence -->
              <div>
                <label class="form-label pe-2" for="emergency">
                  {{ trans(CHILL_TICKET_LIST_FILTER_EMERGENCY) }}
                </label>
                <toggle-component
                  v-model="isEmergencyToggled"
                  :on-label="trans(CHILL_TICKET_LIST_FILTER_EMERGENCY)"
                  :off-label="trans(CHILL_TICKET_LIST_FILTER_EMERGENCY)"
                  :classColor="{
                    on: 'bg-warning',
                    off: 'bg-secondary',
                  }"
                  @update:model-value="handleEmergencyToggle"
                  id="emergency"
                  :disabled="
                    ticketFilterParams?.byCurrentStateEmergency ? true : false
                  "
                />
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <!-- Filtre pour temps de réponse dépassé -->
          <div class="col-md-6 mb-3">
            <div class="form-check">
              <input
                v-model="filters.byAddresseeToMe"
                class="form-check-input"
                type="checkbox"
                id="stateMe"
                :disabled="ticketFilterParams?.byAddresseeToMe ? true : false"
              />
              <label class="form-check-label" for="stateMe">
                {{ trans(CHILL_TICKET_LIST_FILTER_TO_ME) }}
              </label>
            </div>

            <div class="form-check">
              <input
                class="form-check-input"
                type="checkbox"
                v-model="filters.byResponseTimeExceeded"
                @change="handleResponseTimeExceededChange"
                id="responseTimeExceeded"
                :disabled="
                  ticketFilterParams?.byResponseTimeExceeded ? true : false
                "
              />
              <label class="form-check-label" for="responseTimeExceeded">
                {{ trans(CHILL_TICKET_LIST_FILTER_RESPONSE_TIME_EXCEEDED) }}
              </label>
            </div>
            <small class="form-text text-muted">
              <i class="bi bi-exclamation-triangle"></i>
              {{ trans(CHILL_TICKET_LIST_FILTER_RESPONSE_TIME_WARNING) }}
            </small>
          </div>
          <!-- Filtre par numéro de ticket -->
          <div class="col-md-6 mb-3">
            <label class="form-label pe-2" for="ticketSelector">
              {{ trans(CHILL_TICKET_LIST_FILTER_BY_TICKET_ID) }}
            </label>
            <ticket-selector
              v-model="filters.byTicketId"
              id="ticketSelector"
              :disabled="ticketFilterParams?.byTicketId ? true : false"
            />
          </div>
        </div>

        <!-- Filtre par date de création -->
        <div class="row">
          <div class="col-md-6 mb-3">
            <date-and-time-selector-component
              :label="trans(CHILL_TICKET_LIST_FILTER_CREATED_AFTER)"
              date-id="byCreatedAfter"
              default-value-time="00:00"
              :model-value-date="filters.byCreatedAfter"
              :model-value-time="byCreatedAfterTime"
              :disabled="
                filters.byResponseTimeExceeded ||
                ticketFilterParams?.byCreatedAfter
                  ? true
                  : false
              "
              @update:modelValueDate="filters.byCreatedAfter = $event"
              @update:modelValueTime="byCreatedAfterTime = $event"
            />
          </div>

          <div class="col-md-6 mb-3">
            <date-and-time-selector-component
              :label="trans(CHILL_TICKET_LIST_FILTER_CREATED_BEFORE)"
              date-id="byCreatedBefore"
              default-value-time="23:59"
              :model-value-date="filters.byCreatedBefore"
              :model-value-time="byCreatedBeforeTime"
              :disabled="
                filters.byResponseTimeExceeded ||
                ticketFilterParams?.byCreatedBefore
                  ? true
                  : false
              "
              @update:modelValueDate="filters.byCreatedBefore = $event"
              @update:modelValueTime="byCreatedBeforeTime = $event"
            />
          </div>
        </div>

        <div class="row">
          <div class="col-12 d-flex align-items-end justify-content-end gap-2">
            <button
              type="button"
              @click="resetFilters"
              class="btn btn-outline-secondary"
            >
              <i class="bi bi-arrow-clockwise"></i>
              {{ trans(CHILL_TICKET_LIST_FILTER_RESET) }}
            </button>
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-funnel"></i>
              {{ trans(CHILL_TICKET_LIST_FILTER_APPLY) }}
            </button>
          </div>
        </div>
        <div class="row">
          <span
            class="col-12 d-flex align-items-end justify-content-end form-text text-muted mt-1"
          >
            {{ resultCount !== 0 ? `${resultCount} ` : "" }}
            {{ trans(CHILL_TICKET_LIST_FILTER_RESULT, { count: resultCount }) }}
          </span>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import type { Person } from "ChillPersonAssets/types";
import {
  type Motive,
  type TicketFilterParams,
  type TicketFilters,
} from "../../../types";

// Translation
import {
  trans,
  CHILL_TICKET_LIST_FILTER_TITLE,
  CHILL_TICKET_LIST_FILTER_PERSONS_CONCERNED,
  CHILL_TICKET_LIST_FILTER_BY_PERSON,
  CHILL_TICKET_LIST_FILTER_CREATORS,
  CHILL_TICKET_LIST_FILTER_BY_CREATOR,
  CHILL_TICKET_LIST_FILTER_ADDRESSEES,
  CHILL_TICKET_LIST_FILTER_BY_ADDRESSEES,
  CHILL_TICKET_LIST_FILTER_BY_MOTIVES,
  CHILL_TICKET_LIST_FILTER_BY_TICKET_ID,
  CHILL_TICKET_LIST_FILTER_REMOVE,
  CHILL_TICKET_LIST_FILTER_OPEN,
  CHILL_TICKET_LIST_FILTER_CLOSED,
  CHILL_TICKET_LIST_FILTER_TO_ME,
  CHILL_TICKET_LIST_FILTER_EMERGENCY,
  CHILL_TICKET_LIST_FILTER_CREATED_AFTER,
  CHILL_TICKET_LIST_FILTER_CREATED_BEFORE,
  CHILL_TICKET_LIST_FILTER_RESPONSE_TIME_EXCEEDED,
  CHILL_TICKET_LIST_FILTER_RESPONSE_TIME_WARNING,
  CHILL_TICKET_LIST_FILTER_RESET,
  CHILL_TICKET_LIST_FILTER_APPLY,
  CHILL_TICKET_LIST_FILTER_RESULT,
  CHILL_TICKET_LIST_FILTER_CURRENT_STATE,
} from "translator";

// Components
import PersonsSelector from "../../TicketApp/components/Person/PersonsSelectorComponent.vue";
import MotiveSelector from "../../TicketApp/components/Motive/MotiveSelectorComponent.vue";
import AddresseeSelectorComponent from "../../TicketApp/components/Addressee/AddresseeSelectorComponent.vue";
import ToggleComponent from "./ToggleComponent.vue";
import TicketSelector from "../../TicketApp/components/Ticket/TicketSelector.vue";
import DateAndTimeSelectorComponent from "./DateAndTimeSelectorComponent.vue";

// Props
const props = defineProps<{
  availablePersons?: Person[];
  availableMotives: Motive[];
  resultCount: number;
  ticketFilterParams: TicketFilters | null;
}>();

// Emits
const emit = defineEmits<{
  "filters-changed": [filters: TicketFilterParams];
}>();

const filtersInitValues: TicketFilters = {
  byPerson: props.ticketFilterParams?.byPerson ?? [],
  byCreator: props.ticketFilterParams?.byCreator ?? [],
  byAddressee: props.ticketFilterParams?.byAddressee ?? [],
  byCurrentState: props.ticketFilterParams?.byCurrentState ?? ["open"],
  byCurrentStateEmergency:
    props.ticketFilterParams?.byCurrentStateEmergency ?? [],
  byMotives: props.ticketFilterParams?.byMotives ?? [],
  byCreatedAfter: props.ticketFilterParams?.byCreatedAfter ?? "",
  byCreatedBefore: props.ticketFilterParams?.byCreatedBefore ?? "",
  byResponseTimeExceeded:
    props.ticketFilterParams?.byResponseTimeExceeded ?? false,
  byAddresseeToMe: props.ticketFilterParams?.byAddresseeToMe ?? false,
  byTicketId: props.ticketFilterParams?.byTicketId ?? null,
};

// État réactif
const filters = ref<TicketFilters>({ ...filtersInitValues });

const byCreatedAfterTime = ref("00:00");
const byCreatedBeforeTime = ref("23:59");
const isClosedToggled = ref(false);
const isEmergencyToggled = ref(false);

const availablePersons = ref<Person[]>(props.availablePersons || []);
const selectedMotive = ref<Motive | null>();

watch(selectedMotive, (newMotive) => {
  if (
    newMotive &&
    !filters.value.byMotives.find((m) => m.id === newMotive.id)
  ) {
    filters.value.byMotives = [...filters.value.byMotives, newMotive];
  }
});

const selectedPersonIds = computed(() =>
  filters.value.byPerson.map((person) => person.id),
);

const selectedUserAddresseesIds = computed(() =>
  filters.value.byAddressee
    .filter((addressee) => addressee.type === "user")
    .map((addressee) => addressee.id),
);

const selectedGroupAddresseesIds = computed(() =>
  filters.value.byAddressee
    .filter((addressee) => addressee.type === "user_group")
    .map((addressee) => addressee.id),
);

const selectedCreatorIds = computed(() =>
  filters.value.byCreator.map((creator) => creator.id),
);

const selectedMotiveIds = computed(() =>
  filters.value.byMotives.map((motive) => motive.id),
);

const handleStateToggle = (value: boolean) => {
  if (value) {
    filters.value.byCurrentState = ["closed"];
  } else {
    filters.value.byCurrentState = ["open"];
  }
};

const handleEmergencyToggle = (value: boolean) => {
  if (value) {
    filters.value.byCurrentStateEmergency = ["yes"];
  } else {
    filters.value.byCurrentStateEmergency = [];
  }
};

const formatDateToISO = (dateString: string, timeString: string): string => {
  const [hours, minutes] = timeString.split(":").map(Number);
  const date = new Date(dateString);
  date.setHours(hours, minutes, 0, 0);
  return date.toISOString();
};

const getMotiveDisplayName = (motive: Motive): string => {
  if (typeof motive.label === "string") {
    return motive.label;
  }
  if (typeof motive.label === "object" && motive.label !== null) {
    const labels = Object.values(motive.label);
    return labels[0] || `Motive ${motive.id}`;
  }
  return `Motive ${motive.id}`;
};

const removeMotive = (motiveToRemove: Motive): void => {
  filters.value.byMotives = filters.value.byMotives.filter(
    (m) => m.id !== motiveToRemove.id,
  );
  if (selectedMotive.value && motiveToRemove.id == selectedMotive.value.id) {
    selectedMotive.value = null;
  }
};

const applyFilters = (): void => {
  const apiFilters: TicketFilterParams = {};

  if (selectedPersonIds.value.length > 0) {
    apiFilters.byPerson = selectedPersonIds.value;
  }
  if (selectedCreatorIds.value.length > 0) {
    apiFilters.byCreator = selectedCreatorIds.value;
  }
  if (selectedUserAddresseesIds.value.length > 0) {
    apiFilters.byAddressee = selectedUserAddresseesIds.value;
  }
  if (selectedGroupAddresseesIds.value.length > 0) {
    apiFilters.byAddresseeGroup = selectedGroupAddresseesIds.value;
  }
  if (filters.value.byCurrentState.length > 0) {
    apiFilters.byCurrentState = filters.value.byCurrentState;
  }

  if (filters.value.byCurrentStateEmergency.length > 0) {
    apiFilters.byCurrentStateEmergency = filters.value.byCurrentStateEmergency;
  }

  if (selectedMotiveIds.value.length > 0) {
    apiFilters.byMotives = selectedMotiveIds.value;
  }

  if (filters.value.byCreatedAfter) {
    apiFilters.byCreatedAfter = formatDateToISO(
      filters.value.byCreatedAfter,
      byCreatedAfterTime.value,
    );
  }

  if (filters.value.byCreatedBefore) {
    apiFilters.byCreatedBefore = formatDateToISO(
      filters.value.byCreatedBefore,
      byCreatedBeforeTime.value,
    );
  }

  if (filters.value.byResponseTimeExceeded) {
    apiFilters.byResponseTimeExceeded = "true";
  }
  if (filters.value.byAddresseeToMe) {
    apiFilters.byAddresseeToMe = true;
  }
  if (filters.value.byAddresseeToMe) {
    apiFilters.byAddresseeToMe = true;
  }
  if (filters.value.byTicketId) {
    apiFilters.byTicketId = filters.value.byTicketId;
  }
  emit("filters-changed", apiFilters);
};

const resetFilters = (): void => {
  filters.value = { ...filtersInitValues };
  selectedMotive.value = null;
  isClosedToggled.value = false;
  isEmergencyToggled.value = false;
  byCreatedAfterTime.value = "00:00";
  byCreatedBeforeTime.value = "23:59";
  applyFilters();
};

const handleResponseTimeExceededChange = (): void => {
  if (filters.value.byResponseTimeExceeded) {
    filters.value.byCreatedBefore = "";
    filters.value.byCreatedAfter = "";
    isClosedToggled.value = false;
  }
};
</script>

<style scoped>
.form-text {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.badge .btn-close {
  font-size: 0.65em;
}

.form-label {
  font-weight: bold;
}
.form-check-label {
  font-weight: bold;
}
</style>
