<script setup lang="ts">
// @todo: sample page view
import { storeToRefs } from "pinia";
import {
  ABtn,
  ACol,
  AContainer,
  ActindoDataTable,
  ADivider,
  AForm,
  ARow,
  ASheet,
  ASpacer,
  ATextField,
  AToolbar,
  DetailedView,
  LoaderIcon,
  useEditableTable,
} from "@actindo/core-ui";
import { useSampleStore } from "@/stores/sample";
import { SAMPLE_TABLE, SAMPLE_TABLE_ACTIONS } from "@/constants/tables";
import {
  type ISampleEntity,
  SAMPLE_STATUS,
  sampleEntityApi,
} from "@/services/api/Sample/Entity";
import EntityForm from "./components/EntityForm.vue";
import CellSampleStatus from "./components/CellSampleStatus.vue";

const sampleStore = useSampleStore();
const { sample } = storeToRefs(sampleStore);
const { toggleSample } = sampleStore;

const {
  table,
  isBatchLoading,
  showChangeDialog,
  onAddRow,
  onEditRow,
  onDeleteRows,
  batchApiCalls,
} = useEditableTable({
  addApi: sampleEntityApi.mockedCreate,
  editApi: sampleEntityApi.mockedUpdate,
  deleteApi: sampleEntityApi.mockedRemove,
});

function updateItems(selectedRows: ISampleEntity[], status: SAMPLE_STATUS) {
  const updatedItems = selectedRows.map((item) => [{ ...item, status }]);

  return batchApiCalls(onEditRow, updatedItems, sample.value);
}

function handleAction(eventName: string, selectedRows: ISampleEntity[]) {
  switch (eventName) {
    case SAMPLE_TABLE_ACTIONS.DELETE:
      return batchApiCalls(
        onDeleteRows,
        selectedRows.map(({ id }) => [id]),
        sample.value,
      );

    case SAMPLE_TABLE_ACTIONS.MARK_INIT:
      return updateItems(selectedRows, SAMPLE_STATUS.INIT);
    case SAMPLE_TABLE_ACTIONS.MARK_DONE:
      return updateItems(selectedRows, SAMPLE_STATUS.DONE);
    case SAMPLE_TABLE_ACTIONS.MARK_FAILED:
      return updateItems(selectedRows, SAMPLE_STATUS.FAILED);
  }
}

function addEntity() {
  showChangeDialog.value = true;
}

async function save(newEntity: ISampleEntity) {
  await onAddRow(newEntity);
  showChangeDialog.value = false;
}
</script>

<template>
  <ASheet class="d-flex flex-column h-100" color="background_2">
    <AToolbar color="transparent" :title="$t('SampleView.toolbarTitle')">
      <LoaderIcon v-if="isBatchLoading" />
      {{ sample ? $t("SampleView.iterate") : "" }}
      <ASpacer />
      <ABtn
        class="mr-4"
        color="primary"
        variant="outlined"
        :text="$t('common.rollBackChanges')"
        @click="sample = false"
      />
      <ABtn
        class="mr-4"
        color="primary"
        variant="flat"
        :text="$t('SampleView.toggle')"
        @click="toggleSample"
      />
    </AToolbar>
    <ADivider color="on_bg_64" />
    <div class="flex-grow-1 overflow-hidden">
      <ActindoDataTable
        ref="table"
        v-bind="SAMPLE_TABLE"
        @action="handleAction"
        @create="addEntity"
      >
        <template #cell-status="{ cellValue }">
          <CellSampleStatus :cell-value="cellValue" />
        </template>

        <template #details="{ row, close }: { row: ISampleEntity }">
          <DetailedView>
            <template #toolbar-title>
              <div class="d-flex">
                <span>{{ $t("SampleView.dataDetails") }}</span>
                <CellSampleStatus
                  v-if="row"
                  :cell-value="row.status"
                  class="pr-2 ml-4"
                />
              </div>
            </template>

            <template #toolbar-actions>
              <ABtn
                v-if="row.status !== SAMPLE_STATUS.DONE"
                :text="$t('SampleView.actions.markDone')"
                @click="
                  handleAction(SAMPLE_TABLE_ACTIONS.MARK_DONE, [row]);
                  close();
                "
              />
            </template>

            <AContainer v-if="row" fluid>
              <AForm @submit.prevent>
                <ARow>
                  <ACol cols="12" md="6">
                    <ATextField
                      v-model="row.sample.name"
                      :label="$t('SampleView.name')"
                      readonly
                    />
                  </ACol>
                  <ACol cols="12" md="6">
                    <ATextField
                      v-model="row.key"
                      :label="$t('SampleView.key')"
                      readonly
                    />
                  </ACol>
                  <ACol cols="12" md="6">
                    <ATextField
                      v-model="row.validFrom"
                      :label="$t('SampleView.validFrom')"
                      type="date"
                      readonly
                    />
                  </ACol>
                </ARow>
              </AForm>
            </AContainer>
          </DetailedView>
        </template>

        <template #modals>
          <EntityForm
            v-if="showChangeDialog"
            v-model="showChangeDialog"
            :loading="isBatchLoading"
            @save="save"
          />
        </template>
      </ActindoDataTable>
    </div>
  </ASheet>
</template>
