import { computed, onMounted, reactive, ref } from 'vue'

import { useAwardsStore } from '../../stores/awards'

const fallbackDisabledMessage = 'Clip-Einreichungen sind aktuell geschlossen.'

export function useAdminOptionalFeatures() {
  const store = useAwardsStore()
  const optionalFeaturesLoading = ref(false)
  const optionalFeaturesSaving = ref(false)
  const optionalFeaturesError = ref('')
  const optionalFeaturesSuccess = ref('')
  const optionalFeaturesModalOpen = ref(false)
  const originalSnapshot = ref('')
  const optionalFeaturesForm = reactive({
    clipSubmissionsEnabled: false,
    clipReviewEnabled: true,
    clipAdminMenuVisible: true,
    clipSubmissionDisabledMessage: fallbackDisabledMessage,
  })

  const pendingClipCount = computed(() =>
    store.adminSeasonDetail.clipSubmissions.filter((clip) => clip.status === 'pending').length,
  )
  const totalClipCount = computed(() => store.adminSeasonDetail.clipSubmissions.length)
  const optionalFeaturesSummary = computed(() => ({
    clipSubmissionsEnabled: optionalFeaturesForm.clipSubmissionsEnabled,
    clipReviewEnabled: optionalFeaturesForm.clipReviewEnabled,
    pendingClipCount: pendingClipCount.value,
    totalClipCount: totalClipCount.value,
  }))
  const hasUnsavedOptionalFeatureChanges = computed(() =>
    JSON.stringify(normalizedForm()) !== originalSnapshot.value,
  )

  function normalizedForm() {
    return {
      clipSubmissionsEnabled: optionalFeaturesForm.clipSubmissionsEnabled,
      clipReviewEnabled: optionalFeaturesForm.clipReviewEnabled,
      clipAdminMenuVisible: optionalFeaturesForm.clipAdminMenuVisible,
      clipSubmissionDisabledMessage: normalizeDisabledMessage(optionalFeaturesForm.clipSubmissionDisabledMessage),
      showactApplicationsEnabled: store.adminOptionalFeatureSettings.showactApplicationsEnabled,
      showactApplicationStartsAt: store.adminOptionalFeatureSettings.showactApplicationStartsAt,
      showactApplicationEndsAt: store.adminOptionalFeatureSettings.showactApplicationEndsAt,
      showactApplicationDisabledMessage: store.adminOptionalFeatureSettings.showactApplicationDisabledMessage,
      sponsorsVisible: store.adminOptionalFeatureSettings.sponsorsVisible,
    }
  }

  function applyResponse(response = store.adminOptionalFeatureSettings) {
    optionalFeaturesForm.clipSubmissionsEnabled = response.clipSubmissionsEnabled
    optionalFeaturesForm.clipReviewEnabled = response.clipReviewEnabled
    optionalFeaturesForm.clipAdminMenuVisible = response.clipAdminMenuVisible
    optionalFeaturesForm.clipSubmissionDisabledMessage = normalizeDisabledMessage(response.clipSubmissionDisabledMessage)
    originalSnapshot.value = JSON.stringify(normalizedForm())
  }

  async function loadOptionalFeatureSettings() {
    optionalFeaturesLoading.value = true
    optionalFeaturesError.value = ''
    optionalFeaturesSuccess.value = ''
    try {
      const response = await store.loadAdminOptionalFeatureSettings()
      applyResponse(response)
    } catch (error) {
      optionalFeaturesError.value = error instanceof Error ? error.message : 'Optionale Workflows konnten nicht geladen werden.'
      applyResponse()
    } finally {
      optionalFeaturesLoading.value = false
    }
  }

  async function saveOptionalFeatureSettings() {
    optionalFeaturesSaving.value = true
    optionalFeaturesError.value = ''
    optionalFeaturesSuccess.value = ''
    try {
      const response = await store.updateAdminOptionalFeatureSettings(normalizedForm())
      applyResponse(response)
      optionalFeaturesSuccess.value = 'Clip-Workflow wurde gespeichert.'
      optionalFeaturesModalOpen.value = false
    } catch (error) {
      optionalFeaturesError.value = error instanceof Error ? error.message : 'Clip-Workflow konnte nicht gespeichert werden.'
    } finally {
      optionalFeaturesSaving.value = false
    }
  }

  function openOptionalFeaturesModal() {
    optionalFeaturesError.value = ''
    optionalFeaturesSuccess.value = ''
    optionalFeaturesModalOpen.value = true
  }

  function closeOptionalFeaturesModal() {
    if (hasUnsavedOptionalFeatureChanges.value && !window.confirm('Ungespeicherte Clip-Workflow-Änderungen verwerfen?')) {
      return
    }

    applyResponse()
    optionalFeaturesModalOpen.value = false
  }

  onMounted(loadOptionalFeatureSettings)

  return {
    hasUnsavedOptionalFeatureChanges,
    optionalFeaturesError,
    optionalFeaturesForm,
    optionalFeaturesLoading,
    optionalFeaturesModalOpen,
    optionalFeaturesSaving,
    optionalFeaturesSuccess,
    optionalFeaturesSummary,
    closeOptionalFeaturesModal,
    loadOptionalFeatureSettings,
    openOptionalFeaturesModal,
    saveOptionalFeatureSettings,
  }
}

function normalizeDisabledMessage(value: string) {
  const trimmed = value.trim()
  return trimmed ? trimmed.slice(0, 240) : fallbackDisabledMessage
}
