import { apiClient, ApiClient } from '@/api/api-client'
import { AsyncData } from '@/api/client-rest'
import { defineComponent, onMounted, ref } from 'vue'
import { LoadingElement } from './_ui/functional-loader'
import { ResultatMiseEnConcurrence } from './titre/resultat-mise-en-concurrence'
import { DemarcheId, demarcheIdValidator, GetResultatMiseEnConcurrence } from 'camino-common/src/demarche'
import { computed } from 'vue'
import { isNotNullNorUndefined } from 'camino-common/src/typescript-tools'
import { useRoute, useRouter } from 'vue-router'
import { useState } from '@/utils/vue-tsx-utils'
import { inject } from 'vue'
import { entreprisesKey, userKey } from '@/moi'
import { MachineInfo } from 'camino-common/src/machines'

export const DemarcheResultatMiseEnConcurrence = defineComponent(() => {
  const currentRoute = useRoute<'resultatMiseEnConcurrence'>()
  const demarcheId = computed<null | DemarcheId>(() => {
    const { data } = demarcheIdValidator.safeParse(currentRoute.params.demarcheId)

    return data ?? null
  })

  return () => <>{isNotNullNorUndefined(demarcheId.value) ? <PureDemarcheResultatMiseEnConcurrence demarcheId={demarcheId.value} apiClient={apiClient} /> : null}</>
})

type Props = {
  demarcheId: DemarcheId
  apiClient: Pick<ApiClient, 'getResultatMiseEnConcurrence' | 'getEtapesTypesEtapesStatuts' | 'etapeCreer' | 'uploadTempDocument' | 'getEtapeDocumentsByEtapeId'>
}

const PureDemarcheResultatMiseEnConcurrence = defineComponent<Props>(props => {
  const [data, setData] = useState<AsyncData<{ pivot: GetResultatMiseEnConcurrence; machineInfo: MachineInfo }>>({ status: 'LOADING' })

  const entreprises = inject(entreprisesKey, ref([]))
  const user = inject(userKey)
  const router = useRouter()

  onMounted(async () => {
    const result = await props.apiClient.getResultatMiseEnConcurrence(props.demarcheId)
    if ('message' in result) {
      setData({
        status: 'NEW_ERROR',
        error: result,
      })
    } else {
      const machineInfo = MachineInfo.withMachineId(result.titreTypeId, result.demarcheTypeId, result.demarcheId, result.machineId)
      if (!machineInfo.valid) {
        setData({ status: 'NEW_ERROR', error: { message: machineInfo.error } })
      } else {
        setData({ status: 'LOADED', value: { pivot: result, machineInfo: machineInfo.value } })
      }
    }
  })

  return () => (
    <LoadingElement
      data={data.value}
      renderItem={item => (
        <ResultatMiseEnConcurrence
          apiClient={{
            ...props.apiClient,
            etapeCreer: async etape => {
              const value = await props.apiClient.etapeCreer(etape)
              router.push({ name: 'demarche', params: { demarcheId: props.demarcheId } })
              return value
            },
          }}
          user={user}
          pivot={item.pivot}
          machineInfo={item.machineInfo}
          entreprises={entreprises.value}
        />
      )}
    />
  )
})

// @ts-ignore waiting for https://github.com/vuejs/core/issues/7833
PureDemarcheResultatMiseEnConcurrence.props = ['demarcheId', 'apiClient']
