<template>
  <div class="space-y-4">
    <div class="flex flex-wrap items-center justify-between gap-2">
      <div class="text-sm text-gray-500">
        {{ t('store.temporaryHours.tip') }}
      </div>
      <div class="flex items-center gap-2">
        <ElButton @click="loadHolidays">{{ t('store.action.refresh') }}</ElButton>
        <ElButton type="primary" @click="handleAdd">
          {{ t('store.temporaryHours.action.add') }}
        </ElButton>
      </div>
    </div>

    <ElTable :data="holidays" border stripe v-loading="loading" class="w-full">
      <ElTableColumn :label="t('store.temporaryHours.table.dateRange')" min-width="200">
        <template #default="{ row }">
          <span>{{ formatDate(row.date) }}</span>
          <span v-if="row.endDate"> ~ {{ formatDate(row.endDate) }}</span>
        </template>
      </ElTableColumn>
      <ElTableColumn :label="t('store.temporaryHours.table.timeRange')" min-width="140">
        <template #default="{ row }">
          <span v-if="row.isAllDay">{{ t('store.temporaryHours.allDay') }}</span>
          <span v-else>{{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}</span>
        </template>
      </ElTableColumn>
      <ElTableColumn :label="t('store.temporaryHours.table.overrideType')" min-width="120">
        <template #default="{ row }">
          <ElTag :type="getOverrideTypeTagType(row.overrideType)">
            {{ getOverrideTypeLabel(row.overrideType) }}
          </ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn
        :label="t('store.temporaryHours.table.reason')"
        min-width="180"
        prop="reason"
      />
      <ElTableColumn :label="t('common.action')" width="120" fixed="right" align="center">
        <template #default="{ row }">
          <ElButton link type="primary" @click="handleEdit(row)">
            {{ t('common.edit') }}
          </ElButton>
          <ElButton link type="danger" @click="handleDelete(row)">
            {{ t('store.action.delete') }}
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog
      v-model="dialogVisible"
      :title="
        isEdit
          ? t('store.temporaryHours.dialog.editTitle')
          : t('store.temporaryHours.dialog.addTitle')
      "
      width="500px"
      destroy-on-close
    >
      <ElForm ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <ElFormItem :label="t('store.temporaryHours.form.dateRange')" prop="dateRange">
          <ElDatePicker
            v-model="form.dateRange"
            type="daterange"
            :start-placeholder="t('common.startDate')"
            :end-placeholder="t('common.endDate')"
            value-format="YYYY-MM-DD"
            class="!w-full"
          />
        </ElFormItem>

        <ElFormItem :label="t('store.temporaryHours.form.isAllDay')">
          <ElSwitch v-model="form.isAllDay" />
        </ElFormItem>

        <ElFormItem
          v-if="!form.isAllDay"
          :label="t('store.temporaryHours.form.timeRange')"
          prop="timeRange"
        >
          <ElTimePicker
            v-model="form.timeRange"
            is-range
            format="HH:mm"
            value-format="HH:mm:ss"
            :start-placeholder="t('common.startTime')"
            :end-placeholder="t('common.endTime')"
            class="!w-full"
          />
        </ElFormItem>

        <ElFormItem :label="t('store.temporaryHours.form.overrideType')" prop="overrideType">
          <ElSelect v-model="form.overrideType" class="w-full">
            <ElOption
              v-for="option in overrideTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>

        <ElFormItem :label="t('store.temporaryHours.form.reason')">
          <ElInput
            v-model="form.reason"
            type="textarea"
            :rows="2"
            maxlength="200"
            show-word-limit
            :placeholder="t('store.temporaryHours.form.reasonPlaceholder')"
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <ElButton @click="dialogVisible = false">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ t('common.confirm') }}
        </ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElDatePicker,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElMessage,
    ElMessageBox,
    ElOption,
    ElSelect,
    ElSwitch,
    ElTable,
    ElTableColumn,
    ElTag,
    ElTimePicker,
    type FormInstance,
    type FormRules
  } from 'element-plus'
  import {
    fetchCreateStoreHoliday,
    fetchDeleteStoreHoliday,
    fetchStoreHolidays,
    fetchUpdateStoreHoliday
  } from '@/api/store'
  import { OverrideType } from '@/enums/OverrideType'

  defineOptions({ name: 'TemporaryHoursPanel' })

  // 1. 基础输入
  const props = defineProps<{ storeId: string }>()
  const { t } = useI18n()

  // 2. 状态管理
  const loading = ref(false)
  const submitting = ref(false)
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const editingId = ref<string | null>(null)
  const holidays = ref<Api.Store.StoreHolidayDto[]>([])
  const formRef = ref<FormInstance>()

  // 3. 表单数据
  const form = reactive({
    dateRange: [] as string[],
    isAllDay: true,
    timeRange: [] as string[],
    overrideType: OverrideType.Closed,
    reason: ''
  })

  // 4. 选项配置
  const overrideTypeOptions = computed(() => [
    {
      value: OverrideType.Closed,
      label: t('store.temporaryHours.overrideType.closed')
    },
    {
      value: OverrideType.TemporaryOpen,
      label: t('store.temporaryHours.overrideType.temporaryOpen')
    },
    {
      value: OverrideType.ModifiedHours,
      label: t('store.temporaryHours.overrideType.modifiedHours')
    }
  ])

  // 5. 表单校验规则
  const formRules: FormRules = {
    dateRange: [
      {
        required: true,
        message: t('store.temporaryHours.rules.dateRequired'),
        trigger: 'change'
      }
    ],
    overrideType: [
      {
        required: true,
        message: t('store.temporaryHours.rules.typeRequired'),
        trigger: 'change'
      }
    ],
    timeRange: [
      {
        validator: (_rule, _value, callback) => {
          if (!form.isAllDay && (!form.timeRange || form.timeRange.length < 2)) {
            callback(new Error(t('store.temporaryHours.rules.timeRequired')))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
  }

  // 6. 数据加载
  const loadHolidays = async () => {
    if (!props.storeId) {
      holidays.value = []
      return
    }
    loading.value = true
    try {
      holidays.value = await fetchStoreHolidays(props.storeId)
    } finally {
      loading.value = false
    }
  }

  watch(
    () => props.storeId,
    () => {
      loadHolidays()
    },
    { immediate: true }
  )

  // 7. 辅助函数
  const formatDate = (dateStr: string) => dateStr?.split('T')[0] || ''
  const formatTime = (timeStr?: string) => timeStr?.substring(0, 5) || ''

  const getOverrideTypeLabel = (type: number) => {
    const option = overrideTypeOptions.value.find((item) => item.value === type)
    return option?.label || ''
  }
  const getOverrideTypeTagType = (type: number) => {
    switch (type) {
      case OverrideType.Closed:
        return 'danger'
      case OverrideType.TemporaryOpen:
        return 'success'
      case OverrideType.ModifiedHours:
        return 'warning'
      default:
        return 'info'
    }
  }

  // 8. 交互处理
  const resetForm = () => {
    form.dateRange = []
    form.isAllDay = true
    form.timeRange = []
    form.overrideType = OverrideType.Closed
    form.reason = ''
    editingId.value = null
    formRef.value?.clearValidate()
  }

  const handleAdd = () => {
    resetForm()
    isEdit.value = false
    dialogVisible.value = true
  }

  const handleEdit = (row: Api.Store.StoreHolidayDto) => {
    resetForm()
    isEdit.value = true
    editingId.value = row.id
    const startDate = formatDate(row.date)
    const endDate = row.endDate ? formatDate(row.endDate) : startDate
    form.dateRange = [startDate, endDate]
    form.isAllDay = row.isAllDay
    form.timeRange = row.startTime && row.endTime ? [row.startTime, row.endTime] : []
    form.overrideType = row.overrideType
    form.reason = row.reason || ''
    dialogVisible.value = true
  }

  const handleDelete = async (row: Api.Store.StoreHolidayDto) => {
    try {
      await ElMessageBox.confirm(t('store.temporaryHours.deleteConfirm'), t('common.warning'), {
        type: 'warning'
      })
    } catch {
      return
    }
    await fetchDeleteStoreHoliday(props.storeId, row.id)
    ElMessage.success(t('store.message.deleteSuccess'))
    loadHolidays()
  }

  const handleSubmit = async () => {
    if (!formRef.value) {
      return
    }
    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) {
      return
    }

    const payload: Api.Store.CreateStoreHolidayRequest = {
      date: form.dateRange[0],
      endDate: form.dateRange[1] !== form.dateRange[0] ? form.dateRange[1] : undefined,
      isAllDay: form.isAllDay,
      startTime: !form.isAllDay ? form.timeRange[0] : undefined,
      endTime: !form.isAllDay ? form.timeRange[1] : undefined,
      overrideType: form.overrideType,
      reason: form.reason?.trim() || undefined
    }

    submitting.value = true
    try {
      if (isEdit.value && editingId.value) {
        await fetchUpdateStoreHoliday(props.storeId, editingId.value, payload)
        ElMessage.success(t('store.message.updateSuccess'))
      } else {
        await fetchCreateStoreHoliday(props.storeId, payload)
        ElMessage.success(t('store.message.createSuccess'))
      }
      dialogVisible.value = false
      loadHolidays()
    } finally {
      submitting.value = false
    }
  }
</script>
