import { ref } from 'vue';
import * as utils from './utils';

// Components
import '@mozaic-ds/datatable-vue/style.css';
import { MDataTable, MDataTableColumn } from '@mozaic-ds/datatable-vue';
import MTextInput from '../textinput/MTextInput.vue';
import MStatusBadge from '../statusbadge/MStatusBadge.vue';
import MFlag from '../flag/MFlag.vue';
import MLink from '../link/MLink.vue';
import MActionListbox from '../actionlistbox/MActionListbox.vue';
import MKpiItem from '../kpiitem/MKpiItem.vue';
import MTag from '../tag/MTag.vue';

export default {
  title: 'DataTable/MDataTable Table Cells',
  component: MDataTable,
  args: utils.args,
  parameters: {
    componentName: 'MDataTable',
    docs: {
      canvas: { sourceState: 'none' },
    },
  },
};

export const Default = {
  args: {
    selectable: true,
    expandable: true,
    pageable: true,
  },
  render: (args) => ({
    components: {
      MDataTable,
      MDataTableColumn,
      MStatusBadge,
      MFlag,
      MLink,
      MActionListbox,
      MKpiItem,
      MTag,
      MTextInput,
    },
    setup() {
      const currentPage = ref(1);
      const items = ref([]);
      const itemsAPI = ref([]);
      const itemsPerPage = ref(7);
      const listbox = ref([
        [
          {
            text: 'Edit',
            icon: 'PublishEdit24',
          },
          {
            text: 'Print',
            icon: 'Print24',
            disabled: true,
          },
          {
            text: 'Mark as validated',
            icon: 'NotificationCircleAvailable24',
          },
        ],
        [
          {
            text: 'Open in a new window',
            icon: 'DisplayExternalLink24',
          },
        ],
        [
          {
            text: 'Delete',
            icon: 'PublishTrashbin24',
            danger: true,
          },
        ],
      ]);
      const loading = ref(false);
      const totalItems = ref(0);

      return {
        args,
        currentPage,
        items,
        itemsAPI,
        itemsPerPage,
        listbox,
        loading,
        totalItems,
      };
    },
    template: `
      <MDataTable
        v-bind="args"
        :items="items"
        :loading="loading"
        :totalItems="totalItems"
        maxHeight="500px"
        fixedHeader
        @change="updatePage"
      >
        <!-- No Data -->
        <template v-slot:no-data>
          <p><strong>No data available at this time.</strong></p>
        </template>

        <!-- Siren -->
        <MDataTableColumn label="Siren" value="siren" type="number" />

        <!-- Nom -->
        <MDataTableColumn label="Nom" value="nom" />
        <template v-slot:header.nom="{ header }">
          {{ header.label }}
          <small>codeEpci</small>
        </template>
        <template v-slot:cell.nom="{ item }">
          {{ item.nom }}
          <small>codeEpci: {{ item.codeEpci }}</small>
        </template>

        <!-- Population -->
        <MDataTableColumn label="Population" value="population" />
        <template v-slot:cell.population="{ item }">
          <MKpiItem
            v-if="item.population > 50000"
            :value="item.population"
            status="success"
            trend="increasing"
          />
          <MKpiItem
            v-if="item.population > 20000 && item.population < 50000"
            :value="item.population"
            trend="increasing"
          />
          <MKpiItem
            v-if="item.population > 5000 && item.population < 20000"
            :value="item.population"
            status="neutral"
            trend="stable"
          />
          <MKpiItem
            v-if="item.population > 2000 && item.population < 5000"
            :value="item.population"
            status="warning"
            trend="decreasing"
          />
          <MKpiItem
            v-if="item.population < 2000"
            :value="item.population"
            status="error"
            trend="stable"
          />
        </template>

        <!-- Codes Postaux -->
        <MDataTableColumn label="Codes Postaux" value="codesPostaux" />
        <template v-slot:cell.codesPostaux="{ item }">
          <div class="codes-postaux" style="display: flex; gap: 0.25rem">
            <MTag
              v-for="tag in item.codesPostaux"
              :key="tag"
              :id="tag"
              :label="tag"
            />
          </div>
        </template>

        <!-- Code INSEE -->
        <MDataTableColumn label="Code INSEE" value="code" />
        <template v-slot:cell.code="{ item }">
          <MLink
            size="s"
            href="https://www.insee.fr/fr/metadonnees/cog/commune/COMitem.code-item.nom"
          >
            {{ item.code }}
          </MLink>
        </template>

        <!-- Code INSEE -->
        <MDataTableColumn label="Code EPCI" value="codeEpci" />
        <template v-slot:cell.codeEpci="{ item }">
          <MFlag :label="item.codeEpci" theme="bordered" />
        </template>

        <!-- Code Département -->
        <MDataTableColumn
          label="Code Département"
          value="codeDepartement"
          type="number"
        />

        <!-- Input -->
        <MDataTableColumn label="Note" value="note" type="input" />
        <template v-slot:cell.note="{ item }">
          <MTextInput size="s" />
        </template>

        <!-- Code Région -->
        <MDataTableColumn label="Code Région" value="codeRegion" />
        <template v-slot:cell.codeRegion="{ item }">
          <MStatusBadge :label="item.codeRegion"/>
        </template>

        <!-- Options -->
        <!-- <MDataTableColumn label="" value="options" type="options" />
        <template v-slot:cell.options="{ item }">
          <MActionListbox :items="listbox" position="right" />
        </template> -->
      </MDataTable>
    `,
    async mounted() {
      this.loading = true;
      this.itemsAPI = await this.fetchAPI();
      this.totalItems = this.itemsAPI.length;
      this.items = this.paginateItems(this.itemsPerPage, this.currentPage);
      this.loading = false;
    },
    methods: {
      async fetchAPI() {
        const apiUrl = 'https://geo.api.gouv.fr/departements/59/communes';
        try {
          // Try
          const getData = await fetch(apiUrl, { method: 'GET' });
          const data = await getData.json();

          return data;
        } catch (erreur) {
          // Erreur
          console.log(erreur);

          return [];
        }
      },
      paginateItems(size, page) {
        const start = (page - 1) * size;
        const end = page * size;

        return this.itemsAPI.slice(start, end);
      },
      async updatePage({ size, page }) {
        this.loading = true;

        setTimeout(() => {
          this.items = this.paginateItems(size, page);
          this.loading = false;
        }, 1000);
      },
    },
  }),
};
