<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { commonStatusOptions } from '@/constants/business';
import TableSearchFields, { type SearchField } from '@/components/custom/table-search-fields.vue';
import { $t } from '@/locales';

defineOptions({ name: 'RoleSearch' });

interface Emits {
  (e: 'reset'): void;
  (e: 'search'): void;
}

const emit = defineEmits<Emits>();

const model = defineModel<Api.SystemManage.RoleSearchParams>('model', { required: true });

const searchModel = reactive<{
  keyword: string;
  status?: Api.SystemManage.CommonStatus;
}>({
  keyword: '',
  status: undefined
});

let syncingFromSource = false;

watch(
  () => [model.value.name, model.value.code, model.value.status] as const,
  ([name, code, status]) => {
    syncingFromSource = true;
    searchModel.keyword = name ?? code ?? '';
    searchModel.status = status;
    syncingFromSource = false;
  },
  { immediate: true, flush: 'sync' }
);

watch(
  () => [searchModel.keyword, searchModel.status] as const,
  ([keywordValue, status]) => {
    if (syncingFromSource) {
      return;
    }

    const keywordText = keywordValue.trim() || undefined;
    model.value.name = keywordText;
    model.value.code = keywordText;
    model.value.status = status;
  },
  { flush: 'sync' }
);

const fields = computed<SearchField[]>(() => [
  {
    key: 'keyword',
    label: $t('page.system.role.searchKeyword'),
    type: 'input',
    placeholder: $t('page.system.role.searchPlaceholder')
  },
  {
    key: 'status',
    label: $t('page.system.role.roleStatus'),
    type: 'select',
    placeholder: $t('page.system.role.form.roleStatus'),
    options: commonStatusOptions.map(item => ({
      label: $t(item.label),
      value: item.value
    }))
  }
]);

function reset() {
  emit('reset');
}

function search() {
  emit('search');
}
</script>

<template>
  <TableSearchFields v-model="searchModel" :fields="fields" :columns="3" @reset="reset" @search="search" />
</template>

<style scoped></style>
