<template>
  <form class="assignments-filters" @submit.prevent="onSubmit">
    <div class="assignments-filters__grid">
      <TextField v-model="form.title" name="title" label="عنوان تکلیف">
        <template #appendIcon>
          <SvgIcon name="monitor" :size="20" color="var(--color-thd-gray)" />
        </template>
      </TextField>
      <SelectField
        v-model="form.termId"
        name="termId"
        label="ترم"
        :options="termOptions"
        option-label="title"
        option-value="id"
        :searchable="true"
        :on-search="searchTerms"
        @update:modelValue="onTermChange"
      />
      <SelectField
        v-if="form.termId"
        v-model="form.courseId"
        name="courseId"
        label="دوره"
        :options="templateOptions"
        option-label="title"
        option-value="id"
        :searchable="true"
        :on-search="searchTemplates"
        @update:modelValue="onCourseChange"
      />
      <SelectField
        v-if="form.courseId"
        v-model="form.sessionId"
        name="sessionId"
        label="جلسه"
        :options="sessionOptions"
        option-label="title"
        option-value="id"
        :searchable="true"
        :on-search="searchSessions"
      />
      <DatePickerField v-model="form.fromDate" name="fromDate" label="از تاریخ" :max="todayIso" />
      <DatePickerField v-model="form.toDate" name="toDate" label="تا تاریخ" :max="todayIso" />
    </div>

    <div class="assignments-filters__actions">
      <CircleButton
        v-if="hasFilters"
        tooltip="حذف فیلتر"
        bg-color="transparent"
        size="2.5rem"
        type="button"
        @click="onReset"
      >
        <template #icon>
          <SvgIcon name="close" color="black" :size="20" />
        </template>
      </CircleButton>
      <CircleButton
        tooltip="اعمال فیلتر"
        bg-color="rgba(104, 104, 104, 0.05)"
        size="2.5rem"
        type="submit"
      >
        <template #icon>
          <SvgIcon name="funnel" :size="20" color="var(--color-error)" />
        </template>
      </CircleButton>
    </div>
  </form>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import useDebounce from '@/composables/useDebounce'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'
import CircleButton from '@/components/CircleButton.vue'
import SelectField from '@/components/form/SelectField.vue'
import DatePickerField from '@/components/form/DatePickerField.vue'
import { useAdminTermsListQuery } from '@/services/query/admin-terms'
import { useAdminCoursesListQuery } from '@/services/query/admin-courses'
import { useAdminSessionsListQuery } from '@/services/query/admin-sessions'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      title: '',
      termId: '',
      courseId: '',
      sessionId: '',
      fromDate: '',
      toDate: '',
    }),
  },
})

const emit = defineEmits(['update:modelValue', 'apply', 'reset'])

const emptyForm = () => ({
  title: '',
  termId: '',
  courseId: '',
  sessionId: '',
  fromDate: '',
  toDate: '',
})
const form = ref({ ...emptyForm(), ...props.modelValue })

watch(
  () => props.modelValue,
  (next) => {
    form.value = { ...emptyForm(), ...next }
  },
  { deep: true }
)

const todayIso = new Date().toISOString()

const termSearch = ref('')
const termFilters = computed(() => ({ title: termSearch.value }))
const termPagination = ref({ page: 1, perPage: 10 })
const { data: termsResponse } = useAdminTermsListQuery(termFilters, termPagination)
const termOptions = computed(() => termsResponse.value?.data ?? [])

const templateSearch = ref('')
const templateFilters = computed(() => ({
  title: templateSearch.value,
  termId: form.value.termId || undefined,
}))
const templatePagination = ref({ page: 1, perPage: 10 })
const { data: templatesResponse } = useAdminCoursesListQuery(templateFilters, templatePagination, {
  enabled: () => !!form.value.termId,
})
const templateOptions = computed(() => templatesResponse.value?.data ?? [])

const sessionSearch = ref('')
const sessionListFilters = computed(() => ({
  title: sessionSearch.value,
  courseId: form.value.courseId || undefined,
}))
const sessionPagination = ref({ page: 1, perPage: 10 })
const { data: sessionsResponse } = useAdminSessionsListQuery(
  sessionListFilters,
  sessionPagination,
  {
    enabled: () => !!form.value.courseId,
  }
)
const sessionOptions = computed(() => sessionsResponse.value?.data ?? [])

const searchTerms = useDebounce((q) => {
  termSearch.value = q || ''
}, 400)
const searchTemplates = useDebounce((q) => {
  templateSearch.value = q || ''
}, 400)
const searchSessions = useDebounce((q) => {
  sessionSearch.value = q || ''
}, 400)

const onTermChange = () => {
  form.value.courseId = ''
  form.value.sessionId = ''
}

const onCourseChange = () => {
  form.value.sessionId = ''
}

const hasFilters = computed(() =>
  Object.values(form.value).some((v) => v !== '' && v !== null && v !== undefined)
)

const onSubmit = () => {
  emit('update:modelValue', { ...form.value })
  emit('apply', { ...form.value })
}

const onReset = () => {
  form.value = emptyForm()
  emit('update:modelValue', { ...form.value })
  emit('reset')
}
</script>

<style lang="scss" scoped>
.assignments-filters {
  display: flex;
  align-items: flex-start;
  gap: 0.625rem;

  &__grid {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.5rem;

    @media (min-width: 768px) {
      grid-template-columns: repeat(3, 1fr);
    }

    @media (min-width: 1280px) {
      grid-template-columns: repeat(6, 1fr);
    }
  }

  &__actions {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    padding-top: 1.75rem;
  }
}
</style>
