import { defineComponent, inject, onMounted } from 'vue'
import { AsyncData, asyncDataAutomaticLoad } from '@/api/client-rest'
import { GetMutation, MutationId, mutationIdValidator } from 'camino-common/src/mutations'
import { LoadingElement } from './_ui/functional-loader'
import { useState } from '@/utils/vue-tsx-utils'
import { JournauxApiClient, journauxApiClient } from './journaux/journaux-api-client'
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { isNotNullNorUndefined } from 'camino-common/src/typescript-tools'
import { CaminoAccessError } from './error'
import { userKey } from '@/moi'
import { fr } from '@codegouvfr/react-dsfr'
import { LabelWithValue } from './_ui/label-with-value'
import { dateTimeFormat } from 'camino-common/src/date'

export const Mutation = defineComponent(() => {
  const route = useRoute<'mutation'>()
  const user = inject(userKey)

  const mutationId = computed<MutationId | null>(() => {
    const mutationId = route.params.mutationId
    const validated = mutationIdValidator.safeParse(mutationId)

    if (validated.success) {
      return validated.data
    }

    return null
  })

  return () => <>{isNotNullNorUndefined(mutationId.value) ? <PureMutation apiClient={journauxApiClient} mutationId={mutationId.value} /> : <CaminoAccessError user={user} />}</>
})

interface Props {
  apiClient: Pick<JournauxApiClient, 'getMutation'>
  mutationId: MutationId
}
export const PureMutation = defineComponent<Props>(props => {
  const [mutation, setMutation] = useState<AsyncData<GetMutation>>({ status: 'LOADING' })
  onMounted(async () => {
    await asyncDataAutomaticLoad(() => props.apiClient.getMutation(props.mutationId), setMutation)
  })

  return () => (
    <LoadingElement
      data={mutation.value}
      renderItem={item => (
        <>
          <div class={fr.cx('fr-pt-8w', 'fr-pb-4w')} style={{ display: 'flex', gap: '2rem', flexDirection: 'column' }}>
            <LabelWithValue title="Date" text={dateTimeFormat(new Date(item.datetime))} />
            <LabelWithValue title="Utilisateur" text={`${item.utilisateur_nom} ${item.utilisateur_prenom}`} />
            <LabelWithValue title="Path" text={item.path} />
            <LabelWithValue title="Méthode" text={item.method} />
            <LabelWithValue title="Body" item={<pre>{JSON.stringify(JSON.parse(item.body), null, 4)}</pre>} />
          </div>
        </>
      )}
    />
  )
})

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