<script setup lang="ts">
import { toRefs, ref, PropType, watch } from 'vue'
import {
  LabelControl,
  Tooltip,
} from './index'
import {
  purifyHtml,
  removeItemsFromArray,
} from '@/helper'
import { useSettingsStore } from '@/stores/settings-store'
import { storeToRefs } from 'pinia'
import Preview from './Preview.vue'

const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
  controlSettings: {
    type: Array as PropType<any[]>,
    required: true,
  },
})
const { params, controlSettings } = toRefs(props)
const settingsStore = useSettingsStore()
const {
  showPopup,
  componentUpgrade,
  selectedConditionKey,
  selectedConditionValue,
  editedRowKey,
  dynamicOptions,
} = storeToRefs(settingsStore)

const arg = params.value
const controls = ref<any[]>(controlSettings.value ?? [])
const options = ref<any>({})
const default_value = ref<any>(arg['default'])
const with_preview = ref<any>(arg['preview'])
const selected_value = ref<any>('')
const previewRef = ref<any>([])

if (typeof default_value.value !== 'undefined' && default_value.value !== null) {
  selected_value.value = default_value.value
}

// Watch for changes in controlSettings to update controls array
// This allows Preview component to react to changes from other controls (like color pickers with preview_ref)
// When a control with preview_ref matching this select's ID changes, DynamicComponents updates controlSettings,
// which triggers this watch and updates the controls array, causing Preview to re-render with new values
watch(
  () => controlSettings.value,
  (newControls) => {
    if (newControls && Array.isArray(newControls)) {
      // Update controls array with latest values from controlSettings
      // This ensures Preview component sees updated default values from other controls
      controls.value = newControls.map((newControl: any) => {
        // Find existing control to preserve any local state
        const existingControl = controls.value.find((c: any) => c.id === newControl.id)
        if (existingControl) {
          // Merge, prioritizing new default value from controlSettings
          // This is crucial for Preview component to see updated color values
          return {
            ...existingControl,
            ...newControl,
            default: newControl.default !== undefined ? newControl.default : existingControl.default
          }
        }
        return newControl
      })
    }
  },
  { deep: true, immediate: true }
)

// check if multiple is set to true.
if (typeof arg['multiple'] !== 'undefined' && arg['multiple'] !== null) {
  if (arg['multiple']) {
    if (selected_value.value.length === 0) {
      selected_value.value = []
    }
  }
}

if (typeof arg['dependent_option'] !== 'undefined' && arg['dependent_option'] !== null) {
  // Check if the dependent option is selected.
  if (typeof dynamicOptions.value[arg['dependent_option']] !== 'undefined' && dynamicOptions.value[arg['dependent_option']] !== null) {
    options.value = arg['options'][dynamicOptions.value[arg['dependent_option']]]
    selected_value.value = default_value.value
  }
} else if (typeof arg['dependent'] !== 'undefined' && arg['dependent']) {
  options.value = arg['options']
} else {
  options.value = arg['options']
}

if (typeof arg['with_condition'] !== 'undefined' && arg['with_condition'] !== null) {
  if (editedRowKey.value === null) {
    if (selectedConditionKey.value !== '' && selectedConditionValue.value !== '') {
      if (selectedConditionKey.value === arg['id']) {
        selected_value.value = selectedConditionValue.value
      }
    }
  } else {
    if (selectedConditionKey.value !== '' && selectedConditionValue.value !== '') {
      if (selectedConditionKey.value === arg['id']) {
        selected_value.value = selectedConditionValue.value
      }
    } else {
      const new_selected_value = selected_value.value
      selected_value.value = new_selected_value
    }
  }
}

const disable = ref<boolean>(arg['disabled'] ?? false)
const emit = defineEmits(['fieldData', 'selectedCondition', 'selectedDependent', 'previewRef'])
const inputValues = ref<any>([])
const selectTriggerValue = ref<any>([])

// Set for default value.
if (selected_value.value !== '' && !disable.value) {
  inputValues.value[arg['id']] = selected_value.value

  let selectedValue = options.value[selected_value.value]
  if (Array.isArray(selected_value.value)) {
    selectedValue = selected_value.value.map((index: any) => options.value[index])
  }
  if (typeof arg['label_id'] !== 'undefined' && arg['label_id'] !== null) {
    inputValues.value[arg['label_id']] = selectedValue
  }
  emit('fieldData', inputValues.value)
}

const emitValueChange = () => {
  const value = selected_value.value

  if (typeof arg['pro'] !== 'undefined' && arg['pro'] !== null) {
    if (typeof arg['pro_on_active'] !== 'undefined' && arg['pro_on_active'] !== null) {
      if (arg['pro_on_active'] && selected_value.value !== '') {
        showPopup.value = true
        selected_value.value = ''
      }
    } else {
      showPopup.value = true
      selected_value.value = default_value.value
    }

    componentUpgrade.value = arg['pro']
  } else {
    let selectedValue = options.value[value]
    if (Array.isArray(value)) {
      selectedValue = value.map((index) => options.value[index])
    }
    inputValues.value[arg['id']] = value
    if (typeof arg['label_id'] !== 'undefined' && arg['label_id'] !== null) {
      inputValues.value[arg['label_id']] = selectedValue
    }

    // For dependent column.
    if (typeof arg['column_dependent'] !== 'undefined' && arg['column_dependent'] !== null) {
      inputValues.value[arg['column_dependent']] = value

      if (typeof arg['column_dependent_text'] !== 'undefined' && arg['column_dependent_text'] !== null) {
        inputValues.value[arg['column_dependent_text']] = selectedValue
      }
    }

    emit('fieldData', inputValues.value)

    // Conditional.
    if (typeof arg['with_condition'] !== 'undefined' && arg['with_condition'] !== null) {
      if (arg['with_condition']) {
        selectedConditionKey.value = arg['id']
        selectedConditionValue.value = value

        selectTriggerValue.value[arg['id']] = value
        emit('selectedCondition', selectTriggerValue.value)
      }
    }

    // Dependent.
    if (typeof arg['dependent'] !== 'undefined' && arg['dependent'] !== null) {
      if (arg['dependent']) {
        selectedConditionKey.value = arg['id']
        selectedConditionValue.value = value

        dynamicOptions.value[arg['id']] = value
        emit('selectedDependent', dynamicOptions)
      }
    }

    selected_value.value = value

    previewRef.value[arg['id']] = inputValues.value
    emit('previewRef', previewRef.value)
  }
}

if (typeof arg['edit_options'] !== 'undefined' && arg['edit_options'] !== null) {
  if (editedRowKey.value === null) {
    options.value = removeItemsFromArray(options.value, arg['edit_options'])
  } else {
    if (typeof arg['dependent_option'] !== 'undefined' && arg['dependent_option'] !== null) {
      // Check if the dependent option is selected.
      if (typeof dynamicOptions.value[arg['dependent_option']] !== 'undefined' && dynamicOptions.value[arg['dependent_option']] !== null) {
        options.value = arg['options'][dynamicOptions.value[arg['dependent_option']]]
      }
    } else if (typeof arg['dependent'] !== 'undefined' && arg['dependent']) {
      options.value = arg['options']
    } else {
      options.value = arg['options']
    }
  }
}
</script>

<template>
  <div>
    <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-2">
      <LabelControl :params="arg" />
    </div>
    <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-2">
      <select
        v-model="selected_value"
        @change="emitValueChange"
        class="stwlite-tw-block stwlite-tw-w-full stwlite-tw-max-w-xs stwlite-tw-rounded-md stwlite-tw-border-gray-300 stwlite-tw-shadow-sm focus:stwlite-tw-border-blue-500 focus:stwlite-tw-ring-blue-500 stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border"
        :disabled="disable"
      >
        <option v-for="(option, optionkey) in options" :key="optionkey" :value="optionkey">
          {{ option }}
        </option>
      </select>
      <Tooltip :params="arg" />
    </div>
    <div v-if="with_preview" class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-mb-2 stwlite-tw-gap-2">
      <Preview
        v-if="arg['preview_options']?.text_color && arg['preview_options']?.background_color && arg['preview_options']?.border_color" 
        :selected_value="selected_value" 
        :preview_options="arg['preview_options']" 
        :controls="controls"
      />
    </div>
    <p v-if="arg['description'] !== 'undefined'" class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mt-2" v-html="purifyHtml(arg?.['description'] ?? '')" />
  </div>
</template>

<style scoped lang="scss">
select {
  max-width: 20rem;
  font-size: 16px;
  padding-top: 0.3rem;
  padding-bottom: 0.3rem;
  padding-left: 0.75rem;
  padding-right: 0.75rem;
  border-color: rgb(209, 213, 219);
  border-radius: 0.375rem;
}
</style>