<script setup lang="ts">
import type { BackendError } from '~/types'

import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useStore } from '~/store'

import axios from 'axios'

import Layout from '~/components/ui/Layout.vue'
import Button from '~/components/ui/Button.vue'
import Input from '~/components/ui/Input.vue'
import Alert from '~/components/ui/Alert.vue'

import updateQueryString from '~/composables/updateQueryString'
import useLogger from '~/composables/useLogger'

type Type = 'rss' | 'artists' | 'both'

interface Events {
  (e: 'subscribed', rss: object): void
}

interface Props {
  initialId?: string
  initialType?: Type
  redirect?: boolean
  showSubmit?: boolean
  standalone?: boolean
}

const emit = defineEmits<Events>()
const props = withDefaults(defineProps<Props>(), {
  initialId: '',
  initialType: 'artists',
  redirect: true,
  showSubmit: true,
  standalone: true
})

const type = ref(props.initialType)
const id = ref(props.initialId)
const errors = ref([] as string[])

const logger = useLogger()
const { t } = useI18n()
const labels = computed(() => ({
  title: type.value === 'rss'
    ? t('components.RemoteSearchForm.label.rss.title')
    : t('components.RemoteSearchForm.label.fediverse.title'),
  fieldLabel: type.value === 'rss'
    ? t('components.RemoteSearchForm.label.rss.fieldLabel')
    : t('components.RemoteSearchForm.label.fediverse.fieldLabel'),
  fieldPlaceholder: type.value === 'rss'
    ? t('components.RemoteSearchForm.label.rss.fieldPlaceholder')
    : t('components.RemoteSearchForm.label.fediverse.fieldPlaceholder')
}))

const obj = ref()
const objInfo = computed(() => obj.value?.status === 'finished' ? obj.value.object : null)
const redirectRoute = computed(() => {
  if (!objInfo.value) {
    return null
  }

  switch (objInfo.value.type) {
    case 'account': {
      const [username, domain] = objInfo.value.full_username.split('@')
      return { name: 'profile.full', params: { username, domain } }
    }

    case 'library':
      return { name: 'library.detail', params: { id: objInfo.value.uuid } }

    case 'artist':
      return { name: 'library.artists.detail', params: { id: objInfo.value.id } }

    case 'album':
      return { name: 'library.albums.detail', params: { id: objInfo.value.id } }

    case 'track':
      return { name: 'library.tracks.detail', params: { id: objInfo.value.id } }

    case 'upload':
      return { name: 'library.uploads.detail', params: { id: objInfo.value.uuid } }

    case 'channel':
      return { name: 'channels.detail', params: { id: objInfo.value.uuid } }
  }

  return null
})

const router = useRouter()
watch(redirectRoute, () => {
  if (props.redirect && redirectRoute.value) {
    return router.push(redirectRoute.value)
  }
})

const submit = () => {
  if (type.value === 'rss') {
    return rssSubscribe()
  }

  return createFetch()
}

const isLoading = ref(false)
const createFetch = async () => {
  logger.debug(id.value, props.standalone)
  if (!id.value) return
  if (props.standalone) {
    history.replaceState(history.state, '', updateQueryString(location.href, 'id', id.value))
  }

  obj.value = undefined
  errors.value = []
  isLoading.value = true

  try {
    const response = await axios.post('federation/fetches/', { object_uri: id.value })
    obj.value = response.data

    if (response.data.status === 'errored' || response.data.status === 'skipped') {
      errors.value.push(t('components.RemoteSearchForm.error.fetchFailed'))
    }
  } catch (error) {
    errors.value = (error as BackendError).backendErrors
  }

  isLoading.value = false
}

const store = useStore()

const rssSubscribe = async () => {
  if (!id.value) return
  if (props.standalone) {
    history.replaceState(history.state, '', updateQueryString(location.href, 'id', id.value))
  }

  obj.value = undefined
  errors.value = []
  isLoading.value = true

  try {
    const response = await axios.post('channels/rss-subscribe/', { url: id.value })
    store.commit('channels/subscriptions', { uuid: response.data.channel.uuid, value: true })
    emit('subscribed', response.data)

    if (props.redirect) {
      return router.push({ name: 'channels.detail', params: { id: response.data.channel.uuid } })
    }
  } catch (error) {
    errors.value = (error as BackendError).backendErrors
  }

  isLoading.value = false
}

watch(() => props.initialId, () => {
  id.value = props.initialId

  if (id.value) {
    submit()
  }
}, { immediate: true })
</script>

<template>
  <Layout
    v-if="type === 'both'"
    stack
  >
    <Button
      secondary
      raised
      split
      round
      icon="bi-rss-fill"
      split-icon="bi-globe"
      style="align-self: center;"
      :split-title="t('components.RemoteSearchForm.button.fediverse')"
      @click.prevent="type = 'rss'"
      @split-click.prevent="type = 'artists'"
    >
      {{ t('components.RemoteSearchForm.button.rss') }}
    </Button>
  </Layout>
  <Layout
    v-else
    id="remote-search"
    form
    :class="['ui', {loading: isLoading}, 'form']"
    @submit.stop.prevent="submit"
  >
    <Alert
      v-if="errors.length > 0"
      red
      role="alert"
      title="t('components.RemoteSearchForm.header.fetchFailed')"
    >
      <ul
        v-if="errors.length > 1"
        class="list"
      >
        <li
          v-for="(error, key) in errors"
          :key="key"
        >
          {{ error }}
        </li>
      </ul>
      <p v-else>
        {{ errors[0] }}
      </p>
    </Alert>
    <p v-if="type === 'rss'">
      {{ t('components.RemoteSearchForm.description.rss') }}
    </p>
    <p v-else-if="type === 'artists'">
      {{ t('components.RemoteSearchForm.description.fediverse') }}
    </p>

    <Input
      id="object-id"
      v-model="id"
      type="text"
      name="object-id"
      :label="labels.fieldLabel"
      :placeholder="labels.fieldPlaceholder"
      style="width: 100%;"
      required
    />

    <Button
      v-if="showSubmit"
      primary
      type="submit"
      :class="{loading: isLoading}"
      :disabled="isLoading || !id || id.length === 0"
    >
      {{ t('components.RemoteSearchForm.button.search') }}
    </Button>
  </Layout>
  <Alert
    v-if="!isLoading && obj?.status === 'finished' && !redirectRoute"
    red
  >
    {{ t('components.RemoteSearchForm.warning.unsupported') }}
  </Alert>
</template>
