import { computed } from 'vue'
import { BarChart3, Clock3, ShieldAlert, Sparkles, Tags, Users } from '@lucide/vue'

import { getRiskMetricValue, getVoteMetricValue } from '../../lib/adminMetrics'
import { useAwardsStore } from '../../stores/awards'
import { useAuthStore } from '../../stores/auth'

const metricToneMap = {
  Nominierungen: {
    icon: Sparkles,
    source: 'Nomination-Tabelle',
  },
  Stimmen: {
    icon: BarChart3,
    source: 'VoteEntries-Tabelle',
  },
  Kategorien: {
    icon: Tags,
    source: 'Categories-Tabelle',
  },
  'Reviews offen': {
    icon: Clock3,
    source: 'Nominations-Review-Status',
  },
  Risikohinweise: {
    icon: ShieldAlert,
    source: 'RiskFlags-Tabelle',
  },
} as const

export function useAdminDashboardOverview() {
  const store = useAwardsStore()
  const authStore = useAuthStore()

  const metrics = computed(() => store.admin.metrics)
  const activities = computed(() => store.admin.activities)
  const topCategories = computed(() => store.admin.topCategories)
  const metricCards = computed(() =>
    metrics.value.map((metric) => ({
      ...metric,
      ...(metricToneMap[metric.label as keyof typeof metricToneMap] ?? {
        icon: BarChart3,
        source: 'Backend-Metrik',
      }),
    })),
  )
  const openReviewCount = computed(() => store.adminSeasonDetail.pendingNominations.length)
  const openRiskCount = computed(() => getRiskMetricValue(metrics.value))
  const liveSummary = computed(() => {
    const phase = store.adminSeasonDetail.currentPhase || 'nicht gesetzt'
    const reviewText = openReviewCount.value === 1 ? '1 offene Review' : `${openReviewCount.value} offene Reviews`
    const riskText = openRiskCount.value === 1 ? '1 Risikohinweis' : `${openRiskCount.value} Risikohinweise`
    const categoryText = store.adminSeasonDetail.categories.length === 1
      ? '1 Kategorie'
      : `${store.adminSeasonDetail.categories.length} Kategorien`
    const candidateText = store.adminSeasonDetail.candidates.length === 1
      ? '1 Kandidat'
      : `${store.adminSeasonDetail.candidates.length} Kandidaten`

    return `Aktuelle Phase: ${phase}. ${categoryText}, ${candidateText}, ${reviewText} und ${riskText} kommen direkt aus der Admin-API.`
  })
  const liveStatusBadge = computed(() => {
    if (openRiskCount.value > 0) {
      return `${openRiskCount.value} Risiko offen`
    }

    if (openReviewCount.value > 0) {
      return `${openReviewCount.value} Review offen`
    }

    return 'Betrieb wirkt sauber'
  })
  const maxCategoryVotes = computed(() => Math.max(...topCategories.value.map((category) => category.votes), 1))
  const totalCategoryVotes = computed(() => topCategories.value.reduce((sum, category) => sum + category.votes, 0))
  const yearTotals = computed(() => [
    {
      label: 'Nominierungen gesamt',
      value: metrics.value.find((metric) => metric.label === 'Nominierungen')?.value ?? 0,
      note: `im Award-Jahr ${store.adminSeasonDetail.year}`,
      icon: Sparkles,
    },
    {
      label: 'Stimmen gesamt',
      value: getVoteMetricValue(metrics.value),
      note: 'alle abgegebenen Votes',
      icon: BarChart3,
    },
    {
      label: 'Kandidaten',
      value: store.adminSeasonDetail.candidates.length,
      note: 'für Voting und Archiv gepflegt',
      icon: Users,
    },
    {
      label: 'Kategorien',
      value: store.adminSeasonDetail.categories.length,
      note: 'aktive Award-Kategorien',
      icon: Tags,
    },
    {
      label: 'Offene Reviews',
      value: store.adminSeasonDetail.pendingNominations.length,
      note: 'brauchen Team-Entscheidung',
      icon: Clock3,
    },
    {
      label: 'Risikohinweise',
      value: openRiskCount.value,
      note: 'aktuell offen',
      icon: ShieldAlert,
    },
  ])
  function canOpenAdminPath(path: string) {
    if (path.startsWith('/admin/nominations')) return authStore.hasPermission('nominations')
    if (path.startsWith('/admin/risk')) return authStore.hasPermission('risk')
    if (path.startsWith('/admin/categories')) return authStore.hasPermission('categories')
    if (path.startsWith('/admin/candidates')) return authStore.hasPermission('candidates')
    if (path.startsWith('/admin/clips')) return authStore.hasPermission('clips')
    if (path.startsWith('/admin/winners')) return authStore.hasPermission('winners')
    if (path.startsWith('/admin/analytics')) return authStore.hasPermission('analytics')
    return true
  }

  const priorityActions = computed(() => [
    {
      label: 'Reviews bearbeiten',
      value: store.adminSeasonDetail.pendingNominations.length,
      to: '/admin/nominations?review=1',
      hint: 'Freitext-Nominierungen warten auf Entscheidung',
      icon: Sparkles,
      tone: 'violet',
    },
    {
      label: 'Risiko prüfen',
      value: openRiskCount.value,
      to: '/admin/risk',
      hint: 'Auffällige Muster brauchen Sichtung',
      icon: ShieldAlert,
      tone: 'rose',
    },
    {
      label: 'Kategorien pflegen',
      value: store.adminSeasonDetail.categories.length,
      to: '/admin/categories',
      hint: 'Texte, Limits und Reihenfolge aktuell halten',
      icon: Tags,
      tone: 'amber',
    },
    {
      label: 'Kandidatenbasis',
      value: store.adminSeasonDetail.candidates.length,
      to: '/admin/candidates',
      hint: 'Kandidaten und Plattformen schnell prüfen',
      icon: Users,
      tone: 'emerald',
    },
  ].filter((item) => canOpenAdminPath(item.to)))
  const operationChecks = computed(() => {
    const categoriesWithoutCandidates = store.adminSeasonDetail.categories.filter((category) =>
      !store.adminSeasonDetail.candidates.some((candidate) => candidate.categoryId === category.id),
    )
    const categoriesWithReviews = store.adminSeasonDetail.categories.filter((category) =>
      store.adminSeasonDetail.pendingNominations.some((nomination) => nomination.categoryId === category.id),
    )

    return [
      {
        label: 'Kategorien ohne Kandidaten',
        value: categoriesWithoutCandidates.length,
        to: '/admin/categories',
        state: categoriesWithoutCandidates.length === 0 ? 'ok' : 'warn',
        note: categoriesWithoutCandidates.length === 0 ? 'Alle Kategorien sind besetzt.' : 'Vor Voting-Endspurt prüfen.',
      },
      {
        label: 'Review-Backlog verteilt',
        value: categoriesWithReviews.length,
        to: '/admin/nominations',
        state: categoriesWithReviews.length <= 1 ? 'ok' : 'warn',
        note: categoriesWithReviews.length <= 1 ? 'Backlog ist fokussiert.' : 'Mehrere Kategorien brauchen Sichtung.',
      },
      {
        label: 'Risk Flags offen',
        value: openRiskCount.value,
        to: '/admin/risk',
        state: openRiskCount.value === 0 ? 'ok' : 'danger',
        note: openRiskCount.value === 0 ? 'Keine offenen Hinweise.' : 'Missbrauchsschutz zuerst prüfen.',
      },
    ].filter((item) => canOpenAdminPath(item.to))
  })

  return {
    store,
    activities,
    topCategories,
    metricCards,
    openReviewCount,
    openRiskCount,
    liveSummary,
    liveStatusBadge,
    maxCategoryVotes,
    totalCategoryVotes,
    yearTotals,
    priorityActions,
    operationChecks,
  }
}
