<script setup lang="ts">
import { FileText, Handshake, MessageCircleQuestion, Mic2, RadioTower, ScrollText, Send, Share2, ShieldCheck, Sparkles } from '@lucide/vue'
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import AdminContentAwardsSection from '../../components/admin/AdminContentAwardsSection.vue'
import AdminContentBasicsSection from '../../components/admin/AdminContentBasicsSection.vue'
import AdminContentFaqPreviewModal from '../../components/admin/AdminContentFaqPreviewModal.vue'
import AdminContentFaqSection from '../../components/admin/AdminContentFaqSection.vue'
import AdminContentLandingExtrasSection from '../../components/admin/AdminContentLandingExtrasSection.vue'
import AdminContentPageSection from '../../components/admin/AdminContentPageSection.vue'
import AdminContentPrivacyPreviewModal from '../../components/admin/AdminContentPrivacyPreviewModal.vue'
import AdminContentPrivacySection from '../../components/admin/AdminContentPrivacySection.vue'
import AdminContentSocialLinksSection from '../../components/admin/AdminContentSocialLinksSection.vue'
import AdminContentStreamBannerSection from '../../components/admin/AdminContentStreamBannerSection.vue'
import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import Modal from '../../components/ui/Modal.vue'
import { watchAdminToast } from '../../composables/useAdminToast'
import { useAwardsStore } from '../../stores/awards'
import { useAdminContentManager } from '../../components/admin/useAdminContentManager'

type ContentEditorKey = 'awards' | 'streamBanner' | 'imprint' | 'contact' | 'socials' | 'faq' | 'privacy' | 'showacts' | 'sponsors'

const store = useAwardsStore()
const route = useRoute()
const router = useRouter()

const {
  form,
  saving,
  saveMessage,
  saveError,
  privacyPreviewOpen,
  iconUploadError,
  hostImageUploadError,
  hostImageUploading,
  privacyPreviewHtml,
  privacyUpdatedLabel,
  addSocialLink,
  removeSocialLink,
  addFaqItem,
  removeFaqItem,
  isUploadedIcon,
  selectedSocialIconValue,
  handleSocialIconSelection,
  hasSocialIconPreview,
  socialIconModeLabel,
  socialSimpleIconPath,
  socialSimpleIconColor,
  handleSocialIconUpload,
  clearSocialIcon,
  handleHostImageUpload,
  saveSiteSettings,
  adminSiteSettings,
} = useAdminContentManager()

watchAdminToast(saveMessage, saveError)

const faqPreviewOpen = ref(false)
const activeContentEditor = ref<ContentEditorKey | null>(null)

const contentEditors = computed(() => [
  {
    key: 'awards' as const,
    eyebrow: 'Landingpage',
    title: 'Awards-Bereich',
    description: 'Titel und Beschreibung für Die Awards und Unterkategorien pflegen.',
    metric: form.awardsSectionTitle.trim() && form.subcategoriesSectionTitle.trim() ? 'Texte gepflegt' : 'Texte prüfen',
    icon: Sparkles,
  },
  {
    key: 'streamBanner' as const,
    eyebrow: 'Landingpage',
    title: 'Finale-Banner',
    description: 'Titel, Text, Button und Abschluss-Inhalt für den Countdown-Banner pflegen.',
    metric: form.streamBannerUseCompletedContent ? 'Abschluss aktiv' : 'Countdown aktiv',
    icon: RadioTower,
  },
  {
    key: 'imprint' as const,
    eyebrow: 'Rechtliches',
    title: 'Impressum',
    description: 'Impressumstext für das Footer-Modal bearbeiten.',
    metric: form.imprintContent ? 'Inhalt vorhanden' : 'Leer',
    icon: ScrollText,
  },
  {
    key: 'contact' as const,
    eyebrow: 'Rechtliches',
    title: 'Kontakt',
    description: 'Kontakttext für das Footer-Modal bearbeiten.',
    metric: form.contactContent ? 'Inhalt vorhanden' : 'Leer',
    icon: Send,
  },
  {
    key: 'showacts' as const,
    eyebrow: 'Show Module',
    title: 'Showacts',
    description: 'Seiteninhalt, Banner-Toggle und Bewerbungen verwalten.',
    metric: `${store.adminShowactApplications.length} Bewerbungen`,
    icon: Mic2,
  },
  {
    key: 'sponsors' as const,
    eyebrow: 'Partner',
    title: 'Sponsoren',
    description: 'Seiteninhalt, Sichtbarkeit und Sponsor-Kacheln verwalten.',
    metric: `${store.adminSponsors.length} Einträge`,
    icon: Handshake,
  },
  {
    key: 'socials' as const,
    eyebrow: 'Community',
    title: 'Social Links',
    description: 'Plattformen, Labels, URLs und Custom Icons pflegen.',
    metric: `${form.socialLinks.length} Links`,
    icon: Share2,
  },
  {
    key: 'faq' as const,
    eyebrow: 'Support',
    title: 'FAQ',
    description: 'Fragen und Antworten für die Landingpage verwalten.',
    metric: `${form.faq.length} Fragen`,
    icon: MessageCircleQuestion,
  },
  {
    key: 'privacy' as const,
    eyebrow: 'Rechtstexte',
    title: 'Datenschutz',
    description: 'Datenschutz-E-Mail und Datenschutzerklärung bearbeiten.',
    metric: privacyUpdatedLabel.value,
    icon: ShieldCheck,
  },
])

const currentContentEditor = computed(() => contentEditors.value.find((item) => item.key === activeContentEditor.value) ?? null)

watch(
  () => route.query.editor,
  (editor) => {
    const resolved = Array.isArray(editor) ? editor[0] : editor
    activeContentEditor.value = contentEditors.value.some((item) => item.key === resolved)
      ? resolved as ContentEditorKey
      : null
  },
  { immediate: true },
)

function openContentEditor(key: ContentEditorKey) {
  const nextQuery = { ...route.query, editor: key } as Record<string, string>
  void router.replace({ query: nextQuery })
}

function closeContentEditor() {
  const nextQuery = { ...route.query } as Record<string, string>
  delete nextQuery.editor
  void router.replace({ query: nextQuery })
}
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Content Hub"
      description="Landingpage, Footer, Social Links und Rechtstexte pflegen."
      :icon="FileText"
    />

    <AdminContentBasicsSection
      :form="form"
      :saving="saving"
      :host-image-uploading="hostImageUploading"
      :host-image-upload-error="hostImageUploadError"
      :handle-host-image-upload="handleHostImageUpload"
      :save-site-settings="saveSiteSettings"
    />

    <section aria-labelledby="content-editor-title" class="space-y-4">
      <div>
        <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Weitere Bereiche</p>
        <h2 id="content-editor-title" class="mt-1 text-xl font-bold text-slate-900">Landingpage-Module bearbeiten</h2>
      </div>

      <div class="grid gap-3 lg:grid-cols-2">
        <button
          v-for="editor in contentEditors"
          :key="editor.key"
          type="button"
          class="group flex min-h-[132px] items-start gap-4 rounded-[24px] border border-violet-100 bg-white/86 p-5 text-left shadow-[0_16px_40px_rgba(124,92,255,0.07)] transition hover:-translate-y-0.5 hover:border-violet-200 hover:bg-violet-50/70 hover:shadow-[0_20px_48px_rgba(124,92,255,0.12)]"
          @click="openContentEditor(editor.key)"
        >
          <span class="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-violet-100 text-violet-700 transition group-hover:bg-white">
            <component :is="editor.icon" class="h-5 w-5" />
          </span>
          <span class="min-w-0 flex-1">
            <span class="block text-[11px] font-semibold uppercase tracking-[0.2em] text-violet-500">{{ editor.eyebrow }}</span>
            <span class="mt-1 block text-lg font-bold text-slate-900">{{ editor.title }}</span>
            <span class="mt-2 block text-sm leading-6 text-slate-500">{{ editor.description }}</span>
          </span>
          <span class="shrink-0 rounded-2xl border border-violet-100 bg-violet-50 px-3 py-2 text-xs font-bold text-violet-700">{{ editor.metric }}</span>
        </button>
      </div>
    </section>

    <Modal
      :open="activeContentEditor !== null"
      :title="currentContentEditor?.title"
      :subtitle="currentContentEditor?.description"
      size="xl"
      @close="closeContentEditor"
    >
      <AdminContentAwardsSection
        v-if="activeContentEditor === 'awards'"
        :form="form"
        :saving="saving"
        :save-site-settings="saveSiteSettings"
      />
      <AdminContentStreamBannerSection
        v-else-if="activeContentEditor === 'streamBanner'"
        :form="form"
        :saving="saving"
        :save-site-settings="saveSiteSettings"
      />
      <AdminContentPageSection
        v-else-if="activeContentEditor === 'imprint'"
        :form="form"
        :saving="saving"
        content-key="imprintContent"
        label="Impressum"
        placeholder="Impressumstext..."
        :save-site-settings="saveSiteSettings"
      />
      <AdminContentPageSection
        v-else-if="activeContentEditor === 'contact'"
        :form="form"
        :saving="saving"
        content-key="contactContent"
        label="Kontakt"
        placeholder="Kontakttext..."
        :save-site-settings="saveSiteSettings"
      />
      <AdminContentSocialLinksSection
        v-else-if="activeContentEditor === 'socials'"
        :form="form"
        :saving="saving"
        :icon-upload-error="iconUploadError"
        :add-social-link="addSocialLink"
        :remove-social-link="removeSocialLink"
        :is-uploaded-icon="isUploadedIcon"
        :selected-social-icon-value="selectedSocialIconValue"
        :handle-social-icon-selection="handleSocialIconSelection"
        :has-social-icon-preview="hasSocialIconPreview"
        :social-icon-mode-label="socialIconModeLabel"
        :social-simple-icon-path="socialSimpleIconPath"
        :social-simple-icon-color="socialSimpleIconColor"
        :handle-social-icon-upload="handleSocialIconUpload"
        :clear-social-icon="clearSocialIcon"
        :save-site-settings="saveSiteSettings"
      />
      <AdminContentFaqSection
        v-else-if="activeContentEditor === 'faq'"
        :form="form"
        :saving="saving"
        :add-faq-item="addFaqItem"
        :remove-faq-item="removeFaqItem"
        :save-site-settings="saveSiteSettings"
        @open-preview="faqPreviewOpen = true"
      />
      <AdminContentPrivacySection
        v-else-if="activeContentEditor === 'privacy'"
        :form="form"
        :saving="saving"
        :updated-by="adminSiteSettings.privacyPolicyUpdatedBy"
        :updated-label="privacyUpdatedLabel"
        :save-site-settings="saveSiteSettings"
        @open-preview="privacyPreviewOpen = true"
      />
      <AdminContentLandingExtrasSection
        v-else-if="activeContentEditor === 'showacts'"
        section="showacts"
        :form="form"
        :saving="saving"
        :save-site-settings="saveSiteSettings"
      />
      <AdminContentLandingExtrasSection
        v-else-if="activeContentEditor === 'sponsors'"
        section="sponsors"
        :form="form"
        :saving="saving"
        :save-site-settings="saveSiteSettings"
      />
    </Modal>

    <AdminContentPrivacyPreviewModal
      :open="privacyPreviewOpen"
      :content-html="privacyPreviewHtml"
      :updated-label="privacyUpdatedLabel"
      @close="privacyPreviewOpen = false"
    />
    <AdminContentFaqPreviewModal
      :open="faqPreviewOpen"
      :faq="form.faq"
      @close="faqPreviewOpen = false"
    />
  </div>
</template>
