<script setup>
import dayjs from "dayjs";

const props = defineProps({
  queryStringData: {
    type: String
  },
  item: {
    type: Object,
    required: true
  },
  topLevelType: {
    type: String,
    required: true
  },
  platform: {
    type: String,
    required: true
  }
})

const dataStore = useDataStore()
const tempStore = useTempStore()

const router = useRouter()

const dataType = dataStore.dataTypes[props.topLevelType]

// const selectedColumns = ref(tempStore.columns[props.topLevelType] ? tempStore.columns[props.topLevelType] : dataType.templateColumns.filter(i => !i.disabledInTable))
// const columns = computed(() => dataType.templateColumns.filter((column) => !column.disabledInTable && selectedColumns.value.find(i => i.key === column.key)))

const getDatapointValue = (datapoint) => {
  if (datapoint.key.includes(".")) {
    const [parentKey, childKey] = datapoint.key.split(".")
    return props.item?.[parentKey]?.[childKey]
  }
  return props.item?.[datapoint.key]
}

const renderDatapointValue = (datapoint) => {
  const value = getDatapointValue(datapoint)
  if (value === null || value === undefined || value === "") return "-"

  if (datapoint.displayFunction) {
    return datapoint.displayFunction(value, props.item)
  }

  if (datapoint.inputType === "date") {
    return dayjs(value).isValid() ? dayjs(value).format("DD.MM.YYYY") : String(value)
  }

  if (datapoint.inputType === "datetime") {
    return dayjs(value).isValid() ? dayjs(value).format("DD.MM.YYYY HH:mm") : String(value)
  }

  if (datapoint.inputType === "bool" || typeof value === "boolean") {
    return value ? "Ja" : "Nein"
  }

  return `${value}${datapoint.unit ? datapoint.unit : ""}`
}

</script>

<template>
  <UCard class="mt-5 scroll" :style="props.platform !== 'mobile' ? 'height: 80vh' : ''">
    <template #header v-if="props.platform === 'mobile'">
      <span>Informationen</span>
    </template>
    <UAlert
        v-if="props.item.archived"
        color="error"
        variant="outline"
        :title="`${dataType.labelSingle} archiviert`"
        icon="i-heroicons-archive-box"
        class="mb-5"
    />
    <div class="text-wrap">
      <table class="w-full">
        <tbody>
        <tr
            v-for="datapoint in dataType.templateColumns"
        >
          <td>{{datapoint.label}}:</td>
          <td>
            <component v-if="datapoint.component" :is="datapoint.component" :row="props.item" :in-show="true"></component>
            <div v-else>
              <span>{{ renderDatapointValue(datapoint) }}</span>
            </div>
          </td>
        </tr>
        </tbody>

      </table>
    </div>

  </UCard>

</template>

<style scoped>
td {
  border-bottom: 1px solid lightgrey;
  vertical-align: top;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}
</style>
