<script lang="ts">
  import Translations from "../i18n/Translations"
  import Tr from "../Base/Tr.svelte"
  import PlantNetSpeciesList from "./PlantNetSpeciesList.svelte"
  import { ImmutableStore, Store, UIEventSource } from "../../Logic/UIEventSource"
  import type { PlantNetResult, PlantNetSpeciesMatch } from "../../Logic/Web/PlantNet"
  import PlantNet from "../../Logic/Web/PlantNet"
  import { XCircleIcon } from "@babeard/svelte-heroicons/solid"
  import BackButton from "../Base/BackButton.svelte"
  import NextButton from "../Base/NextButton.svelte"
  import WikipediaPanel from "../Wikipedia/WikipediaPanel.svelte"
  import Plantnet_logo from "../../assets/svg/Plantnet_logo.svelte"
  import ArrowPath from "@babeard/svelte-heroicons/mini/ArrowPath"
  import AccordionSingle from "../Flowbite/AccordionSingle.svelte"

  /**
   * The main entry point for the plantnet wizard
   */
  const t = Translations.t.plantDetection

  /**
   * All the URLs pointing to images of the selected feature.
   * We need to feed them into Plantnet when applicable
   */
  export let imageUrls: Store<string[]>
  export let onConfirm: (wikidataId: string) => void
  let options: UIEventSource<PlantNetSpeciesMatch[]> = new UIEventSource<PlantNetSpeciesMatch[]>(
    undefined
  )

  let error: string | "no_plant_detected" = undefined

  /**
   * The Wikidata-id of the species to apply
   */
  let selectedOption: string

  let running = false
  let expandExplanation = false
  let done = false

  function speciesSelected(species: string) {
    console.log("Selected:", species)
    selectedOption = species
  }

  async function detectSpecies() {
    error = undefined
    running = true
    try {
      const result: PlantNetResult | "no_plant_detected" = await PlantNet.query(
        imageUrls.data.slice(0, 5)
      )
      if (result === "no_plant_detected") {
        error = "no_plant_detected"
        expandExplanation = true
        return
      }
      const filteredResults = result.results.filter((r) => r.score > 0.005).slice(0, 8)
      expandExplanation = filteredResults.length == 0
      options.set(filteredResults)
    } catch (e) {
      console.error("Caught", e)
      error = e
      running = false
    }
  }
</script>

<div class="mb-4 flex flex-col">
  <!-- Error message -->
  {#if error === "no_plant_detected"}
    <Tr cls="alert" t={t.noPlantDetected} />
  {:else if error !== undefined}
    <Tr cls="alert" t={t.error.Subs({ error })} />
  {/if}

  <!-- Button. If 'done==false', the button should be shown, otherwise <PlantnetSpeciesList> will handle the flow -->
  {#if !done && !running && !selectedOption}
    <button class="flex w-full" on:click={detectSpecies}>
      <Plantnet_logo class="mr-2 h-8 w-8 shrink-0 rounded-full bg-white p-1" />
      <span class="flex flex-col items-center">
        <Tr t={t.button} />
        {#if error !== undefined}
          <div class="subtle mt-2 flex">
            <ArrowPath class="h-6 w-6" />
            <Tr t={Translations.t.general.retry} />
          </div>
        {/if}
      </span>
    </button>
  {:else if !selectedOption}
    <PlantNetSpeciesList
      {options}
      numberOfImages={$imageUrls.length}
      on:selected={(species) => speciesSelected(species.detail)}
    >
      <XCircleIcon
        slot="upper-right"
        class="m-4 h-8 w-8 cursor-pointer"
        on:click={() => {
          running = false
        }}
      />
    </PlantNetSpeciesList>
  {:else if !done}
    <div class="border-interactive flex flex-col">
      <div class="m-2">
        <WikipediaPanel wikiIds={new ImmutableStore([selectedOption])} />
      </div>
      <div class="flex flex-col items-stretch">
        <BackButton
          on:click={() => {
            selectedOption = undefined
          }}
        >
          <Tr t={t.back} />
        </BackButton>
        <NextButton
          clss="primary"
          on:click={() => {
            done = true
            onConfirm(selectedOption)
          }}
        >
          <Tr t={t.confirm} />
        </NextButton>
      </div>
    </div>
  {:else}
    <!-- done ! -->
    <Tr t={t.done} cls="thanks w-full" />
    <BackButton
      imageClass="w-6 h-6 shrink-0"
      clss="p-1 m-0"
      on:click={() => {
        done = false
        selectedOption = undefined
      }}
    >
      <Tr t={t.tryAgain} />
    </BackButton>
  {/if}

  <!-- Explanation -->
  <div class="low-interaction my-1">
    <AccordionSingle noBorder expanded={expandExplanation}>
      <div class="subtle flex justify-start p-1 text-sm" slot="header">
        <Tr t={t.howTo.title} />
      </div>
      <div class="border-low-interaction flex flex-col border-b border-l border-r p-4">
        <Tr t={t.takeImages} />
        <Tr t={t.howTo.intro} />
        <ul>
          <li>
            <Tr t={t.howTo.li0} />
          </li>
          <li>
            <Tr t={t.howTo.li1} />
          </li>
          <li>
            <Tr t={t.howTo.li2} />
          </li>
          <li>
            <Tr t={t.howTo.li3} />
          </li>
          <li>
            <Tr t={t.howTo.li4} />
          </li>
        </ul>
        <!-- Attribution -->
        <div class="low-interaction mt-4 flex w-fit items-center self-end rounded-xl p-2 px-3">
          <Plantnet_logo class="mr-2 h-8 w-8 rounded-full bg-white p-1" />
          <Tr t={t.poweredByPlantnet} />
        </div>
      </div>
    </AccordionSingle>
  </div>
</div>
