<script setup lang="ts">
import { computed, ref } from 'vue'
import type { KbxSearchField } from '@kbx/contracts'
import KbxButton from './KbxButton.vue'
import KbxSearchFieldControl from './KbxSearchFieldControl.vue'

const props = withDefaults(defineProps<{
  modelValue: Record<string, unknown>
  fields: KbxSearchField[]
  remember?: boolean
  rememberChecked?: boolean
  savedSearch?: boolean
  searchLabel?: string
}>(), { remember:false, rememberChecked:false, savedSearch:false, searchLabel:'조회' })
const emit = defineEmits<{
  'update:modelValue':[Record<string, unknown>]
  'update:rememberChecked':[boolean]
  search:[]
  reset:[]
  savedSearchRequested:[]
}>()

const primary = computed(() => props.fields.filter(x => x.primary !== false))
const secondary = computed(() => props.fields.filter(x => x.primary === false))
const showMore = computed(() => secondary.value.length > 0)
const expanded = ref(false)
const activeSecondaryCount = computed(() => secondary.value.filter(isActive).length)

function isActive(field:KbxSearchField){
  if(field.type==='date-range'&&field.range)return Boolean(props.modelValue[field.range.from]||props.modelValue[field.range.to])
  const current=props.modelValue[field.key]
  return current!==null&&current!==undefined&&current!==''&&current!==false
}
function setValue(key:string,value:unknown){emit('update:modelValue',{...props.modelValue,[key]:value})}
function reset(){
  const next={...props.modelValue}
  for(const field of props.fields){
    if(field.type==='date-range'&&field.range){next[field.range.from]=null;next[field.range.to]=null;continue}
    next[field.key]=field.defaultValue??(field.type==='checkbox'?false:null)
  }
  emit('update:modelValue',next);emit('reset')
}
</script>

<template>
  <form class="kbx-search-panel" role="search" @submit.prevent="emit('search')">
    <div class="kbx-search-panel__fields">
      <KbxSearchFieldControl v-for="field in primary" :key="field.key" :field="field" :model="modelValue" @change="setValue" />
    </div>

    <div class="kbx-search-panel__actions">
      <KbxButton type="submit" :label="searchLabel" variant="primary" />
      <KbxButton v-if="showMore" :label="activeSecondaryCount?`상세조건 ${activeSecondaryCount}`:'상세조건'" :aria-expanded="expanded" @click="expanded=!expanded" />
      <KbxButton label="초기화" variant="ghost" @click="reset" />
      <KbxButton v-if="savedSearch" label="기본조건 저장" variant="ghost" @click="emit('savedSearchRequested')" />
    </div>

    <div v-if="expanded&&secondary.length" class="kbx-search-panel__secondary">
      <KbxSearchFieldControl v-for="field in secondary" :key="field.key" :field="field" :model="modelValue" @change="setValue" />
      <label v-if="remember" class="kbx-search-remember"><input type="checkbox" :checked="rememberChecked" @change="emit('update:rememberChecked',($event.target as HTMLInputElement).checked)"><span>마지막 조회조건 기억<small>민감한 자유검색어는 저장 대상에서 제외할 수 있습니다.</small></span></label>
    </div>
  </form>
</template>

<style scoped>
.kbx-search-panel{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--kbx-space-2) var(--kbx-space-3);padding:var(--kbx-space-2) var(--kbx-space-3);border:var(--kbx-border-width) solid var(--kbx-color-border);background:var(--kbx-color-surface-muted)}.kbx-search-panel__fields,.kbx-search-panel__secondary{display:flex;align-items:center;gap:var(--kbx-space-2) var(--kbx-space-4);flex-wrap:wrap}.kbx-search-panel__secondary{grid-column:1/-1;padding-top:var(--kbx-space-2);border-top:var(--kbx-border-width) solid var(--kbx-color-border)}.kbx-search-panel__actions{display:flex;align-items:flex-start;gap:var(--kbx-space-1);white-space:nowrap}.kbx-search-remember{display:inline-flex;align-items:center;gap:var(--kbx-space-2);min-height:var(--kbx-control-height);font-size:var(--kbx-font-sm);margin-left:auto;color:var(--kbx-color-text-muted)}.kbx-search-remember input{width:var(--kbx-checkbox-size);height:var(--kbx-checkbox-size);margin:0}.kbx-search-remember span{display:grid;gap:var(--kbx-space-1);color:var(--kbx-color-text)}.kbx-search-remember small{font-size:var(--kbx-font-xs);font-weight:400;color:var(--kbx-color-text-muted)}@media(max-width:64rem){.kbx-search-panel{grid-template-columns:1fr}.kbx-search-panel__actions{justify-content:flex-end}.kbx-search-panel__secondary{grid-column:1}}
</style>
