<script setup lang="ts">
import { ref } from 'vue'
import { Check, ChevronDown, ChevronUp, Eye, Plus, Save, Star, Trash2 } from '@lucide/vue'

import type { ShowactFormField, ShowactFieldType } from '../../types/awards/showactForm'
import Button from '../ui/Button.vue'
import Modal from '../ui/Modal.vue'
import NativeSelect from '../ui/NativeSelect.vue'
import type { AdminContentForm } from './adminContentTypes'

const props = defineProps<{
  form: AdminContentForm
  saving: boolean
  saveSiteSettings: (sectionLabel?: string) => Promise<void>
}>()

const expandedIndex = ref<number | null>(null)
const previewOpen = ref(false)
const saveMessage = ref('')
const saveError = ref('')

const fieldTypeOptions: { value: ShowactFieldType; label: string }[] = [
  { value: 'text', label: 'Text' },
  { value: 'email', label: 'E-Mail' },
  { value: 'url', label: 'URL' },
  { value: 'textarea', label: 'Textbereich' },
  { value: 'select', label: 'Einzelauswahl (Dropdown)' },
  { value: 'radio', label: 'Einzelauswahl (Liste)' },
  { value: 'multiselect', label: 'Mehrfachauswahl (Liste)' },
  { value: 'checkbox', label: 'Einzelne Checkboxen' },
]

function fieldTypeBadge(type: ShowactFieldType) {
  return {
    text: 'Text',
    email: 'E-Mail',
    url: 'URL',
    textarea: 'Textarea',
    select: 'Dropdown',
    radio: '1 aus Liste',
    multiselect: 'Mehrfach',
    checkbox: 'Checkboxen',
  }[type] ?? type
}

function toggleExpand(index: number) {
  expandedIndex.value = expandedIndex.value === index ? null : index
}

function addField() {
  const newField: ShowactFormField = {
    id: `field_${Date.now()}`,
    type: 'text',
    label: 'Neues Feld',
    placeholder: '',
    helpText: '',
    required: false,
    isArtistName: false,
    options: [],
    allowOther: false,
    maxLength: 200,
  }
  props.form.showactFormSchema.push(newField)
  expandedIndex.value = props.form.showactFormSchema.length - 1
}

function removeField(index: number) {
  props.form.showactFormSchema.splice(index, 1)
  if (expandedIndex.value === index) {
    expandedIndex.value = null
  } else if (expandedIndex.value !== null && expandedIndex.value > index) {
    expandedIndex.value--
  }
}

function moveUp(index: number) {
  if (index === 0) return
  const arr = props.form.showactFormSchema
  const temp = arr[index - 1]
  arr[index - 1] = arr[index]
  arr[index] = temp
  if (expandedIndex.value === index) expandedIndex.value = index - 1
  else if (expandedIndex.value === index - 1) expandedIndex.value = index
}

function moveDown(index: number) {
  const arr = props.form.showactFormSchema
  if (index >= arr.length - 1) return
  const temp = arr[index + 1]
  arr[index + 1] = arr[index]
  arr[index] = temp
  if (expandedIndex.value === index) expandedIndex.value = index + 1
  else if (expandedIndex.value === index + 1) expandedIndex.value = index
}

function setArtistName(index: number, value: boolean) {
  if (value) {
    props.form.showactFormSchema.forEach((f, i) => {
      f.isArtistName = i === index
    })
  } else {
    props.form.showactFormSchema[index].isArtistName = false
  }
}

function toggleRequired(field: ShowactFormField) {
  field.required = !field.required
}

function updateFieldType(field: ShowactFormField, type: ShowactFieldType) {
  field.type = type

  if (type !== 'multiselect') {
    field.allowOther = false
  }

  if (type === 'checkbox' && field.options.length === 0) {
    field.options = ['Option 1', 'Option 2']
  } else if (type === 'radio' && field.options.length === 0) {
    field.options = ['Ja', 'Nein']
  } else if ((type === 'select' || type === 'multiselect') && field.options.length === 0) {
    field.options = type === 'select' ? ['Option 1'] : ['Option 1', 'Option 2']
  }

  if (type === 'textarea' && (!field.maxLength || field.maxLength < 500)) {
    field.maxLength = 1500
  } else if ((type === 'email' || type === 'url') && (!field.maxLength || field.maxLength < 200)) {
    field.maxLength = 500
  } else if ((type === 'select' || type === 'radio') && (!field.maxLength || field.maxLength > 200)) {
    field.maxLength = 120
  } else if ((type === 'multiselect' || type === 'checkbox') && (!field.maxLength || field.maxLength < 120)) {
    field.maxLength = 500
  }
}

async function save() {
  saveMessage.value = ''
  saveError.value = ''
  try {
    await props.saveSiteSettings('Showact-Formular')
    saveMessage.value = 'Formular-Schema gespeichert.'
  } catch (error) {
    saveError.value = error instanceof Error ? error.message : 'Speichern fehlgeschlagen.'
  }
}

function previewOptionLabel(field: ShowactFormField) {
  if (field.type === 'checkbox') {
    return field.options[0] || 'Ja'
  }

  return field.placeholder || 'Antwort'
}

function isChoiceField(field: ShowactFormField) {
  return field.type === 'select' || field.type === 'radio' || field.type === 'multiselect' || field.type === 'checkbox'
}

function isTextLikeField(field: ShowactFormField) {
  return field.type === 'text' || field.type === 'email' || field.type === 'url' || field.type === 'textarea'
}

function usesPlaceholder(field: ShowactFormField) {
  return isTextLikeField(field) || field.type === 'select'
}

function addOption(field: ShowactFormField) {
  const nextIndex = field.options.length + 1
  field.options.push(`Option ${nextIndex}`)
}

function removeOption(field: ShowactFormField, optionIndex: number) {
  field.options.splice(optionIndex, 1)
}

function choiceFieldHint(field: ShowactFormField) {
  if (field.type === 'select') return 'Wird auf der Landingpage als Dropdown mit genau einer Auswahl gezeigt.'
  if (field.type === 'radio') return 'Wird als sichtbare Liste gezeigt, aus der genau ein Eintrag gewählt werden kann.'
  if (field.type === 'multiselect') return 'Wird als Liste mit mehreren ankreuzbaren Optionen für ein gemeinsames Feld gerendert.'
  if (field.type === 'checkbox') return 'Jede Option wird als eigene benennbare Checkbox auf der Landingpage angezeigt.'
  return ''
}
</script>

<template>
  <div class="space-y-4">
    <div class="flex flex-wrap items-center justify-between gap-3">
      <div>
        <h3 class="text-base font-bold text-slate-900">Formular-Builder</h3>
        <p class="mt-0.5 text-sm text-slate-500">Felder definieren, die im Bewerbungs-Modal angezeigt werden.</p>
      </div>
      <div class="flex items-center gap-2">
        <Button
          variant="ghost"
          class="gap-2 rounded-2xl border border-violet-200 bg-white px-4 text-violet-700 shadow-none hover:bg-violet-50"
          @click="previewOpen = true"
        >
          <Eye class="h-4 w-4" />
          Vorschau
        </Button>
        <Button class="gap-2" :disabled="props.saving" @click="save">
          <Save class="h-4 w-4" />
          {{ props.saving ? 'Speichert ...' : 'Schema speichern' }}
        </Button>
      </div>
    </div>

    <p v-if="saveMessage" class="text-sm font-semibold text-emerald-700">{{ saveMessage }}</p>
    <p v-if="saveError" class="text-sm font-semibold text-rose-700">{{ saveError }}</p>

    <div class="overflow-hidden rounded-2xl border border-violet-100 bg-white">
      <div
        v-for="(field, index) in props.form.showactFormSchema"
        :key="field.id"
        class="border-b border-violet-100 last:border-b-0"
      >
        <!-- Field header row -->
        <div class="flex items-center gap-2 px-4 py-3">
          <!-- Up/Down buttons -->
          <div class="flex shrink-0 flex-col gap-0.5">
            <button
              type="button"
              :disabled="index === 0"
              class="flex h-5 w-5 items-center justify-center rounded text-slate-400 hover:text-violet-700 disabled:opacity-30"
              @click="moveUp(index)"
            >
              <ChevronUp class="h-3.5 w-3.5" />
            </button>
            <button
              type="button"
              :disabled="index === props.form.showactFormSchema.length - 1"
              class="flex h-5 w-5 items-center justify-center rounded text-slate-400 hover:text-violet-700 disabled:opacity-30"
              @click="moveDown(index)"
            >
              <ChevronDown class="h-3.5 w-3.5" />
            </button>
          </div>

          <!-- Type badge -->
          <span class="shrink-0 rounded-full bg-violet-100 px-2 py-0.5 text-xs font-bold text-violet-700">
            {{ fieldTypeBadge(field.type) }}
          </span>

          <!-- Label + indicators -->
          <button
            type="button"
            class="flex min-w-0 flex-1 items-center gap-2 text-left"
            @click="toggleExpand(index)"
          >
            <span class="truncate text-sm font-semibold text-slate-800">{{ field.label || '(kein Label)' }}</span>
            <span v-if="field.required" class="shrink-0 text-xs font-bold text-rose-600">*</span>
            <Star v-if="field.isArtistName" class="h-3.5 w-3.5 shrink-0 fill-amber-400 text-amber-500" />
          </button>

          <!-- Delete + expand -->
          <button
            type="button"
            :disabled="props.form.showactFormSchema.length <= 1"
            class="shrink-0 rounded p-1 text-slate-400 hover:text-rose-600 disabled:opacity-30"
            @click="removeField(index)"
          >
            <Trash2 class="h-4 w-4" />
          </button>
          <button
            type="button"
            class="shrink-0 rounded p-1 text-slate-400 hover:text-violet-700"
            @click="toggleExpand(index)"
          >
            <ChevronDown v-if="expandedIndex !== index" class="h-4 w-4" />
            <ChevronUp v-else class="h-4 w-4" />
          </button>
        </div>

        <!-- Expanded editor -->
        <div v-if="expandedIndex === index" class="space-y-3 border-t border-violet-100 bg-violet-50/40 px-4 py-4">
          <div class="grid gap-3 sm:grid-cols-2">
            <!-- Field type -->
            <label class="flex flex-col gap-1.5">
              <span class="text-xs font-bold text-slate-700">Feldtyp</span>
              <NativeSelect
                :model-value="field.type"
                :options="fieldTypeOptions"
                @update:model-value="updateFieldType(field, (($event ?? 'text') as ShowactFieldType))"
              />
            </label>

            <!-- Field ID -->
            <label class="flex flex-col gap-1.5">
              <span class="text-xs font-bold text-slate-700">Feld-ID (eindeutig)</span>
              <input
                v-model="field.id"
                maxlength="80"
                placeholder="z.B. artist_name"
                class="rounded-xl border border-violet-100 bg-white px-3 py-2 text-sm text-slate-700 outline-none focus:border-violet-300 focus:ring-4 focus:ring-violet-100"
              />
            </label>
          </div>

          <div class="grid gap-3 sm:grid-cols-2">
            <!-- Label -->
            <label class="flex flex-col gap-1.5">
              <span class="text-xs font-bold text-slate-700">Label</span>
              <input
                v-model="field.label"
                maxlength="500"
                placeholder="Anzeige-Name"
                class="rounded-xl border border-violet-100 bg-white px-3 py-2 text-sm text-slate-700 outline-none focus:border-violet-300 focus:ring-4 focus:ring-violet-100"
              />
            </label>

            <!-- Placeholder -->
            <label v-if="usesPlaceholder(field)" class="flex flex-col gap-1.5">
              <span class="text-xs font-bold text-slate-700">Platzhaltertext</span>
              <input
                v-model="field.placeholder"
                maxlength="500"
                :placeholder="field.type === 'select' ? 'z.B. Bitte auswählen' : 'Hinweistext im leeren Feld'"
                class="rounded-xl border border-violet-100 bg-white px-3 py-2 text-sm text-slate-700 outline-none focus:border-violet-300 focus:ring-4 focus:ring-violet-100"
              />
            </label>
          </div>

          <!-- Help text -->
          <label class="flex flex-col gap-1.5">
            <span class="text-xs font-bold text-slate-700">Hilfetext / Beschreibung</span>
            <textarea
              v-model="field.helpText"
              rows="2"
              maxlength="1000"
              placeholder="Optionaler Text unter dem Label"
              class="rounded-xl border border-violet-100 bg-white px-3 py-2 text-sm text-slate-700 outline-none focus:border-violet-300 focus:ring-4 focus:ring-violet-100"
            />
          </label>

          <!-- MaxLength -->
          <label v-if="isTextLikeField(field)" class="flex flex-col gap-1.5">
            <span class="text-xs font-bold text-slate-700">Max. Zeichenanzahl</span>
            <input
              v-model.number="field.maxLength"
              type="number"
              min="1"
              max="10000"
              class="w-36 rounded-xl border border-violet-100 bg-white px-3 py-2 text-sm text-slate-700 outline-none focus:border-violet-300 focus:ring-4 focus:ring-violet-100"
            />
          </label>

          <!-- Options for choice fields -->
          <div v-if="isChoiceField(field)" class="space-y-3 rounded-2xl border border-violet-100 bg-white/80 p-4">
            <div class="flex flex-wrap items-start justify-between gap-3">
              <div>
                <span class="text-xs font-bold text-slate-700">Optionen</span>
                <p class="mt-1 text-xs font-semibold leading-5 text-slate-500">
                  {{ choiceFieldHint(field) }}
                </p>
              </div>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                class="gap-2 rounded-xl border border-violet-200 bg-violet-50 text-violet-700 shadow-none hover:bg-violet-100"
                @click="addOption(field)"
              >
                <Plus class="h-4 w-4" />
                Option
              </Button>
            </div>

            <div v-if="field.options.length > 0" class="space-y-2">
              <div
                v-for="(_, optionIndex) in field.options"
                :key="`${field.id}-${optionIndex}`"
                class="grid gap-2 rounded-2xl border border-violet-100 bg-violet-50/55 p-3 sm:grid-cols-[auto_minmax(0,1fr)_auto] sm:items-center"
              >
                <span
                  class="flex h-9 w-9 items-center justify-center rounded-xl border border-violet-200 bg-white text-violet-600"
                  :class="field.type === 'radio' ? 'rounded-full' : ''"
                >
                  <span
                    class="block border-2 border-violet-300 bg-white"
                    :class="field.type === 'radio' ? 'h-3.5 w-3.5 rounded-full' : 'h-3.5 w-3.5 rounded-[4px]'"
                  />
                </span>
                <input
                  v-model="field.options[optionIndex]"
                  maxlength="300"
                  :placeholder="field.type === 'checkbox' ? 'Checkbox-Beschriftung' : 'Optionslabel'"
                  class="rounded-xl border border-violet-100 bg-white px-3 py-2 text-sm font-semibold text-slate-700 outline-none focus:border-violet-300 focus:ring-4 focus:ring-violet-100"
                />
                <button
                  type="button"
                  class="inline-flex h-9 items-center justify-center rounded-xl border border-rose-200 bg-rose-50 px-3 text-sm font-bold text-rose-600 transition hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-40"
                  :disabled="field.options.length <= 1"
                  @click="removeOption(field, optionIndex)"
                >
                  <Trash2 class="h-4 w-4" />
                </button>
              </div>
            </div>

            <p v-else class="rounded-xl border border-dashed border-violet-200 bg-violet-50/60 px-3 py-3 text-sm font-semibold text-slate-500">
              Noch keine Optionen angelegt.
            </p>
          </div>

          <!-- Toggles row -->
          <div class="flex flex-wrap gap-3">
            <!-- Required toggle -->
            <button
              type="button"
              class="inline-flex items-center gap-2 rounded-2xl border px-3.5 py-2 text-sm font-semibold transition"
              :class="field.required
                ? 'border-violet-300 bg-violet-100/90 text-violet-900 shadow-[0_10px_24px_rgba(139,108,219,0.14)]'
                : 'border-violet-200 bg-white text-slate-700 hover:border-violet-300 hover:bg-violet-50'"
              @click="toggleRequired(field)"
            >
              <span
                class="flex h-5 w-5 items-center justify-center rounded-md border transition"
                :class="field.required
                  ? 'border-violet-500 bg-violet-600 text-white'
                  : 'border-violet-200 bg-violet-50 text-transparent'"
              >
                <Check class="h-3.5 w-3.5" />
              </span>
              <span>Pflichtfeld</span>
            </button>

            <!-- isArtistName toggle -->
            <button
              type="button"
              class="inline-flex items-center gap-2 rounded-2xl border px-3.5 py-2 text-sm font-semibold transition"
              :class="field.isArtistName
                ? 'border-amber-300 bg-amber-50 text-amber-900 shadow-[0_10px_24px_rgba(251,191,36,0.16)]'
                : 'border-violet-200 bg-white text-slate-700 hover:border-amber-300 hover:bg-amber-50/70'"
              @click="setArtistName(index, !field.isArtistName)"
            >
              <span
                class="flex h-5 w-5 items-center justify-center rounded-md border transition"
                :class="field.isArtistName
                  ? 'border-amber-400 bg-amber-400 text-white'
                  : 'border-amber-200 bg-amber-50 text-transparent'"
              >
                <Check class="h-3.5 w-3.5" />
              </span>
              <span>Künstlername-Feld</span>
              <Star class="h-3.5 w-3.5 fill-amber-400 text-amber-500" />
            </button>

            <!-- Other option toggle -->
            <button
              v-if="field.type === 'multiselect'"
              type="button"
              class="inline-flex items-center gap-2 rounded-2xl border px-3.5 py-2 text-sm font-semibold transition"
              :class="field.allowOther
                ? 'border-violet-300 bg-violet-100/90 text-violet-900 shadow-[0_10px_24px_rgba(139,108,219,0.14)]'
                : 'border-violet-200 bg-white text-slate-700 hover:border-violet-300 hover:bg-violet-50'"
              @click="field.allowOther = !field.allowOther"
            >
              <span
                class="flex h-5 w-5 items-center justify-center rounded-md border transition"
                :class="field.allowOther
                  ? 'border-violet-500 bg-violet-600 text-white'
                  : 'border-violet-200 bg-violet-50 text-transparent'"
              >
                <Check class="h-3.5 w-3.5" />
              </span>
              <span>„Andere" erlauben</span>
            </button>
          </div>
        </div>
      </div>

      <div v-if="props.form.showactFormSchema.length === 0" class="px-4 py-6 text-center text-sm text-slate-500">
        Noch keine Felder definiert. Klicke unten auf „Feld hinzufügen".
      </div>
    </div>

    <Button variant="ghost" class="gap-2 rounded-2xl border border-violet-200 bg-violet-50 px-4 text-violet-700 shadow-none hover:bg-violet-100" @click="addField">
      <Plus class="h-4 w-4" />
      Feld hinzufügen
    </Button>

    <Modal
      :open="previewOpen"
      size="lg"
      title="Formular-Vorschau"
      subtitle="So werden die aktuell konfigurierten Felder im Bewerbungsformular aufgebaut."
      @close="previewOpen = false"
    >
      <div v-if="props.form.showactFormSchema.length === 0" class="rounded-2xl border border-dashed border-violet-200 bg-violet-50/60 p-6 text-center text-sm font-semibold text-slate-500">
        Noch keine Felder für die Vorschau vorhanden.
      </div>
      <div v-else class="space-y-4">
        <div
          v-for="field in props.form.showactFormSchema"
          :key="field.id"
          class="rounded-2xl border border-violet-100 bg-white p-4 shadow-sm"
        >
          <div class="flex flex-wrap items-center justify-between gap-2">
            <label class="text-sm font-black text-violet-800">
              {{ field.label || '(kein Label)' }}<span v-if="field.required" class="text-rose-600"> *</span>
            </label>
            <span class="rounded-full bg-violet-100 px-2.5 py-1 text-xs font-black text-violet-700">{{ fieldTypeBadge(field.type) }}</span>
          </div>
          <p v-if="field.helpText" class="mt-1 text-xs font-semibold leading-5 text-slate-500">{{ field.helpText }}</p>

          <input
            v-if="field.type === 'text' || field.type === 'email' || field.type === 'url'"
            disabled
            :placeholder="field.placeholder || previewOptionLabel(field)"
            class="mt-3 w-full rounded-xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold text-slate-500"
          />
          <textarea
            v-else-if="field.type === 'textarea'"
            disabled
            rows="3"
            :placeholder="field.placeholder || 'Lange Antwort'"
            class="mt-3 w-full resize-none rounded-xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold text-slate-500"
          />
          <select
            v-else-if="field.type === 'select'"
            disabled
            class="mt-3 w-full rounded-xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold text-slate-500"
          >
            <option>{{ field.placeholder || 'Bitte wählen' }}</option>
            <option v-for="option in field.options" :key="option">{{ option }}</option>
          </select>
          <div v-else-if="field.type === 'radio' || field.type === 'multiselect'" class="mt-3 space-y-2">
            <label
              v-for="option in field.options"
              :key="option"
              class="flex items-center gap-3 rounded-xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold text-slate-600"
            >
              <span
                class="h-4 w-4 border border-violet-300 bg-white"
                :class="field.type === 'radio' ? 'rounded-full' : 'rounded'"
              />
              {{ option }}
            </label>
            <label v-if="field.type === 'multiselect' && field.allowOther" class="flex items-center gap-3 rounded-xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold text-slate-600">
              <span class="h-4 w-4 rounded border border-violet-300 bg-white" />
              Andere:
              <span class="min-w-28 flex-1 border-b border-violet-200 text-slate-400">Eigene Antwort</span>
            </label>
            <p v-if="field.options.length === 0" class="rounded-xl border border-dashed border-violet-200 bg-violet-50/60 px-3 py-3 text-sm font-semibold text-slate-500">
              Keine Optionen konfiguriert.
            </p>
          </div>
          <div v-else-if="field.type === 'checkbox'" class="mt-3 space-y-2">
            <label
              v-for="option in field.options"
              :key="option"
              class="flex items-center gap-3 rounded-xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold text-slate-600"
            >
              <span class="h-4 w-4 rounded border border-violet-300 bg-white" />
              {{ option }}
            </label>
            <p
              v-if="field.options.length === 0"
              class="rounded-xl border border-dashed border-violet-200 bg-violet-50/60 px-3 py-3 text-sm font-semibold text-slate-500"
            >
              Keine Checkboxen konfiguriert.
            </p>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>
