<template>
  <div class="ivyforms-quick-mode-controls ivyforms-mt-16 ivyforms-width-100">
    <div class="ivyforms-quick-mode-controls__section ivyforms-pr-8 ivyforms-pb-16">
      <!-- Form Background -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{ getLabel('form_background') }}</label>
        <div class="ivyforms-quick-mode-controls__color-input">
          <StyleColorPicker v-model="formBackground">
            <template #reference>
              <IvyTextInput v-model="formBackground" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: formBackground }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Form Border Color -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('form_border_color')
        }}</label>
        <div class="ivyforms-quick-mode-controls__color-input">
          <StyleColorPicker v-model="formBorderColor">
            <template #reference>
              <IvyTextInput v-model="formBorderColor" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: formBorderColor }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Form Border Width -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('form_border_width')
        }}</label>
        <IvyMixedInput
          v-model="formBorderWidthValue"
          v-model:unit="formBorderWidthUnit"
          secondary
          icon-prepend="size-border"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="1"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <IvyDivider class="ivyforms-mt-8 ivyforms-mb-8" />

      <!-- Vertical Spacing -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('vertical_spacing')
        }}</label>
        <IvyMixedInput
          v-model="verticalSpacingValue"
          v-model:unit="verticalSpacingUnit"
          secondary
          icon-prepend="size-height"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="16"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <!-- Horizontal Spacing -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('horizontal_spacing')
        }}</label>
        <IvyMixedInput
          v-model="horizontalSpacingValue"
          v-model:unit="horizontalSpacingUnit"
          secondary
          icon-prepend="size-width"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="0"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <!-- Form Corner -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16 ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16--corner ivyforms-align-items-start"
      >
        <label class="ivyforms-quick-mode-controls__label">{{ getLabel('form_corner') }}</label>
        <div
          class="ivyforms-quick-mode-controls__corner-inputs ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-8"
        >
          <div
            class="ivyforms-quick-mode-controls__corner-main-input ivyforms-flex ivyforms-align-items-center ivyforms-gap-8"
          >
            <IvyButtonAction
              size="s"
              type="ghost"
              :priority="isFormCornerLinked ? 'secondary' : 'tertiary'"
              :icon-start="isFormCornerLinked ? 'link' : 'link-broken'"
              icon-start-category="global"
              :icon-only="true"
              :aria-label="
                isFormCornerLinked ? getLabel('unlink_corners') : getLabel('link_corners')
              "
              @click="toggleFormCornerLinked"
            />
            <IvyMixedInput
              v-model="formCornerMainValue"
              v-model:unit="formCornerLinkedUnit"
              secondary
              icon-prepend="corner-all"
              icon-prepend-category="builder"
              :units="['px', 'rem', 'em', '%']"
              :placeholder="formCornerMainPlaceholder"
              :disabled="!isFormCornerLinked"
              class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
            />
          </div>
        </div>
      </div>
      <div
        v-if="!isFormCornerLinked"
        class="ivyforms-quick-mode-controls__corner-grid ivyforms-gap-12 ivyforms-pb-8"
      >
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="formCornerTopLeftValue"
            v-model:unit="formCornerTopLeftUnit"
            secondary
            icon-prepend="corner-top-left"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="8"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="formCornerTopRightValue"
            v-model:unit="formCornerTopRightUnit"
            secondary
            icon-prepend="corner-top-right"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="8"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="formCornerBottomLeftValue"
            v-model:unit="formCornerBottomLeftUnit"
            secondary
            icon-prepend="corner-bottom-left"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="8"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="formCornerBottomRightValue"
            v-model:unit="formCornerBottomRightUnit"
            secondary
            icon-prepend="corner-bottom-right"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="8"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
      </div>

      <!-- Form Title Text -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{ getLabel('form_title_text') }}</label>
        <div class="ivyforms-quick-mode-controls__color-input">
          <StyleColorPicker v-model="formTitleText">
            <template #reference>
              <IvyTextInput v-model="formTitleText" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div class="ivyforms-color-preview" :style="{ backgroundColor: formTitleText }" />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <IvyDivider class="ivyforms-mt-8 ivyforms-mb-8" />

      <!-- Field Background -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('field_background')
        }}</label>
        <div class="ivyforms-quick-mode-controls__color-input">
          <StyleColorPicker v-model="fieldBackground">
            <template #reference>
              <IvyTextInput v-model="fieldBackground" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: fieldBackground }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Field Text -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{ getLabel('field_text') }}</label>
        <div class="ivyforms-quick-mode-controls__color-input">
          <StyleColorPicker v-model="fieldText">
            <template #reference>
              <IvyTextInput v-model="fieldText" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div class="ivyforms-color-preview" :style="{ backgroundColor: fieldText }" />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Field Border Color -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('field_border_color')
        }}</label>
        <div class="ivyforms-quick-mode-controls__color-input">
          <StyleColorPicker v-model="fieldBorderColor">
            <template #reference>
              <IvyTextInput v-model="fieldBorderColor" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: fieldBorderColor }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Field Corner -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16 ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16--corner ivyforms-align-items-start"
      >
        <label class="ivyforms-quick-mode-controls__label">{{ getLabel('field_corner') }}</label>
        <div class="ivyforms-quick-mode-controls__corner-inputs">
          <div
            class="ivyforms-quick-mode-controls__corner-main-input ivyforms-flex ivyforms-align-items-center ivyforms-gap-8"
          >
            <IvyButtonAction
              size="s"
              type="ghost"
              :priority="isFieldCornerLinked ? 'secondary' : 'tertiary'"
              :icon-start="isFieldCornerLinked ? 'link' : 'link-broken'"
              icon-start-category="global"
              :icon-only="true"
              :aria-label="
                isFieldCornerLinked ? getLabel('unlink_corners') : getLabel('link_corners')
              "
              @click="toggleFieldCornerLinked"
            />
            <IvyMixedInput
              v-model="fieldCornerMainValue"
              v-model:unit="fieldCornerLinkedUnit"
              secondary
              icon-prepend="corner-all"
              icon-prepend-category="builder"
              :units="['px', 'rem', 'em', '%']"
              :placeholder="fieldCornerMainPlaceholder"
              :disabled="!isFieldCornerLinked"
              class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
            />
          </div>
        </div>
      </div>
      <div
        v-if="!isFieldCornerLinked"
        class="ivyforms-quick-mode-controls__corner-grid ivyforms-gap-12 ivyforms-pb-8"
      >
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="fieldCornerTopLeftValue"
            v-model:unit="fieldCornerTopLeftUnit"
            secondary
            icon-prepend="corner-top-left"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="6"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="fieldCornerTopRightValue"
            v-model:unit="fieldCornerTopRightUnit"
            secondary
            icon-prepend="corner-top-right"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="6"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="fieldCornerBottomLeftValue"
            v-model:unit="fieldCornerBottomLeftUnit"
            secondary
            icon-prepend="corner-bottom-left"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="6"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
        <div
          class="ivyforms-quick-mode-controls__corner-grid-item ivyforms-width-100 ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-6"
        >
          <IvyMixedInput
            v-model="fieldCornerBottomRightValue"
            v-model:unit="fieldCornerBottomRightUnit"
            secondary
            icon-prepend="corner-bottom-right"
            icon-prepend-category="builder"
            :units="['px', 'rem', 'em', '%']"
            placeholder="6"
            class="ivyforms-quick-mode-controls__input ivyforms-quick-mode-controls__input--full"
          />
        </div>
      </div>

      <!-- Field Border Width -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('field_border_width')
        }}</label>
        <IvyMixedInput
          v-model="fieldBorderWidthValue"
          v-model:unit="fieldBorderWidthUnit"
          secondary
          icon-prepend="size-border"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="1"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <!-- Field Padding Left/Right -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('field_padding_left_right')
        }}</label>
        <IvyMixedInput
          v-model="fieldPaddingLeftRightValue"
          v-model:unit="fieldPaddingLeftRightUnit"
          secondary
          icon-prepend="margin-left-right"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="12"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <!-- Field Padding Top/Bottom -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('field_padding_top_bottom')
        }}</label>
        <IvyMixedInput
          v-model="fieldPaddingTopBottomValue"
          v-model:unit="fieldPaddingTopBottomUnit"
          secondary
          icon-prepend="margin-top-bottom"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="8"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <!-- Label Font Color -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('label_font_color')
        }}</label>
        <div class="ivyforms-color-input-wrapper">
          <StyleColorPicker v-model="labelFontColor">
            <template #reference>
              <IvyTextInput v-model="labelFontColor" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: labelFontColor }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <IvyDivider class="ivyforms-mt-8 ivyforms-mb-8" />

      <!-- Button Background -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('button_background')
        }}</label>
        <div class="ivyforms-color-input-wrapper">
          <StyleColorPicker v-model="buttonBackground">
            <template #reference>
              <IvyTextInput v-model="buttonBackground" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: buttonBackground }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Button Border Color -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('button_border_color')
        }}</label>
        <div class="ivyforms-color-input-wrapper">
          <StyleColorPicker v-model="buttonBorderColor">
            <template #reference>
              <IvyTextInput v-model="buttonBorderColor" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div
                    class="ivyforms-color-preview"
                    :style="{ backgroundColor: buttonBorderColor }"
                  />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>

      <!-- Button Border Width -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{
          getLabel('button_border_width')
        }}</label>
        <IvyMixedInput
          v-model:unit="buttonBorderWidthUnit"
          v-model="buttonBorderWidthValue"
          secondary
          icon-prepend="size-border"
          icon-prepend-category="builder"
          :units="['px', 'rem', 'em']"
          placeholder="1"
          class="ivyforms-quick-mode-controls__input"
        />
      </div>

      <!-- Button Text -->
      <div
        class="ivyforms-quick-mode-controls__field ivyforms-flex ivyforms-align-items-center ivyforms-gap-16 ivyforms-justify-content-between ivyforms-mb-16"
      >
        <label class="ivyforms-quick-mode-controls__label">{{ getLabel('button_text') }}</label>
        <div class="ivyforms-color-input-wrapper">
          <StyleColorPicker v-model="buttonText">
            <template #reference>
              <IvyTextInput v-model="buttonText" secondary class="ivyforms-color-text-input">
                <template #suffix>
                  <div class="ivyforms-color-preview" :style="{ backgroundColor: buttonText }" />
                </template>
              </IvyTextInput>
            </template>
          </StyleColorPicker>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { useFormBuilder } from '@/stores/useFormBuilder'
import { useLabels } from '@/composables/useLabels'
import { DEFAULT_FORM_STYLES } from '@/constants/defaultFormStyles'
import {
  parseDimension,
  parseDimensionToNumeric,
  parseCornerNumericValue,
  resolveSyncStringValue,
  parseSyncNumericDimension,
  resolveCornerDefaultValue,
  resolveCornerLinkedState,
  buildDimensionString,
  applyCornerSettings,
  buildCornerSettings,
  toggleCornerLinked,
  createDimensionWatcher,
} from '@/utils/styleUtils'
import {
  registerCallbackStyleWatchers,
  registerCallbackDimensionWatchers,
  registerDeferredWatchGroup,
} from '@/composables/useStyleWatcherRegistries.ts'
import IvyTextInput from '@/views/_components/input/IvyTextInput.vue'
import IvyMixedInput from '@/views/_components/input/IvyMixedInput.vue'
import IvyButtonAction from '@/views/_components/button/IvyButtonAction.vue'
import StyleColorPicker from './StyleColorPicker.vue'
import IvyDivider from '@/views/_components/divider/IvyDivider.vue'

const { getLabel } = useLabels()
const formBuilderStore = useFormBuilder()
const isSyncingFromStore = ref(false)

// Get defaults from theme
const defaults = DEFAULT_FORM_STYLES.quickMode

// Initialize refs with values from theme defaults
const formBorderWidthDefault = parseDimensionToNumeric(defaults.formBorderWidth as string, 1)
const formCornerDefault = parseDimension(resolveCornerDefaultValue(defaults.formCorner))
const fieldBorderWidthDefault = parseDimensionToNumeric(defaults.fieldBorderWidth as string, 1)
const fieldCornerDefault = parseDimension(resolveCornerDefaultValue(defaults.fieldCorner))
const fieldPaddingLRDefault = parseDimensionToNumeric(defaults.fieldPaddingLeftRight as string, 4)
const fieldPaddingTBDefault = parseDimensionToNumeric(defaults.fieldPaddingTopBottom as string, 0)
const buttonBorderWidthDefault = parseDimensionToNumeric(defaults.buttonBorderWidth as string, 1)
const verticalSpacingDefault = parseDimensionToNumeric(defaults.verticalSpacing as string, 16)
const horizontalSpacingDefault = parseDimensionToNumeric(defaults.horizontalSpacing as string, 0)

const formBackground = ref(defaults.formBackground as string)
const formBorderColor = ref(defaults.formBorderColor as string)
const formBorderWidthValue = ref(formBorderWidthDefault.value)
const formBorderWidthUnit = ref(formBorderWidthDefault.unit)
const verticalSpacingValue = ref(verticalSpacingDefault.value)
const verticalSpacingUnit = ref(verticalSpacingDefault.unit)
const horizontalSpacingValue = ref(horizontalSpacingDefault.value)
const horizontalSpacingUnit = ref(horizontalSpacingDefault.unit)
const isFormCornerLinked = ref(resolveCornerLinkedState(defaults.formCorner))
const formCornerInitialValue = parseCornerNumericValue(formCornerDefault)
const formCornerLinkedValue = ref(formCornerInitialValue)
const formCornerLinkedUnit = ref(formCornerDefault.unit)
const formCornerTopLeftValue = ref(formCornerInitialValue)
const formCornerTopLeftUnit = ref(formCornerDefault.unit)
const formCornerTopRightValue = ref(formCornerInitialValue)
const formCornerTopRightUnit = ref(formCornerDefault.unit)
const formCornerBottomRightValue = ref(formCornerInitialValue)
const formCornerBottomRightUnit = ref(formCornerDefault.unit)
const formCornerBottomLeftValue = ref(formCornerInitialValue)
const formCornerBottomLeftUnit = ref(formCornerDefault.unit)
const formTitleText = ref(defaults.formTitleText as string)
const fieldBackground = ref(defaults.fieldBackground as string)
const fieldText = ref(defaults.fieldText as string)
const fieldBorderColor = ref(defaults.fieldBorderColor as string)
const isFieldCornerLinked = ref(resolveCornerLinkedState(defaults.fieldCorner))
const fieldCornerInitialValue = parseCornerNumericValue(fieldCornerDefault)
const fieldCornerLinkedValue = ref(fieldCornerInitialValue)
const fieldCornerLinkedUnit = ref(fieldCornerDefault.unit)
const fieldCornerTopLeftValue = ref(fieldCornerInitialValue)
const fieldCornerTopLeftUnit = ref(fieldCornerDefault.unit)
const fieldCornerTopRightValue = ref(fieldCornerInitialValue)
const fieldCornerTopRightUnit = ref(fieldCornerDefault.unit)
const fieldCornerBottomRightValue = ref(fieldCornerInitialValue)
const fieldCornerBottomRightUnit = ref(fieldCornerDefault.unit)
const fieldCornerBottomLeftValue = ref(fieldCornerInitialValue)
const fieldCornerBottomLeftUnit = ref(fieldCornerDefault.unit)
const fieldBorderWidthValue = ref(fieldBorderWidthDefault.value)
const fieldBorderWidthUnit = ref(fieldBorderWidthDefault.unit)
const fieldPaddingLeftRightValue = ref(fieldPaddingLRDefault.value)
const fieldPaddingLeftRightUnit = ref(fieldPaddingLRDefault.unit)
const fieldPaddingTopBottomValue = ref(fieldPaddingTBDefault.value)
const fieldPaddingTopBottomUnit = ref(fieldPaddingTBDefault.unit)
const labelFontColor = ref(defaults.labelFontColor as string)
const buttonBackground = ref(defaults.buttonBackground as string)
const buttonBorderColor = ref(defaults.buttonBorderColor as string)
const buttonBorderWidthValue = ref(buttonBorderWidthDefault.value)
const buttonBorderWidthUnit = ref(buttonBorderWidthDefault.unit)
const buttonText = ref(defaults.buttonText as string)

const formCornerMainPlaceholder = computed(() =>
  isFormCornerLinked.value ? String(formCornerLinkedValue.value) : getLabel('mix'),
)
const fieldCornerMainPlaceholder = computed(() =>
  isFieldCornerLinked.value ? String(fieldCornerLinkedValue.value) : getLabel('mix'),
)

const formCornerMainValue = computed({
  get: () => (isFormCornerLinked.value ? formCornerLinkedValue.value : ''),
  set: (newValue) => {
    if (isFormCornerLinked.value) {
      formCornerLinkedValue.value = newValue === '' ? 0 : Number(newValue)
    }
  },
})

const fieldCornerMainValue = computed({
  get: () => (isFieldCornerLinked.value ? fieldCornerLinkedValue.value : ''),
  set: (newValue) => {
    if (isFieldCornerLinked.value) {
      fieldCornerLinkedValue.value = newValue === '' ? 0 : Number(newValue)
    }
  },
})

const updateFormCornerSettings = () => {
  const cornerSettings = buildCornerSettings(
    isFormCornerLinked.value,
    formCornerLinkedValue.value,
    formCornerLinkedUnit.value,
    formCornerTopLeftValue.value,
    formCornerTopLeftUnit.value,
    formCornerTopRightValue.value,
    formCornerTopRightUnit.value,
    formCornerBottomRightValue.value,
    formCornerBottomRightUnit.value,
    formCornerBottomLeftValue.value,
    formCornerBottomLeftUnit.value,
  )
  formBuilderStore.updateStyleSettings('quickMode.formCorner', cornerSettings)
  formBuilderStore.updateStyleSettings('advancedMode.general.formCorner', cornerSettings)
}

const updateFieldCornerSettings = () => {
  const cornerSettings = buildCornerSettings(
    isFieldCornerLinked.value,
    fieldCornerLinkedValue.value,
    fieldCornerLinkedUnit.value,
    fieldCornerTopLeftValue.value,
    fieldCornerTopLeftUnit.value,
    fieldCornerTopRightValue.value,
    fieldCornerTopRightUnit.value,
    fieldCornerBottomRightValue.value,
    fieldCornerBottomRightUnit.value,
    fieldCornerBottomLeftValue.value,
    fieldCornerBottomLeftUnit.value,
  )
  formBuilderStore.updateStyleSettings('quickMode.fieldCorner', cornerSettings)
  formBuilderStore.updateStyleSettings('advancedMode.fieldStates.default.corner', cornerSettings)
}

const toggleFormCornerLinked = () => {
  toggleCornerLinked(
    isFormCornerLinked,
    formCornerLinkedValue,
    formCornerLinkedUnit,
    formCornerTopLeftValue,
    formCornerTopLeftUnit,
    formCornerTopRightValue,
    formCornerTopRightUnit,
    formCornerBottomRightValue,
    formCornerBottomRightUnit,
    formCornerBottomLeftValue,
    formCornerBottomLeftUnit,
  )
  updateFormCornerSettings()
}

const toggleFieldCornerLinked = () => {
  toggleCornerLinked(
    isFieldCornerLinked,
    fieldCornerLinkedValue,
    fieldCornerLinkedUnit,
    fieldCornerTopLeftValue,
    fieldCornerTopLeftUnit,
    fieldCornerTopRightValue,
    fieldCornerTopRightUnit,
    fieldCornerBottomRightValue,
    fieldCornerBottomRightUnit,
    fieldCornerBottomLeftValue,
    fieldCornerBottomLeftUnit,
  )
  updateFieldCornerSettings()
}

// Sync refs with store values
const syncWithStore = () => {
  isSyncingFromStore.value = true
  const quickMode = formBuilderStore.styleSettings.quickMode
  if (quickMode) {
    formBackground.value = resolveSyncStringValue(quickMode.formBackground, defaults.formBackground)
    formBorderColor.value = resolveSyncStringValue(
      quickMode.formBorderColor,
      defaults.formBorderColor,
    )

    const borderWidth = parseSyncNumericDimension(
      quickMode.formBorderWidth,
      defaults.formBorderWidth,
    )
    formBorderWidthValue.value = borderWidth.value
    formBorderWidthUnit.value = borderWidth.unit

    const verticalSpacing = parseSyncNumericDimension(
      quickMode.verticalSpacing,
      defaults.verticalSpacing,
    )
    verticalSpacingValue.value = verticalSpacing.value
    verticalSpacingUnit.value = verticalSpacing.unit

    const horizontalSpacing = parseSyncNumericDimension(
      quickMode.horizontalSpacing,
      defaults.horizontalSpacing,
    )
    horizontalSpacingValue.value = horizontalSpacing.value
    horizontalSpacingUnit.value = horizontalSpacing.unit

    const formCornerDefaultValue = resolveCornerDefaultValue(defaults.formCorner)
    applyCornerSettings(
      quickMode.formCorner,
      formCornerDefaultValue,
      isFormCornerLinked,
      formCornerLinkedValue,
      formCornerLinkedUnit,
      formCornerTopLeftValue,
      formCornerTopLeftUnit,
      formCornerTopRightValue,
      formCornerTopRightUnit,
      formCornerBottomRightValue,
      formCornerBottomRightUnit,
      formCornerBottomLeftValue,
      formCornerBottomLeftUnit,
    )

    formTitleText.value = resolveSyncStringValue(quickMode.formTitleText, defaults.formTitleText)
    fieldBackground.value = resolveSyncStringValue(
      quickMode.fieldBackground,
      defaults.fieldBackground,
    )
    fieldText.value = resolveSyncStringValue(quickMode.fieldText, defaults.fieldText)
    fieldBorderColor.value = resolveSyncStringValue(
      quickMode.fieldBorderColor,
      defaults.fieldBorderColor,
    )

    const fieldCornerDefaultValue = resolveCornerDefaultValue(defaults.fieldCorner)
    applyCornerSettings(
      quickMode.fieldCorner,
      fieldCornerDefaultValue,
      isFieldCornerLinked,
      fieldCornerLinkedValue,
      fieldCornerLinkedUnit,
      fieldCornerTopLeftValue,
      fieldCornerTopLeftUnit,
      fieldCornerTopRightValue,
      fieldCornerTopRightUnit,
      fieldCornerBottomRightValue,
      fieldCornerBottomRightUnit,
      fieldCornerBottomLeftValue,
      fieldCornerBottomLeftUnit,
    )

    const fieldBorderWidth = parseSyncNumericDimension(
      quickMode.fieldBorderWidth,
      defaults.fieldBorderWidth,
    )
    fieldBorderWidthValue.value = fieldBorderWidth.value
    fieldBorderWidthUnit.value = fieldBorderWidth.unit

    const fieldPaddingLR = parseDimensionToNumeric(
      (quickMode.fieldPaddingLeftRight ?? defaults.fieldPaddingLeftRight) as string,
    )
    fieldPaddingLeftRightValue.value = fieldPaddingLR.value
    fieldPaddingLeftRightUnit.value = fieldPaddingLR.unit

    const fieldPaddingTB = parseDimensionToNumeric(
      (quickMode.fieldPaddingTopBottom ?? defaults.fieldPaddingTopBottom) as string,
    )
    fieldPaddingTopBottomValue.value = fieldPaddingTB.value
    fieldPaddingTopBottomUnit.value = fieldPaddingTB.unit

    labelFontColor.value = resolveSyncStringValue(quickMode.labelFontColor, defaults.labelFontColor)
    buttonBackground.value = resolveSyncStringValue(
      quickMode.buttonBackground,
      defaults.buttonBackground,
    )
    buttonBorderColor.value = resolveSyncStringValue(
      quickMode.buttonBorderColor,
      defaults.buttonBorderColor,
    )

    const buttonBorderWidth = parseSyncNumericDimension(
      quickMode.buttonBorderWidth,
      defaults.buttonBorderWidth,
    )
    buttonBorderWidthValue.value = buttonBorderWidth.value
    buttonBorderWidthUnit.value = buttonBorderWidth.unit

    buttonText.value = resolveSyncStringValue(quickMode.buttonText, defaults.buttonText)
  }
  // Allow watchers to resume after the current tick
  setTimeout(() => {
    isSyncingFromStore.value = false
  }, 0)
}

// Sync on mount
onMounted(() => {
  syncWithStore()
})

// Re-sync when the style settings change externally (e.g., reset)
watch(
  () => formBuilderStore.styleSettings,
  () => {
    syncWithStore()
  },
  { deep: true },
)

// Watch only formId changes to reload data when switching forms
watch(
  () => formBuilderStore.formId,
  () => {
    syncWithStore()
  },
)

registerCallbackStyleWatchers(
  [
    {
      watchRef: formBackground,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.formBackground,
      onChange: () => updateFormBackground(),
    },
    {
      watchRef: formBorderColor,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.formBorderColor,
      onChange: () => updateFormBorderColor(),
    },
    {
      watchRef: formTitleText,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.formTitleText,
      onChange: () => updateFormTitleText(),
    },
    {
      watchRef: fieldBackground,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.fieldBackground,
      onChange: () => updateFieldBackground(),
    },
    {
      watchRef: fieldText,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.fieldText,
      onChange: () => updateFieldText(),
    },
    {
      watchRef: fieldBorderColor,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.fieldBorderColor,
      onChange: () => updateFieldBorderColor(),
    },
    {
      watchRef: labelFontColor,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.labelFontColor,
      onChange: () => updateLabelFontColor(),
    },
    {
      watchRef: buttonBackground,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.buttonBackground,
      onChange: () => updateButtonBackground(),
    },
    {
      watchRef: buttonBorderColor,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.buttonBorderColor,
      onChange: () => updateButtonBorderColor(),
    },
    {
      watchRef: buttonText,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.buttonText,
      onChange: () => updateButtonText(),
    },
  ],
  isSyncingFromStore,
)

// Dimension watchers - using createDimensionWatcher utility
createDimensionWatcher(
  formBorderWidthValue,
  formBorderWidthUnit,
  'quickMode.formBorderWidth',
  ['quickMode.formBorderWidth', 'advancedMode.general.formBorderWidth'],
  formBuilderStore,
  isSyncingFromStore,
)
createDimensionWatcher(
  verticalSpacingValue,
  verticalSpacingUnit,
  'quickMode.verticalSpacing',
  ['quickMode.verticalSpacing', 'advancedMode.general.verticalSpacing'],
  formBuilderStore,
  isSyncingFromStore,
)
createDimensionWatcher(
  horizontalSpacingValue,
  horizontalSpacingUnit,
  'quickMode.horizontalSpacing',
  ['quickMode.horizontalSpacing', 'advancedMode.general.horizontalSpacing'],
  formBuilderStore,
  isSyncingFromStore,
)

registerDeferredWatchGroup(
  [
    isFormCornerLinked,
    formCornerLinkedValue,
    formCornerLinkedUnit,
    formCornerTopLeftValue,
    formCornerTopLeftUnit,
    formCornerTopRightValue,
    formCornerTopRightUnit,
    formCornerBottomRightValue,
    formCornerBottomRightUnit,
    formCornerBottomLeftValue,
    formCornerBottomLeftUnit,
  ],
  isSyncingFromStore,
  () => updateFormCornerSettings(),
)

registerDeferredWatchGroup(
  [
    isFieldCornerLinked,
    fieldCornerLinkedValue,
    fieldCornerLinkedUnit,
    fieldCornerTopLeftValue,
    fieldCornerTopLeftUnit,
    fieldCornerTopRightValue,
    fieldCornerTopRightUnit,
    fieldCornerBottomRightValue,
    fieldCornerBottomRightUnit,
    fieldCornerBottomLeftValue,
    fieldCornerBottomLeftUnit,
  ],
  isSyncingFromStore,
  () => updateFieldCornerSettings(),
)

registerCallbackDimensionWatchers(
  [
    {
      valueRef: fieldBorderWidthValue,
      unitRef: fieldBorderWidthUnit,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.fieldBorderWidth,
      onChange: () => updateFieldBorderWidth(),
    },
    {
      valueRef: fieldPaddingLeftRightValue,
      unitRef: fieldPaddingLeftRightUnit,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.fieldPaddingLeftRight,
      onChange: () => updateFieldPaddingLeftRight(),
    },
    {
      valueRef: fieldPaddingTopBottomValue,
      unitRef: fieldPaddingTopBottomUnit,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.fieldPaddingTopBottom,
      onChange: () => updateFieldPaddingTopBottom(),
    },
    {
      valueRef: buttonBorderWidthValue,
      unitRef: buttonBorderWidthUnit,
      getCurrentValue: () => formBuilderStore.styleSettings.quickMode?.buttonBorderWidth,
      onChange: () => updateButtonBorderWidth(),
    },
  ],
  isSyncingFromStore,
)

// Update functions - update both Quick mode and corresponding Advanced mode properties for sync
const updateFormBackground = () => {
  formBuilderStore.updateStyleSettings('quickMode.formBackground', formBackground.value)
  formBuilderStore.updateStyleSettings('advancedMode.general.formBackground', formBackground.value)
}

const updateFormBorderColor = () => {
  formBuilderStore.updateStyleSettings('quickMode.formBorderColor', formBorderColor.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.general.formBorderColor',
    formBorderColor.value,
  )
}

const updateFormTitleText = () => {
  formBuilderStore.updateStyleSettings('quickMode.formTitleText', formTitleText.value)
  formBuilderStore.updateStyleSettings('advancedMode.formTitle.fontColor', formTitleText.value)
}

const updateFieldBackground = () => {
  formBuilderStore.updateStyleSettings('quickMode.fieldBackground', fieldBackground.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.fieldStates.default.background',
    fieldBackground.value,
  )
}

const updateFieldText = () => {
  formBuilderStore.updateStyleSettings('quickMode.fieldText', fieldText.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.fieldStates.default.textColor',
    fieldText.value,
  )
  formBuilderStore.updateStyleSettings('advancedMode.fieldPlaceholder.fontColor', fieldText.value)
}

const updateFieldBorderColor = () => {
  formBuilderStore.updateStyleSettings('quickMode.fieldBorderColor', fieldBorderColor.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.fieldStates.default.borderColor',
    fieldBorderColor.value,
  )
}

const updateLabelFontColor = () => {
  formBuilderStore.updateStyleSettings('quickMode.labelFontColor', labelFontColor.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.fieldLabels.label.fontColor',
    labelFontColor.value,
  )
}

const updateButtonBackground = () => {
  formBuilderStore.updateStyleSettings('quickMode.buttonBackground', buttonBackground.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.buttonStates.normal.background',
    buttonBackground.value,
  )
}

const updateButtonBorderColor = () => {
  formBuilderStore.updateStyleSettings('quickMode.buttonBorderColor', buttonBorderColor.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.buttonStates.normal.borderColor',
    buttonBorderColor.value,
  )
}

const updateButtonText = () => {
  formBuilderStore.updateStyleSettings('quickMode.buttonText', buttonText.value)
  formBuilderStore.updateStyleSettings(
    'advancedMode.buttonStates.normal.textColor',
    buttonText.value,
  )
}

const updateFieldBorderWidth = () => {
  const value = buildDimensionString(fieldBorderWidthValue.value, fieldBorderWidthUnit.value)
  formBuilderStore.updateStyleSettings('quickMode.fieldBorderWidth', value)
  formBuilderStore.updateStyleSettings('advancedMode.fieldStates.default.borderWidth', value)
}

const updateFieldPaddingLeftRight = () => {
  const value = buildDimensionString(
    fieldPaddingLeftRightValue.value,
    fieldPaddingLeftRightUnit.value,
  )
  formBuilderStore.updateStyleSettings('quickMode.fieldPaddingLeftRight', value)
  formBuilderStore.updateStyleSettings('advancedMode.fieldStates.default.paddingLeftRight', value)
}

const updateFieldPaddingTopBottom = () => {
  const value = buildDimensionString(
    fieldPaddingTopBottomValue.value,
    fieldPaddingTopBottomUnit.value,
  )
  formBuilderStore.updateStyleSettings('quickMode.fieldPaddingTopBottom', value)
  formBuilderStore.updateStyleSettings('advancedMode.fieldStates.default.paddingTopBottom', value)
}

const updateButtonBorderWidth = () => {
  const value = buildDimensionString(buttonBorderWidthValue.value, buttonBorderWidthUnit.value)
  formBuilderStore.updateStyleSettings('quickMode.buttonBorderWidth', value)
  formBuilderStore.updateStyleSettings('advancedMode.buttonStates.normal.borderWidth', value)
}
</script>

<style scoped lang="scss">
.ivyforms-quick-mode-controls {
  &__label {
    font-size: 14px;
    font-weight: 500;
    color: var(--map-base-text-0, #212832);
    flex-shrink: 0;
    min-width: 140px;
  }

  &__color-input {
    position: relative;
    width: 240px;
  }

  &__color-text {
    width: 100%;

    :deep(.el-input__wrapper) {
      padding-right: 48px !important;
    }
  }

  :deep(.ivyforms-quick-mode-controls__input) {
    width: 240px !important;

    &.ivyforms-quick-mode-controls__input--full {
      width: 100% !important;
    }
  }

  &__corner-inputs {
    width: 240px;
  }

  &__corner-main-input {
    width: 240px;
  }

  &__corner-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
