<template>
  <div
    class="ivyforms-sample-form-preview ivyforms-flex ivyforms-flex-1 ivyforms-gap-8 ivyforms-flex-direction-column"
  >
    <PageSection>
      <IvyScrollbar modifier="outside-vertical">
        <div :class="outerWrapperClasses">
          <div :class="sampleInnerClasses" :style="wrapperAlignmentStyle">
            <h2 class="ivyforms-sample-form-preview__title ivyforms-form-title">
              {{ getLabel('form_title', 'Form title') }}
            </h2>

            <p class="ivyforms-sample-form-preview__description ivyforms-form-description">
              {{ getLabel('sample_form_description', 'Form description') }}
            </p>

            <div class="ivyforms-sample-form-preview__form-body" inert>
              <IvyForm
                :model="formModel"
                :class="[
                  'ivyforms-sample-form-preview__form',
                  'ivyforms-form',
                  `ivyforms-form-${sampleFormId}`,
                  'ivyforms-flex',
                  'ivyforms-flex-direction-column',
                  'ivyforms-gap-8',
                ]"
              >
                <template v-for="field in sampleFields" :key="field.fieldIndex">
                  <div
                    class="ivyforms-sample-preview-field-wrapper"
                    :class="fieldWrapperClass(field.fieldIndex)"
                  >
                    <component
                      :is="getPreviewFieldComponent(field.type)"
                      :model-value="getFieldValue(field) as never"
                      :field="field"
                      :error="getFieldError(field)"
                      :disabled="false"
                    />
                  </div>

                  <!-- Static open dropdown (styled like select popper) after multi-select -->
                  <div
                    v-if="field.fieldIndex === 5"
                    class="ivyforms-field ivyforms-field__select ivyforms-sample-preview-open-dropdown"
                  >
                    <IvyFormItem
                      :label="getLabel('sample_dropdown_open_label', 'Dropdown (open panel)')"
                    >
                      <div class="ivyforms-sample-open-dropdown">
                        <IvySelectInput
                          :model-value="''"
                          disabled
                          :placeholder="getLabel('sample_select_placeholder', 'Select an option')"
                          :aria-label="
                            getLabel('sample_dropdown_open_label', 'Dropdown (open panel)')
                          "
                        />
                        <div
                          class="ivyforms-sample-preview-popper-shell el-popper is-light ivyforms-select-popper ivyforms-form-popper-sample-preview ivyforms-sample-open-dropdown__panel"
                          role="presentation"
                        >
                          <span class="el-popper__arrow" data-popper-arrow />
                          <div class="el-select-dropdown">
                            <div class="el-select-dropdown__wrap">
                              <ul class="el-select-dropdown__list">
                                <li
                                  class="el-select-dropdown__item ivyforms-select-option is-hovering"
                                  role="option"
                                >
                                  {{ getLabel('sample_option_1', 'Option 1') }}
                                </li>
                                <li
                                  class="el-select-dropdown__item ivyforms-select-option is-selected"
                                  role="option"
                                >
                                  {{ getLabel('sample_option_2', 'Option 2') }}
                                </li>
                                <li
                                  class="el-select-dropdown__item ivyforms-select-option"
                                  role="option"
                                >
                                  {{ getLabel('sample_option_3', 'Option 3') }}
                                </li>
                              </ul>
                            </div>
                          </div>
                        </div>
                      </div>
                    </IvyFormItem>
                  </div>

                  <!-- Opened date picker panel (static, below the date field) -->
                  <div
                    v-if="field.fieldIndex === 6"
                    class="ivyforms-sample-preview-open-datetime ivyforms-mt-8"
                  >
                    <div
                      class="ivyforms-sample-preview-popper-shell ivyforms-sample-preview-popper-shell--fit el-popper is-light ivyforms-date-picker-popper ivyforms-form-popper-sample-preview ivyforms-sample-preview-open-date"
                      role="presentation"
                    >
                      <span class="el-popper__arrow" data-popper-arrow />
                      <div class="el-picker-panel el-date-picker">
                        <div class="el-date-picker__header">
                          <span class="el-date-picker__header-label">June 2025</span>
                        </div>
                        <div class="el-date-picker__body">
                          <table class="el-date-table" role="grid">
                            <tbody>
                              <tr>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">1</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">2</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">3</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">4</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">5</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">6</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">7</span>
                                  </div>
                                </td>
                              </tr>
                              <tr>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">8</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">9</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">10</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">11</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">12</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">13</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">14</span>
                                  </div>
                                </td>
                              </tr>
                              <tr>
                                <td class="available current">
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">15</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">16</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">17</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">18</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">19</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">20</span>
                                  </div>
                                </td>
                                <td>
                                  <div class="el-date-table-cell">
                                    <span class="el-date-table-cell__text">21</span>
                                  </div>
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Opened time picker panel (static, below the time field) -->
                  <div
                    v-if="field.fieldIndex === 7"
                    class="ivyforms-sample-preview-open-datetime ivyforms-mt-8"
                  >
                    <div
                      class="ivyforms-sample-preview-popper-shell ivyforms-sample-preview-popper-shell--fit el-popper is-light ivyforms-time-popper ivyforms-form-popper-sample-preview ivyforms-time-popper--level-2-foreground ivyforms-sample-preview-open-time"
                      role="presentation"
                    >
                      <span class="el-popper__arrow" data-popper-arrow />
                      <div class="el-time-panel">
                        <div class="el-time-spinner">
                          <div class="el-time-spinner__wrapper">
                            <ul class="el-time-spinner__list">
                              <li class="el-time-spinner__item">13</li>
                              <li class="el-time-spinner__item active">14</li>
                              <li class="el-time-spinner__item">15</li>
                            </ul>
                            <ul class="el-time-spinner__list">
                              <li class="el-time-spinner__item">29</li>
                              <li class="el-time-spinner__item active">30</li>
                              <li class="el-time-spinner__item">31</li>
                            </ul>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>

                <div
                  class="ivyforms-sample-form-preview__submit ivyforms-form-submit ivyforms-form-submit--default"
                >
                  <IvyButtonAction priority="tertiary" type="border">
                    {{ getLabel('submit', 'Submit') }}
                  </IvyButtonAction>
                </div>

                <div
                  class="ivyforms-sample-form-preview__success-message ivyforms-confirmation-message"
                >
                  {{ getLabel('sample_success_message', 'Success message preview') }}
                </div>
              </IvyForm>
            </div>
          </div>
        </div>
      </IvyScrollbar>

      <IvyButtonAction
        class="ivyforms-sample-form-preview__back-btn"
        priority="tertiary"
        type="ghost"
        icon-start="arrow-left"
        icon-start-category="arrows"
        @click="handleBackClick"
      >
        {{ getLabel('back_to_form', 'Back to form') }}
      </IvyButtonAction>
    </PageSection>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, provide, watch, ref, type CSSProperties } from 'vue'
import type { Component } from 'vue'
import type { Field } from '@/types/field'
import type { FormStyleSettings } from '@/types/form-style'
import { useFormBuilder } from '@/stores/useFormBuilder'
import { useContextMenuStore } from '@/stores/contextMenuStore'
import PageSection from '@/views/admin/parts/PageSection.vue'
import IvyScrollbar from '@/views/_components/scrollbar/IvyScrollbar.vue'
import IvyForm from '@/views/_components/form/IvyForm.vue'
import IvyFormItem from '@/views/_components/form/IvyFormItem.vue'
import IvySelectInput from '@/views/_components/input/IvySelectInput.vue'
import IvyButtonAction from '@/views/_components/button/IvyButtonAction.vue'
import TextFormField from '@/views/public/fields/TextFormField.vue'
import SelectFormField from '@/views/public/fields/SelectFormField.vue'
import DateFormField from '@/views/public/fields/DateFormField.vue'
import TimeFormField from '@/views/public/fields/TimeFormField.vue'
import RatingFormField from '@/views/public/fields/RatingFormField.vue'
import RadioFormField from '@/views/public/fields/RadioFormField.vue'
import CheckboxFormField from '@/views/public/fields/CheckboxFormField.vue'
import { generateFormCSS, injectFormCSS, parseCssClassList } from '@/utils/formStyleGenerator'
import { useLabels } from '@/composables/useLabels.ts'
import { buildFormPopperScopeClass } from '@/utils/form-styles/selectors'
import { resolveBorderStyle } from '@/utils/styleUtils'
import api from '@/composables/IvyFormAPI'

const SAMPLE_FORM_ID = 'sample-preview'

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

const sampleFormId = SAMPLE_FORM_ID
const formModel = ref<Record<string, unknown>>({})

const formPopperScopeClass = computed(() => buildFormPopperScopeClass(sampleFormId))
provide('formPopperScopeClass', formPopperScopeClass)
provide('clearFieldError', () => {})

const sampleSelectOptions = [
  { id: 1, label: 'Option 1', value: '1', position: 0 },
  { id: 2, label: 'Option 2', value: '2', position: 1 },
  { id: 3, label: 'Option 3', value: '3', position: 2 },
]

const sampleRadioOptions = [
  { id: 1, label: 'Option 1', value: 'radio_opt1', position: 0 },
  { id: 2, label: 'Option 2', value: 'radio_opt2', position: 1 },
]

const sampleCheckboxOptions = [
  { id: 1, label: 'Choice 1', value: 'cb_opt1', position: 0 },
  { id: 2, label: 'Choice 2', value: 'cb_opt2', position: 1 },
]

const sampleRatingOptions = Array.from({ length: 5 }, (_, i) => ({
  id: i + 1,
  label: String(i + 1),
  value: String(i + 1),
  position: i,
}))

function buildSampleField(
  partial: Partial<Field> & Pick<Field, 'type' | 'fieldIndex' | 'label'>,
): Field {
  return {
    id: partial.fieldIndex + 1,
    formId: 0,
    fieldIndex: partial.fieldIndex,
    label: partial.label,
    type: partial.type,
    defaultValue: partial.defaultValue ?? '',
    required: partial.required ?? false,
    placeholder: partial.placeholder ?? '',
    fieldOptions: partial.fieldOptions ?? [],
    labelPosition: partial.labelPosition ?? 'top',
    ...partial,
  } as Field
}

const sampleFields = computed<Field[]>(() => [
  buildSampleField({
    type: 'text',
    fieldIndex: 0,
    label: getLabel('sample_text_field', 'Text (default)'),
    description: getLabel('sample_field_description', 'Field description'),
    placeholder: getLabel('sample_text_input_placeholder', 'Placeholder'),
    required: true,
  }),
  buildSampleField({
    type: 'text',
    fieldIndex: 1,
    label: getLabel('sample_active_field', 'Text (active)'),
    placeholder: getLabel('sample_active_state', 'Active state'),
  }),
  buildSampleField({
    type: 'text',
    fieldIndex: 2,
    label: getLabel('sample_error_field', 'Text (error)'),
    placeholder: getLabel('sample_error_state', 'Error state'),
  }),
  buildSampleField({
    type: 'select',
    fieldIndex: 3,
    label: getLabel('sample_dropdown_label', 'Dropdown (empty)'),
    placeholder: getLabel('sample_select_placeholder', 'Select an option'),
    fieldOptions: sampleSelectOptions,
  }),
  buildSampleField({
    type: 'select',
    fieldIndex: 4,
    label: getLabel('sample_dropdown_selected_label', 'Dropdown (selected)'),
    placeholder: getLabel('sample_select_placeholder', 'Select an option'),
    fieldOptions: sampleSelectOptions,
  }),
  buildSampleField({
    type: 'multi-select',
    fieldIndex: 5,
    label: getLabel('sample_multiselect_label', 'Multi-select'),
    placeholder: getLabel('sample_select_placeholder', 'Choose one or more'),
    fieldOptions: sampleSelectOptions,
  }),
  buildSampleField({
    type: 'date',
    fieldIndex: 6,
    label: getLabel('sample_date_field', 'Date'),
    dateFieldType: 'picker',
    dateFormat: 'MM/DD/YYYY',
    placeholder: getLabel('sample_date_placeholder', 'Select date'),
  }),
  buildSampleField({
    type: 'time',
    fieldIndex: 7,
    label: getLabel('sample_time_field', 'Time'),
    timeFieldType: 'time-picker',
    timeFormat: '24h',
    placeholder: getLabel('sample_time_placeholder', 'Select time'),
    defaultValue: '14:30',
  }),
  buildSampleField({
    type: 'rating',
    fieldIndex: 8,
    label: getLabel('sample_rating_field', 'Rating'),
    ratingIcon: 'star',
    showRatingText: false,
    fieldOptions: sampleRatingOptions,
  }),
  buildSampleField({
    type: 'radio',
    fieldIndex: 9,
    label: getLabel('sample_radio_group', 'Radio buttons'),
    fieldOptions: sampleRadioOptions,
  }),
  buildSampleField({
    type: 'checkbox',
    fieldIndex: 10,
    label: getLabel('sample_checkbox_group', 'Checkboxes'),
    fieldOptions: sampleCheckboxOptions,
  }),
  buildSampleField({
    type: 'text',
    fieldIndex: 11,
    label: getLabel('sample_readonly_field', 'Read-only'),
    readOnly: true,
    placeholder: '',
  }),
])

const fieldValues = ref<Record<string, unknown>>({
  text_0: getLabel('sample_text_value', 'Sample text'),
  text_1: getLabel('sample_active_value', 'Active field state'),
  text_2: '',
  select_3: '',
  select_4: '2',
  'multi-select_5': ['1', '3'],
  date_6: '2025-06-15',
  time_7: '14:30',
  rating_8: 4,
  radio_9: 'radio_opt1',
  checkbox_10: ['cb_opt1'],
  text_11: getLabel('sample_readonly_value', 'Read-only value'),
})

const getFieldKey = (field: Field) => `${field.type}_${field.fieldIndex}`

const getFieldValue = (field: Field) => {
  const key = getFieldKey(field)
  if (fieldValues.value[key] !== undefined) {
    return fieldValues.value[key]
  }
  return field.defaultValue ?? ''
}

const getFieldError = (field: Field) => {
  if (field.fieldIndex === 2) {
    return getLabel('sample_error_message', 'This field has an error')
  }
  return ''
}

const fieldWrapperClass = (fieldIndex: number) => {
  if (fieldIndex === 1) {
    return 'ivyforms-sample-preview-field--active'
  }
  return ''
}

const styleSettings = computed(() => formBuilderStore.styleSettings)
const parsedCustomClasses = computed(() =>
  parseCssClassList(styleSettings.value?.customCssClass || ''),
)
const parsedAdditionalClasses = computed(() =>
  parseCssClassList(styleSettings.value?.additionalCssClasses || ''),
)

const outerWrapperClasses = computed(() => [
  'ivyforms-sample-form-preview__outer',
  `ivyforms-form-wrapper-${sampleFormId}`,
  `ivyforms-form-${sampleFormId}`,
  ...parsedCustomClasses.value,
  ...parsedAdditionalClasses.value,
])

const sampleInnerClasses = computed(() => [
  'ivyforms-sample-form-preview__wrapper',
  'ivyforms-form-wrapper',
  `ivyforms-form-wrapper-${sampleFormId}`,
])

const baseSelector = computed(() => {
  const wrapperSelector = `.ivyforms-form-wrapper-${sampleFormId}`
  const customClassValue = parsedCustomClasses.value[0]
  if (customClassValue) {
    return `${wrapperSelector}.${customClassValue}`
  }
  return wrapperSelector
})

const labelColor = computed(() => {
  const quickMode = styleSettings.value?.quickMode
  const advancedMode = styleSettings.value?.advancedMode
  return advancedMode?.fieldLabels?.label?.fontColor || quickMode?.labelFontColor || ''
})

const buttonTextColor = computed(() => {
  const quickMode = styleSettings.value?.quickMode
  const advancedMode = styleSettings.value?.advancedMode
  return advancedMode?.buttonStates?.normal?.textColor || quickMode?.buttonText || ''
})

const requiredIndicatorColor = computed(
  () => styleSettings.value?.advancedMode?.fieldLabels?.requiredIndicator?.fontColor || '#E53E3E',
)

const wrapperAlignmentStyle = computed<CSSProperties>(() => {
  const alignment = formBuilderStore.styleSettings?.advancedMode?.general?.alignment
  if (alignment === 'center') {
    return {
      display: 'flex',
      flexDirection: 'column' as const,
      alignItems: 'center' as const,
    }
  }
  if (alignment === 'right') {
    return {
      display: 'flex',
      flexDirection: 'column' as const,
      alignItems: 'flex-end' as const,
    }
  }
  return {}
})

function buildSamplePreviewActiveStateCSS(
  selector: string,
  settings: FormStyleSettings,
  fieldBorderWidth: string,
): string {
  const scope = `${selector} .ivyforms-sample-preview-field--active`
  const activeStateBackground = settings.advancedMode?.fieldStates?.active?.background
  const activeStateBorderColor = settings.advancedMode?.fieldStates?.active?.borderColor
  const activeStateTextColor = settings.advancedMode?.fieldStates?.active?.textColor
  const activeStateDescriptionColor = settings.advancedMode?.fieldStates?.active?.descriptionColor
  const hasActiveBorderStyle = settings.advancedMode?.fieldStates?.active?.borderStyle != null
  const activeStateBorderStyle = hasActiveBorderStyle
    ? resolveBorderStyle(settings.advancedMode?.fieldStates?.active?.borderStyle)
    : undefined

  const css: string[] = []

  if (activeStateBackground || activeStateBorderColor || hasActiveBorderStyle) {
    const activeBorderSelectors = [
      `${scope} .ivyforms-input.el-input .el-input__wrapper`,
      `${scope} .ivyforms-field__text .el-input__wrapper`,
      `${scope} .ivyforms-field__email .el-input__wrapper`,
      `${scope} .ivyforms-field__website .el-input__wrapper`,
      `${scope} .ivyforms-field__textarea .el-textarea__inner`,
      `${scope} .ivyforms-phone-input .el-input__wrapper`,
      `${scope} .ivyforms-field__phone .vue-tel-input`,
      `${scope} .ivyforms-field__select .el-input__wrapper`,
      `${scope} .ivyforms-field__select .el-select__wrapper`,
      `${scope} .el-select .el-select__wrapper`,
      `${scope} .ivyforms-field__date .el-input__wrapper`,
      `${scope} .ivyforms-field__time .el-input__wrapper`,
    ]
    css.push(activeBorderSelectors.join(',') + ' {')
    if (activeStateBackground) {
      css.push(`  background-color: ${activeStateBackground} !important;`)
    }
    if (activeStateBorderColor) {
      css.push(`  border-width: ${fieldBorderWidth} !important;`)
      css.push(`  border-color: ${activeStateBorderColor} !important;`)
    }
    if (hasActiveBorderStyle && activeStateBorderStyle) {
      css.push(`  border-style: ${activeStateBorderStyle} !important;`)
    }
    css.push('}')

    if (activeStateBackground) {
      css.push(`${scope} .ivyforms-field__phone .vti__input {`)
      css.push(`  background-color: ${activeStateBackground} !important;`)
      css.push('}')
    }
  }

  if (activeStateDescriptionColor) {
    css.push(`${scope} .ivyforms-form-item .ivyforms-form-item__info-text,`)
    css.push(`${scope} .el-form-item .ivyforms-form-item__info-text {`)
    css.push(`  color: ${activeStateDescriptionColor} !important;`)
    css.push(`  --ivyforms-info-color: ${activeStateDescriptionColor} !important;`)
    css.push('}')
  }

  if (activeStateTextColor) {
    const activeTextSelectors = [
      `${scope} .ivyforms-field__textarea .el-textarea__inner`,
      `${scope} .ivyforms-field__textarea textarea`,
      `${scope} .ivyforms-field__select .el-select__selected-item`,
      `${scope} .el-select .el-select__selected-item`,
      `${scope} .ivyforms-field__text .el-input__inner`,
      `${scope} .ivyforms-field__text input`,
      `${scope} .ivyforms-field__email .el-input__inner`,
      `${scope} .ivyforms-field__email input`,
      `${scope} .ivyforms-field__phone .vti__input`,
      `${scope} .ivyforms-field__phone .vue-tel-input input`,
      `${scope} .ivyforms-field__phone input.vti__input`,
      `${scope} .ivyforms-field__phone input.iti__input`,
      `${scope} .ivyforms-field__phone .vti__input.vti__phone`,
    ]
    css.push(activeTextSelectors.join(',') + ' {')
    css.push(`  color: ${activeStateTextColor} !important;`)
    css.push(`  -webkit-text-fill-color: ${activeStateTextColor} !important;`)
    css.push('}')
  }

  return css.join('\n')
}

/**
 * Static sample poppers (select / date / time) are not teleported; ensure panel chrome
 * (background, border, arrow) matches real pickers. Date/time omit heavy box-shadow like live poppers.
 */
function buildSamplePreviewPopperShellCSS(
  selector: string,
  settings: FormStyleSettings | null,
): string {
  if (!settings || settings.stylesEnabled === false) {
    return ''
  }
  const calendarBg = settings.advancedMode?.dateTimePicker?.calendarBackground
  const css: string[] = []
  const b = selector
  const selectShell = `${b} .ivyforms-sample-preview-popper-shell.ivyforms-select-popper`
  const dateShell = `${b} .ivyforms-sample-preview-popper-shell.ivyforms-date-picker-popper`
  const timeShell = `${b} .ivyforms-sample-preview-popper-shell.ivyforms-time-popper`

  css.push(`${selectShell} {`)
  css.push(`  background-color: var(--map-ground-level-2-foreground, #ffffff) !important;`)
  css.push(
    `  box-shadow: 0px 12px 32px 4px rgba(0, 0, 0, 0.04), 0px 8px 20px 0px rgba(0, 0, 0, 0.08) !important;`,
  )
  css.push(`  border-radius: 8px !important;`)
  css.push(`  border: 1px solid var(--el-border-color-lighter, #e4e7ed) !important;`)
  css.push(`}`)
  css.push(`${selectShell} .el-select-dropdown {`)
  css.push(`  background-color: transparent !important;`)
  css.push(`  border: none !important;`)
  css.push(`  box-shadow: none !important;`)
  css.push(`}`)

  css.push(`${dateShell},`)
  css.push(`${timeShell} {`)
  if (calendarBg) {
    css.push(`  background-color: ${calendarBg} !important;`)
  } else {
    css.push(`  background-color: var(--map-ground-level-2-foreground, #ffffff) !important;`)
  }
  css.push(`  box-shadow: none !important;`)
  css.push(`  border-radius: 8px !important;`)
  css.push(`  border: 1px solid var(--el-border-color-lighter, #e4e7ed) !important;`)
  css.push(`  width: fit-content !important;`)
  css.push(`  max-width: 100% !important;`)
  css.push(`}`)

  css.push(`${dateShell} .el-picker-panel,`)
  css.push(`${dateShell} .el-date-picker {`)
  css.push(`  min-width: 0 !important;`)
  css.push(`  width: auto !important;`)
  css.push(`}`)

  css.push(`${timeShell} .el-time-panel,`)
  css.push(`${timeShell} .el-time-spinner {`)
  css.push(`  overflow: visible !important;`)
  css.push(`  max-height: none !important;`)
  css.push(`}`)
  css.push(`${timeShell} .el-scrollbar__wrap {`)
  css.push(`  overflow: visible !important;`)
  css.push(`  max-height: none !important;`)
  css.push(`}`)

  css.push(`${dateShell} .el-popper__arrow::before,`)
  css.push(`${dateShell} .el-popper__arrow:before,`)
  css.push(`${timeShell} .el-popper__arrow::before,`)
  css.push(`${timeShell} .el-popper__arrow:before {`)
  if (calendarBg) {
    css.push(`  background: ${calendarBg} !important;`)
    css.push(`  background-color: ${calendarBg} !important;`)
    css.push(`  border-color: ${calendarBg} !important;`)
  } else {
    css.push(`  background: var(--map-ground-level-2-foreground, #ffffff) !important;`)
    css.push(`  border: 1px solid var(--el-border-color-lighter, #e4e7ed) !important;`)
  }
  css.push(`}`)

  css.push(`${selectShell} .el-popper__arrow::before,`)
  css.push(`${selectShell} .el-popper__arrow:before {`)
  css.push(`  background: var(--map-ground-level-2-foreground, #ffffff) !important;`)
  css.push(`  border: 1px solid var(--el-border-color-lighter, #e4e7ed) !important;`)
  css.push(`}`)

  return css.join('\n')
}

const getPreviewFieldComponent = (fieldType: string): Component => {
  let base: Component

  switch (fieldType) {
    case 'text':
      base = TextFormField
      break
    case 'select':
    case 'dropdown':
    case 'multi-select':
      base = SelectFormField
      break
    case 'date':
      base = DateFormField
      break
    case 'time':
      base = TimeFormField
      break
    case 'rating':
      base = RatingFormField
      break
    case 'radio':
      base = RadioFormField
      break
    case 'checkbox':
      base = CheckboxFormField
      break
    default:
      base = TextFormField
      break
  }

  try {
    const filtered = api.hooks.applyFilters('ivyforms/template/field/filter/component', base, {
      type: fieldType,
    }) as Component
    return filtered || base
  } catch {
    return base
  }
}

const applyStyles = () => {
  const ss = formBuilderStore.styleSettings
  let css = generateFormCSS(sampleFormId, ss)

  const extraRules: string[] = []

  if (labelColor.value) {
    extraRules.push(`
      ${baseSelector.value} .ivyforms-form-item__label,
      ${baseSelector.value} .ivyforms-form-item__label span,
      ${baseSelector.value} .el-form-item__label,
      ${baseSelector.value} .ivyforms-form-label,
      ${baseSelector.value} .ivyforms-form-label span {
        color: ${labelColor.value} !important;
      }
    `)
  }

  if (requiredIndicatorColor.value) {
    extraRules.push(`
      ${baseSelector.value} .ivyforms-form-item__asterisk,
      ${baseSelector.value} .el-form-item__label.is-required::before {
        color: ${requiredIndicatorColor.value} !important;
      }
    `)
  }

  if (buttonTextColor.value) {
    extraRules.push(`
      ${baseSelector.value} .ivyforms-form-submit .ivyforms-button-action,
      ${baseSelector.value} .ivyforms-form-submit .ivyforms-button-action span,
      ${baseSelector.value} .ivyforms-form-submit button.ivyforms-button-action {
        color: ${buttonTextColor.value} !important;
      }
    `)
  }

  if (ss && ss.stylesEnabled !== false) {
    const fieldBorderWidth =
      ss.advancedMode?.fieldStates?.default?.borderWidth || ss.quickMode?.fieldBorderWidth || '1px'
    const activeSampleCss = buildSamplePreviewActiveStateCSS(
      baseSelector.value,
      ss,
      fieldBorderWidth,
    )
    if (activeSampleCss) {
      extraRules.push(activeSampleCss)
    }
    const popperShellCss = buildSamplePreviewPopperShellCSS(baseSelector.value, ss)
    if (popperShellCss) {
      extraRules.push(popperShellCss)
    }
  }

  if (extraRules.length) {
    css = `${css}\n${extraRules.join('\n')}`
  }

  injectFormCSS(sampleFormId, css)
}

watch(
  () => formBuilderStore.styleSettings,
  () => {
    applyStyles()
  },
  { deep: true },
)

const handleBackClick = () => {
  contextMenuStore.closeContextMenu()
  formBuilderStore.showSampleView = false
}

watch(
  () => formBuilderStore.showSampleView,
  (visible) => {
    if (visible) {
      applyStyles()
    }
  },
)

onMounted(() => {
  applyStyles()
})

onBeforeUnmount(() => {
  contextMenuStore.closeContextMenu()
})
</script>

<style scoped lang="scss">
.ivyforms-sample-form-preview {
  max-width: 100%;
  overflow: hidden;
  position: relative;

  .el-scrollbar {
    max-width: 100%;
  }

  :deep(.el-scrollbar__wrap) {
    max-width: 100%;
    overflow-x: hidden;
  }

  :deep(.el-scrollbar__view) {
    max-width: 100%;
  }

  &__wrapper {
    width: 100%;
    max-width: 720px;
    margin: 0 auto;
    box-sizing: border-box;
  }

  &__form-body {
    pointer-events: none;
    user-select: none;
  }

  &__container {
    max-width: 100%;
  }

  &__back-btn {
    position: absolute;
    bottom: 24px;
    right: 24px;
    z-index: 100;
    background: var(--map-ground-level-3, white);
    box-shadow: 0px 4px 15px 0px rgba(0, 0, 0, 0.05);
    border-radius: 8px;
  }

  &__success-message {
    font-size: 20px;
  }
}

.ivyforms-sample-open-dropdown {
  width: 100%;
}

.ivyforms-sample-preview-open-datetime {
  width: fit-content;
  max-width: 100%;
}

.ivyforms-sample-preview-popper-shell {
  position: relative;
  display: block;
  margin-top: 8px;
  z-index: 1;
  box-sizing: border-box;
  overflow: visible;
}

.ivyforms-sample-open-dropdown__panel.ivyforms-sample-preview-popper-shell {
  width: 100%;
}

.ivyforms-sample-preview-popper-shell--fit {
  width: fit-content;
  max-width: 100%;
}

.ivyforms-sample-preview-popper-shell .el-popper__arrow {
  position: absolute;
  top: -6px;
  left: 50%;
  z-index: 2;
  width: 16px;
  height: 16px;
  margin-left: -8px;
  pointer-events: none;
}

.ivyforms-sample-preview-popper-shell .el-popper__arrow::before {
  display: block;
  content: '';
  width: 10px;
  height: 10px;
  transform: rotate(45deg);
  box-sizing: border-box;
}

.ivyforms-sample-preview-open-dropdown :deep(.el-select-dropdown__list) {
  list-style: none;
  margin: 0;
  padding: 0;
}

.ivyforms-sample-preview-open-date :deep(.el-picker-panel) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.ivyforms-sample-preview-open-date :deep(.el-date-picker) {
  min-width: 0 !important;
  width: auto !important;
}

.ivyforms-sample-preview-open-date :deep(.el-date-table) {
  width: max-content !important;
  max-width: 100%;
  table-layout: fixed;
}

.ivyforms-sample-preview-open-date :deep(.el-date-picker__body) {
  padding: 4px 8px 8px;
}

.ivyforms-sample-preview-open-time :deep(.el-time-panel) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  width: auto !important;
  overflow: visible !important;
}

.ivyforms-sample-preview-open-time :deep(.el-time-spinner) {
  overflow: visible !important;
  height: auto !important;
  max-height: none !important;
}

.ivyforms-sample-preview-open-time :deep(.el-time-spinner__wrapper) {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  padding: 8px 12px 12px;
  width: auto;
  overflow: visible !important;
}

.ivyforms-sample-preview-open-time :deep(.el-scrollbar) {
  overflow: visible !important;
}

.ivyforms-sample-preview-open-time :deep(.el-scrollbar__wrap) {
  overflow: visible !important;
  max-height: none !important;
}

.ivyforms-sample-preview-open-time :deep(.el-scrollbar__bar) {
  display: none !important;
}

.ivyforms-sample-preview-open-time :deep(.el-time-spinner__list) {
  list-style: none;
  margin: 0;
  padding: 0;
  min-width: 48px;
  text-align: center;
  overflow: visible !important;
  max-height: none !important;
}
</style>
