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

import { useAwardsStore } from '../../stores/awards'
import type { AdminWorkflowRule } from '../../types/awards'

function cloneRules(rules: AdminWorkflowRule[]) {
  return rules.map((rule) => ({ ...rule }))
}

function normalizeRule(rule: AdminWorkflowRule): AdminWorkflowRule {
  return {
    ...rule,
    enabled: Boolean(rule.enabled),
    limit: Math.min(50, Math.max(1, Number(rule.limit) || 1)),
    mode: rule.mode === 'warn' ? 'warn' : 'block',
  }
}

export function useAdminWorkflowRules() {
  const store = useAwardsStore()
  const selectedSeasonId = computed(() => store.adminSelectedSeasonId)
  const workflowLoading = ref(false)
  const workflowSaving = ref(false)
  const workflowError = ref('')
  const workflowSuccess = ref('')
  const workflowRules = ref<AdminWorkflowRule[]>([])
  const originalSnapshot = ref('')

  const workflowRuleSummary = computed(() => {
    const active = workflowRules.value.filter((rule) => rule.enabled).length
    const blocking = workflowRules.value.filter((rule) => rule.enabled && rule.mode === 'block').length

    return {
      active,
      blocking,
      total: workflowRules.value.length,
    }
  })

  const hasUnsavedWorkflowRuleChanges = computed(() =>
    JSON.stringify(workflowRules.value.map(normalizeRule)) !== originalSnapshot.value,
  )

  async function loadWorkflowRules() {
    workflowLoading.value = true
    workflowError.value = ''
    workflowSuccess.value = ''
    try {
      const response = await store.loadAdminWorkflowRules()
      workflowRules.value = cloneRules(response.rules)
      originalSnapshot.value = JSON.stringify(workflowRules.value.map(normalizeRule))
    } catch (error) {
      workflowError.value = error instanceof Error ? error.message : 'Workflow-Regeln konnten nicht geladen werden.'
      workflowRules.value = []
      originalSnapshot.value = '[]'
    } finally {
      workflowLoading.value = false
    }
  }

  function updateWorkflowRule(ruleKey: string, patch: Partial<AdminWorkflowRule>) {
    workflowRules.value = workflowRules.value.map((rule) =>
      rule.key === ruleKey ? normalizeRule({ ...rule, ...patch }) : rule,
    )
  }

  async function saveWorkflowRules() {
    workflowSaving.value = true
    workflowError.value = ''
    workflowSuccess.value = ''
    try {
      const payloadRules = workflowRules.value.map(normalizeRule)
      const response = await store.updateAdminWorkflowRules({ rules: payloadRules })
      workflowRules.value = cloneRules(response.rules)
      originalSnapshot.value = JSON.stringify(workflowRules.value.map(normalizeRule))
      workflowSuccess.value = 'Workflow-Regeln wurden gespeichert.'
    } catch (error) {
      workflowError.value = error instanceof Error ? error.message : 'Workflow-Regeln konnten nicht gespeichert werden.'
    } finally {
      workflowSaving.value = false
    }
  }

  onMounted(loadWorkflowRules)
  watch(selectedSeasonId, (next, previous) => {
    if (next && next !== previous) {
      void loadWorkflowRules()
    }
  })

  return {
    hasUnsavedWorkflowRuleChanges,
    workflowError,
    workflowLoading,
    workflowRules,
    workflowRuleSummary,
    workflowSaving,
    workflowSuccess,
    loadWorkflowRules,
    saveWorkflowRules,
    updateWorkflowRule,
  }
}
