<template>
  <BmsBackButton :fallback="{ path: '/' }" />
  <br />
  <BmsButton @click="changeChoice">Change choice</BmsButton>
  <bms-table
    :headers="headers"
    :filters="filters"
    :items="items"
    mode="dense"
    :size="5"
    :canSaveFilters="true"
    :savedFilters="savedFilters"
    help-link="/help-path"
    activity-link="/activity-path"
    v-model:selectedItems="selectedItems"
    selectable
    :select-mode="SelectMode.SINGLE"
    @saveFilter="onSaveFilter"
    @deleteSavedFilter="onDeleteSavedFilter"
    @filterInput="onFilterInput"
    @filterChange="onFilterChange"
  >
    <template #choice2="{ row }">
      <BmsTooltip tooltipText="tooltip">
        {{ row.choice2 }}
      </BmsTooltip>
    </template>
    <template #deepValue="{ row }">
      {{ row.deepValue.deepAttr }}
    </template>
    <template #tooltip>
      <BmsTooltip tooltip-text="Looooooooooooooooooooooooong tooltip">
        tooltip
      </BmsTooltip>
    </template>
    <template #action="{ isChildElement }">
      <template v-if="isChildElement">
        <BmsChip>Hérité</BmsChip>
      </template>
      <template v-else>
        <BmsIconButton @click="success('Sauvegarde')"> <Save /> </BmsIconButton>
        <BmsIconButton :mode="StatusType.Danger" @click="error('Suppression')">
          <Trash />
        </BmsIconButton>
      </template>
    </template>
  </bms-table>
  <BmsButton @click="goBack">Go Back</BmsButton>
  <div>selectedItems Size = {{ selectedItems.length }}</div>
  <div>
    selectedItems :
    {{ selectedItems }}
  </div>
</template>

<script lang="ts" setup>
import {
  BmsBackButton,
  BmsButton,
  SelectMode,
  useNotifications,
} from '@/index';
import {
  ColumnType,
  Filter,
  InputType,
  SavedFilter,
  SortValue,
  StatusType,
} from '@/models';
import { Ref, ref } from 'vue';
import { useRouterHistory } from '@/plugins/router-history/router-history.composable';
import BmsTooltip from '@/components/feedback/BmsTooltip.vue';
import BmsIconButton from '@/components/button/BmsIconButton.vue';
import { Save, Trash } from 'lucide-vue-next';
import BmsChip from '@/components/form/BmsChip.vue';
import BmsTable from '@/components/table/BmsTable.vue';

const { goBack } = useRouterHistory();
const { error, success } = useNotifications();

const headers = [
  {
    label: 'Colonne 1',
    key: 'column1',
    sortable: true,
    helperText: 'Exemple de tooltip sur l’en-tête de colonne (UiBmsTable).',
  },
  { label: 'actions', key: 'action', action: true },
  { label: 'Colonne 2', key: 'column2' },
  { label: 'Date', key: 'date', columnType: ColumnType.Date },
  { label: 'DateUpdate', key: 'dateUpdate', columnType: ColumnType.Date },
  { label: 'DateDelete', key: 'dateDelete', columnType: ColumnType.Date },
  { label: 'choice1', key: 'choice1' },
  { label: 'choice2', key: 'choice2' },
  {
    label: 'DeepValue',
    key: 'deepValue',
    sortable: true,
    sortFunction: (a: any, b: any, sort: SortValue) => {
      if (a.deepValue.deepAttr < b.deepValue.deepAttr) {
        return sort === SortValue.asc ? -1 : 1;
      }
      if (a.deepValue.deepAttr > b.deepValue.deepAttr) {
        return sort === SortValue.asc ? 1 : -1;
      }
      return 0;
    },
  },
  { label: 'isOk', key: 'isOk', sortable: true },
  { label: 'number', key: 'number' },
  { label: 'tooltip', key: 'tooltip' },
];

const randomDate = () =>
  new Date(
    new Date('2023-01-01').getTime() +
      Math.random() *
        (new Date('2026-01-01').getTime() - new Date('2023-01-01').getTime()),
  );

const items = Array(100)
  .fill(0)
  .map((_, index) => ({
    column1: "Nom de l'item " + index,
    column2: 'little-slug-' + index,
    date: randomDate(),
    dateUpdate: randomDate(),
    dateDelete: randomDate(),
    choice1: Math.random() < 0.5 ? Math.random() * 3 : 'toto',
    choice2:
      Math.random() < 0.5 ? (Math.random() < 0.5 ? 'huey' : 'dewey') : 'louie',
    deepValue: {
      deepAttr: index % 2 === 0,
    },
    isOk: Math.random() < 0.5,
    number: Math.random(),
    childElement:
      Math.random() < 0.5
        ? {
            column1: 'Element enfant',
            column2: index,
            date: randomDate(),
            dateUpdate: randomDate(),
            dateDelete: randomDate(),
            choice1: 'N/A',
            choice2: 'N/A',
            deepValue: {
              deepAttr: index % 2 === 0,
            },
            isOk: true,
            number: 0,
          }
        : undefined,
  }));

const savedFilters: Ref<SavedFilter[]> = ref<SavedFilter[]>([]);
const selectedItems: Ref<any[]> = ref([]);
const onSaveFilter = (savedFilter: SavedFilter) => {
  savedFilters.value.push(savedFilter);
};

const onDeleteSavedFilter = (savedFilter: SavedFilter) => {
  savedFilters.value = savedFilters.value.filter(
    (filter) => filter.id !== savedFilter.id,
  );
};

const onFilterInput = ({
  filterKey,
  e,
  value,
}: {
  filterKey: string;
  e: InputEvent;
  value: any;
}) => {
  console.log(`Input in filter ${filterKey} with val ${value}`);
};
const onFilterChange = ({
  filterKey,
  value,
}: {
  filterKey: string;
  value: any;
}) => {
  console.log(`Change in filter ${filterKey}  with val`, value);
};

const filters = ref<Filter[]>([
  {
    label: 'inputText Colonne 1',
    key: 'column1',
    type: 'input',
  },
  {
    label: 'autocomplete choice',
    key: 'choice1',
    type: 'autocomplete',
    autocompleteOptions: ['titi', 'toto'],
  },
  {
    label: 'choice',
    key: 'choice2',
    type: 'select',
    selectOptions: [
      { label: 'huey', value: 'huey' },
      { label: 'dewey', value: 'dewey' },
      { label: 'louie', value: 'louie' },
    ],
  },
  {
    label: 'Date update greater than',
    key: 'dateUpdate',
    type: 'inputDate',
    inputType: InputType.DATE,
  },
  {
    label: 'Datetime delete greater than',
    key: 'dateDelete',
    type: 'inputDate',
    inputType: InputType.DATETIME,
  },
  {
    label: 'Date',
    key: 'date',
    type: 'betweenDate',
    inputType: InputType.DATE,
  },
  { label: 'isOk', key: 'isOk', type: 'boolean' },
  {
    label: 'custom bool > 0.5',
    key: 'number',
    type: 'boolean',
    customFilter: (item: any, value: any, target: string) =>
      item[target] > 0.5 === value,
  },
]);
const changeChoice = () => {
  filters.value = filters.value.map((f) =>
    f.key === 'choice2'
      ? {
          ...f,
          selectOptions: [
            { label: 'huey', value: 'huey' },
            { label: 'riri', value: 'riri' },
            { label: 'fifi', value: 'fifi' },
            { label: 'loulou', value: 'loulou' },
          ],
        }
      : f,
  );
};
</script>
