<script lang="ts">
  /**
   * Statistics, based on the tagRendering, for a single layer
   */
  import LayerConfig from "../../Models/ThemeConfig/LayerConfig"
  import Tr from "../Base/Tr.svelte"
  import Loading from "../Base/Loading.svelte"
  import type { Feature } from "geojson"
  import { AccordionItem } from "flowbite-svelte"
  import ThemeViewState from "../../Models/ThemeViewState"
  import DefaultIcon from "../Map/DefaultIcon.svelte"
  import { Store } from "../../Logic/UIEventSource"
  import ChartJs from "../Base/ChartJs.svelte"
  import { ChartJsUtils } from "../Base/ChartJsUtils"
  import { Utils } from "../../Utils"

  export let layer: LayerConfig
  export let state: ThemeViewState
  let bbox = state.mapProperties.bounds
  let elements: Store<Feature[]> = bbox.mapD((bbox) =>
    state.perLayer.get(layer.id).GetFeaturesWithin(bbox)
  )

  let trs = layer.tagRenderings.filter((tr) => tr.question)
  let configs = trs.map(tr => ({ tr, config: ChartJsUtils.createConfigForTagRendering(tr, $elements, {
      hideNotApplicable: true
    }) })).filter(ctr => ctr.config !== undefined)
</script>

<AccordionItem
  paddingDefault="p-2"
  inactiveClass="text-black"
  defaultClass="w-full flex-grow justify-start"
>
  <div slot="header" class="flex items-center gap-x-2">
    <div class="inline-block h-8 w-8">
      <DefaultIcon {layer} />
    </div>
    <Tr t={layer.name} />
    ({$elements.length} elements in view)
  </div>

  {#if $elements === undefined}
    <Loading />
  {:else if $elements.length === 0}
    No features in view
  {:else}
    <div class="flex w-full flex-wrap gap-x-4 gap-y-4">
      {#each configs as ctr}
        <div class="flex flex-col">
          <h3>
            {#if ctr.tr.question}
              <Tr t={ctr.tr.question} />
            {:else} {ctr.tr.id}{/if}
          </h3>

          <div class={ctr.tr.multiAnswer ? "w-96 grow" : "w-60 grow"}>
            <ChartJs config={ctr.config }>
              <div class="flex place-content-center justify-center items-center w-full h-full" slot="empty">
                No data for this entry
              </div>
            </ChartJs>
          </div>
        </div>
      {/each}
    </div>
  {/if}
</AccordionItem>
