<template>
  <sa-search-bar
    ref="searchBarRef"
    v-model="formData"
    label-width="120px"
    :showExpand="false"
    @reset="handleReset"
    @search="handleSearch"
    @expand="handleExpand"
  >
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.lotteryPoolConfig')" prop="lottery_config_id">
        <el-select
          v-model="formData.lottery_config_id"
          :placeholder="$t('page.search.placeholderLotteryPool')"
          clearable
          filterable
          remote
          reserve-keyword
          :loading="lotteryPoolLoading"
          :remote-method="filterLotteryPoolOptions"
          style="width: 100%"
          @visible-change="onLotteryPoolDropdownVisible"
        >
          <el-option
            v-for="item in lotteryPoolOptions"
            :key="item.id"
            :label="lotteryPoolOptionLabel(item)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.rewardConfigRecordId')" prop="reward_config_record_id">
        <el-input-number
          v-model="formData.reward_config_record_id"
          :placeholder="$t('table.searchBar.all')"
          :precision="0"
          :step="1"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.drawType')" prop="lottery_type">
        <el-select v-model="formData.lottery_type" :placeholder="$t('table.searchBar.all')" clearable style="width: 100%">
          <el-option :label="$t('page.search.paid')" :value="0" />
          <el-option :label="$t('page.search.free')" :value="1" />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.direction')" prop="direction">
        <el-select v-model="formData.direction" :placeholder="$t('table.searchBar.all')" clearable style="width: 100%">
          <el-option :label="$t('page.search.clockwise')" :value="0" />
          <el-option :label="$t('page.search.anticlockwise')" :value="1" />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.isBigWin')" prop="is_win">
        <el-select v-model="formData.is_win" :placeholder="$t('table.searchBar.all')" clearable style="width: 100%">
          <el-option :label="$t('page.search.noBigWin')" :value="0" />
          <el-option :label="$t('page.search.bigWin')" :value="1" />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.paidAmount')" prop="paid_amount">
        <el-input-number
          v-model="formData.paid_amount"
          :placeholder="$t('table.searchBar.all')"
          :precision="0"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.ante')" prop="ante">
        <el-input-number
          v-model="formData.ante"
          :placeholder="$t('table.searchBar.all')"
          :precision="0"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.winCoin')" prop="win_coin_min">
        <div class="range-wrap">
          <el-input-number
            v-model="formData.win_coin_min"
            :placeholder="$t('table.searchBar.min')"
            :precision="0"
            controls-position="right"
            class="range-input"
          />
          <span class="range-sep">{{ $t('table.searchBar.rangeSeparator') }}</span>
          <el-input-number
            v-model="formData.win_coin_max"
            :placeholder="$t('table.searchBar.max')"
            :precision="0"
            controls-position="right"
            class="range-input"
          />
        </div>
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.rewardTier')" prop="reward_tier">
        <el-select v-model="formData.reward_tier" :placeholder="$t('table.searchBar.all')" clearable style="width: 100%">
          <el-option label="T1" value="T1" />
          <el-option label="T2" value="T2" />
          <el-option label="T3" value="T3" />
          <el-option label="T4" value="T4" />
          <el-option label="T5" value="T5" />
          <el-option label="BIGWIN" value="BIGWIN" />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col v-bind="setSpan(6)">
      <el-form-item :label="$t('page.search.rollNumber')" prop="roll_number">
        <el-select
          v-model="formData.roll_number"
          :placeholder="$t('table.searchBar.all')"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="n in 26"
            :key="n + 4"
            :label="String(n + 4)"
            :value="n + 4"
          />
        </el-select>
      </el-form-item>
    </el-col>
  </sa-search-bar>
</template>

<script setup lang="ts">
  import lotteryPoolApi from '../../../api/lottery_pool_config/index'
  import {
    getChannelDeptRequestParams,
    useInjectedChannelDept
  } from '@/composables/useChannelDeptScope'
  import {
    filterLotteryPoolOptionsByQuery,
    lotteryPoolOptionLabel,
    type LotteryPoolOption
  } from '@/views/plugin/dice/utils/lotteryPoolDisplay'

  interface Props {
    modelValue: Record<string, any>
  }
  interface Emits {
    (e: 'update:modelValue', value: Record<string, any>): void
    (e: 'search', params: Record<string, any>): void
    (e: 'reset'): void
  }
  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()
  const isExpanded = ref<boolean>(false)
  const channelScope = useInjectedChannelDept()

  const lotteryPoolAllOptions = ref<LotteryPoolOption[]>([])
  const lotteryPoolOptions = ref<LotteryPoolOption[]>([])
  const lotteryPoolLoading = ref(false)

  function resolveDeptParams(): Record<string, unknown> {
    const extra = getChannelDeptRequestParams()
    if (extra.dept_id !== undefined) {
      return extra
    }
    if (channelScope) {
      return { dept_id: channelScope.selectedDeptId.value }
    }
    return {}
  }

  async function loadLotteryPoolOptions() {
    lotteryPoolLoading.value = true
    try {
      const list = await lotteryPoolApi.getOptions(resolveDeptParams())
      lotteryPoolAllOptions.value = list
      lotteryPoolOptions.value = list
    } catch {
      lotteryPoolAllOptions.value = []
      lotteryPoolOptions.value = []
    } finally {
      lotteryPoolLoading.value = false
    }
  }

  function filterLotteryPoolOptions(query: string) {
    lotteryPoolOptions.value = filterLotteryPoolOptionsByQuery(lotteryPoolAllOptions.value, query)
  }

  function onLotteryPoolDropdownVisible(visible: boolean) {
    if (visible && lotteryPoolAllOptions.value.length === 0) {
      void loadLotteryPoolOptions()
    }
  }

  onMounted(() => {
    void loadLotteryPoolOptions()
  })

  watch(
    () => channelScope?.selectedDeptId.value,
    () => {
      void loadLotteryPoolOptions()
    }
  )

  const searchBarRef = ref()
  const formData = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  function handleReset() {
    searchBarRef.value?.ref.resetFields()
    emit('reset')
  }

  async function handleSearch() {
    emit('search', formData.value)
  }

  function handleExpand(expanded: boolean) {
    isExpanded.value = expanded
  }

  const setSpan = (span: number) => ({
    span,
    xs: 24,
    sm: span >= 12 ? span : 12,
    md: span >= 8 ? span : 8,
    lg: span,
    xl: span
  })
</script>

<style lang="scss" scoped>
  .range-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0;
  }

  .range-input {
    flex: 1;
    min-width: 0;
  }

  .range-sep {
    color: var(--el-text-color-secondary);
    flex-shrink: 0;
  }
</style>
