<template>
  <div class="ivyforms-form-styles">
    <!-- Theme Selection View -->
    <template v-if="!isCustomizing">
      <div class="ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-16">
        <!-- TODO Disable Styles -->
        <!--        <div class="ivyforms-flex ivyforms-align-items-center ivyforms-gap-12">-->
        <!--          <IvyToggle v-model="stylesDisabled" size="d" />-->
        <!--          <div class="ivyforms-flex ivyforms-align-items-center ivyforms-gap-4 ivyforms-flex-1">-->
        <!--            <div class="ivyforms-form-styles__disable-label regular-16">-->
        <!--              {{ getLabel('disable_styles') }}-->
        <!--            </div>-->
        <!--            <IvyTooltip :content="getLabel('disable_styles_tooltip')">-->
        <!--              <IvyIcon-->
        <!--                name="question"-->
        <!--                type="outline"-->
        <!--                size="s"-->
        <!--                color="var(&#45;&#45;map-base-dusk-symbol-2)"-->
        <!--                class="ivyforms-radio__tooltip-icon"-->
        <!--                @click.prevent-->
        <!--              />-->
        <!--            </IvyTooltip>-->
        <!--          </div>-->
        <!--        </div>-->

        <!-- Ivy Styles Section -->
        <div v-if="!stylesDisabled" class="ivyforms-form-styles__section ivyforms-width-100">
          <div
            class="ivyforms-form-styles__section-title ivyforms-border-bottom ivyforms-flex ivyforms-pb-8 ivyforms-align-items-center ivyforms-gap-16 ivyforms-align-self-stretch"
          >
            {{ getLabel('ivy_styles') }}
          </div>

          <div
            class="ivyforms-form-styles__themes ivyforms-pt-16 ivyforms-gap-4 ivyforms-flex ivyforms-flex-direction-column ivyforms-width-100"
          >
            <IvyThemeCard
              v-for="theme in availableThemes"
              :key="theme.id"
              :theme="theme"
              :is-selected="selectedThemeId === theme.id"
              :selected-theme-id="selectedThemeId"
              @select="handleThemeClick"
              @menu-click="handleThemeMenuClick"
            />
          </div>
        </div>
      </div>
    </template>

    <!-- Customization View -->
    <template v-else>
      <div class="ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-16">
        <!-- Header with Back Button and Reset -->
        <div
          class="ivyforms-form-styles__header ivyforms-pb-12 ivyforms-border-bottom ivyforms-flex ivyforms-pb-8 ivyforms-align-items-center ivyforms-gap-16 ivyforms-align-self-stretch"
        >
          <IvyButtonAction
            size="s"
            type="ghost"
            priority="tertiary"
            icon-start="arrow-left"
            icon-start-category="arrows"
            @click="isCustomizing = false"
          />
          <div class="regular-16">
            {{ selectedThemeName }}
          </div>
          <div class="ivyforms-flex-1"></div>
          <IvyButtonAction
            size="s"
            priority="danger"
            type="ghost"
            icon-start="refresh"
            icon-start-category="arrows"
            @click="showResetDialog = true"
          >
            {{ getLabel('reset') }}
          </IvyButtonAction>
        </div>

        <!-- Style Mode Toggles -->
        <div class="ivyforms-form-styles__mode-tabs ivyforms-mt-16 ivyforms-width-100">
          <IvyTabs
            v-model="styleMode"
            size="s"
            priority="tertiary"
            type="tonal"
            background
            :tabs="[
              { name: 'quick', label: getLabel('quick_start') },
              { name: 'advanced', label: getLabel('advanced') },
            ]"
          />
        </div>

        <!-- Quick Start subtitle -->
        <div v-if="styleMode === 'quick'" class="" style="text-align: center">
          <div class="ivyforms-text-secondary ivyforms-text-sm text-muted">
            {{ getLabel('quick_start_description') }}
          </div>
        </div>

        <!-- Advanced subtitle -->
        <div v-if="styleMode === 'advanced'" class="" style="text-align: center">
          <div class="ivyforms-text-secondary ivyforms-text-sm text-muted">
            {{ getLabel('advanced_mode_description') }}
          </div>
        </div>

        <!-- Quick Mode Controls -->
        <template v-if="styleMode === 'quick'">
          <QuickModeStyleControls />
        </template>

        <!-- Advanced Mode Controls -->
        <template v-if="styleMode === 'advanced'">
          <AdvancedModeStyleControls />
        </template>
      </div>
    </template>

    <!-- Reset Confirmation Dialog -->
    <IvyDialog
      v-model="showResetDialog"
      :title="getLabel('reset_styles_confirmation_title')"
      priority="danger"
      width="364px"
    >
      <div>{{ getLabel('reset_styles_confirmation_message') }}</div>

      <template #footer>
        <div class="ivyforms-flex ivyforms-justify-content-end ivyforms-gap-8">
          <IvyButtonAction
            size="d"
            priority="tertiary"
            type="ghost"
            @click="showResetDialog = false"
          >
            {{ getLabel('cancel') }}
          </IvyButtonAction>
          <IvyButtonAction size="d" priority="danger" type="fill" @click="handleResetToDefault">
            {{ getLabel('reset') }}
          </IvyButtonAction>
        </div>
      </template>
    </IvyDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useLabels } from '@/composables/useLabels'
import { useFormBuilder } from '@/stores/useFormBuilder'
import { AVAILABLE_THEMES } from '@/constants/defaultFormStyles'
import { useContextMenuStore } from '@/stores/contextMenuStore'
import {
  ContextMenuActionType,
  createContextMenuAction,
} from '@/views/_components/context-menu/kit/ContextMenuActionType'
import QuickModeStyleControls from './style-controls/QuickModeStyleControls.vue'
import AdvancedModeStyleControls from './style-controls/AdvancedModeStyleControls.vue'

const { getLabel } = useLabels()
const formBuilderStore = useFormBuilder()
const contextMenuStore = useContextMenuStore()

const showResetDialog = ref(false)
const isCustomizing = ref(false)
const availableThemes = ref(AVAILABLE_THEMES)

// Computed properties
const stylesDisabled = computed({
  get: () => !formBuilderStore.styleSettings.stylesEnabled,
  set: (value) => {
    formBuilderStore.updateStyleSettings('stylesEnabled', !value)
  },
})

const styleMode = computed({
  get: () => formBuilderStore.styleSettings.styleMode || 'quick',
  set: (value) => {
    formBuilderStore.updateStyleSettings('styleMode', value)
  },
})

const selectedThemeId = computed({
  get: () => formBuilderStore.styleSettings.selectedTheme || 'ivy-default',
  set: (value) => {
    formBuilderStore.updateStyleSettings('selectedTheme', value)
  },
})

const selectedThemeName = computed(() => {
  const theme = availableThemes.value.find((t) => t.id === selectedThemeId.value)
  return theme ? theme.name : ''
})

const handleThemeClick = (themeId: string) => {
  const theme = availableThemes.value.find((t) => t.id === themeId)
  // Only apply theme settings if switching to a different theme
  const isNewTheme = selectedThemeId.value !== themeId

  if (theme && !theme.isPro && !theme.isComingSoon) {
    selectedThemeId.value = themeId

    // Only apply theme settings if switching to a different theme
    if (isNewTheme) {
      // Apply all theme settings including both quickMode and advancedMode for proper sync
      Object.keys(theme.settings).forEach((key) => {
        if (key !== 'stylesEnabled' && key !== 'selectedTheme' && key !== 'styleMode') {
          formBuilderStore.updateStyleSettings(key, theme.settings[key])
        }
      })
    }
  }
}

const startCustomization = (themeId: string) => {
  handleThemeClick(themeId)
  formBuilderStore.updateStyleSettings('styleMode', 'quick')
  isCustomizing.value = true
}

const handleThemeMenuClick = (themeId: string, buttonRef?: HTMLElement) => {
  const theme = availableThemes.value.find((t) => t.id === themeId)
  if (!theme || theme.isPro || theme.isComingSoon) {
    return
  }
  contextMenuStore.openContextMenu({
    actions: [
      createContextMenuAction(ContextMenuActionType.Edit, {
        handler: () => startCustomization(themeId),
      }),
    ],
    contextMenuButtonRef: buttonRef,
  })
}

const handleResetToDefault = () => {
  // Find the original theme definition and reset to its defaults
  const currentTheme = availableThemes.value.find((t) => t.id === selectedThemeId.value)

  if (currentTheme) {
    // Deep clone to avoid mutations
    const defaultSettings = JSON.parse(JSON.stringify(currentTheme.settings))

    // Reset all settings to theme defaults
    Object.entries(defaultSettings).forEach(([key, value]) => {
      if (key !== 'stylesEnabled' && key !== 'selectedTheme') {
        formBuilderStore.updateStyleSettings(key, value)
      }
    })

    // Force reactivity update
    formBuilderStore.$patch({
      styleSettings: {
        ...formBuilderStore.styleSettings,
        ...defaultSettings,
        quickMode: defaultSettings.quickMode,
        selectedTheme: selectedThemeId.value,
      },
    })
  }

  showResetDialog.value = false
}
</script>

<style scoped lang="scss">
.ivyforms-form-styles {
  &__disable-label {
    font-weight: 400;
    font-size: 16px;
    line-height: 22px;
    color: var(--map-base-text-0);
  }

  &__header {
    color: var(--map-base-text-0);
  }

  &__section {
    &-title {
      font-weight: 400;
      font-size: 16px;
      line-height: 22px;
      color: var(--map-base-text-0);
      border-color: var(--map-base-dusk-stroke--2);
    }
  }
}

.ivyforms-border-bottom {
  border-bottom: 1px solid var(--map-divider);
}
</style>
