<template>
  <div class="flex flex-col gap-4">
    <ElCard shadow="never" v-loading="loading">
      <template #header>
        <div class="flex items-center justify-between">
          <span>{{ t('store.fee.title') }}</span>
          <ElButton type="primary" :loading="saving" @click="handleSave">
            {{ t('store.action.save') }}
          </ElButton>
        </div>
      </template>

      <ElForm :model="feeForm" label-width="100px" class="store-fee-form">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <div class="lg:border-r lg:border-gray-100 lg:pr-8">
            <!-- 1. 收取方式 -->
            <ElFormItem :label="t('store.fee.packagingMode.title')">
              <ElRadioGroup v-model="uiPackagingMode">
                <ElRadio label="ITEM" size="large">{{
                  t('store.fee.packagingMode.byItem')
                }}</ElRadio>
                <ElRadio label="ORDER" size="large">{{
                  t('store.fee.packagingMode.byOrder')
                }}</ElRadio>
              </ElRadioGroup>
            </ElFormItem>

            <!-- 2. 收费说明 (仅按订单收费显示) -->
            <div
              v-if="uiPackagingMode === 'ORDER'"
              class="ml-[100px] mb-6 p-4 bg-gray-50 rounded-lg border border-gray-100 text-sm text-gray-600"
            >
              <div class="font-medium mb-2 text-gray-900">{{
                t('store.fee.packagingHelp.title')
              }}</div>
              <ul class="list-disc list-inside space-y-1 pl-1">
                <li>{{ t('store.fee.packagingHelp.item1') }}</li>
                <li>{{ t('store.fee.packagingHelp.item2') }}</li>
                <li>{{ t('store.fee.packagingHelp.item3') }}</li>
              </ul>
            </div>

            <!-- 3. 收费规则 (仅按订单收费显示) -->
            <template v-if="uiPackagingMode === 'ORDER'">
              <ElFormItem :label="t('store.fee.packagingRule.title')">
                <ElRadioGroup v-model="uiOrderMode">
                  <ElRadio label="TIERED" size="large">{{
                    t('store.fee.packagingRule.tiered')
                  }}</ElRadio>
                  <ElRadio label="FIXED" size="large">{{
                    t('store.fee.packagingRule.fixed')
                  }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>

              <!-- 3.1 阶梯价表单 (Grid Layout) -->
              <div v-if="uiOrderMode === 'TIERED'" class="pl-[20px] mb-6">
                <div class="space-y-3">
                  <div
                    v-for="(tier, index) in packagingFeeTiers"
                    :key="index"
                    class="flex items-center"
                  >
                    <!-- Label: 折后价阶梯N -->
                    <div class="w-[110px] text-right pr-3 text-sm text-gray-500 shrink-0">
                      {{ t('store.fee.tier.label', { index: index + 1 }) }}
                      <el-tooltip v-if="index === 0" content="Tier 1 starts from 0">
                        <el-icon class="ml-1 translate-y-0.5 text-gray-400 cursor-help"
                          ><QuestionFilled
                        /></el-icon>
                      </el-tooltip>
                    </div>

                    <!-- Range Start -->
                    <div class="text-sm text-gray-900 font-medium w-[60px] text-right shrink-0">
                      {{ index === 0 ? '0' : (packagingFeeTiers[index - 1]?.maxPrice ?? 0) }}
                      {{ t('store.fee.tier.unit') }}
                    </div>

                    <!-- Separator -->
                    <div class="px-2 text-gray-400 shrink-0">-</div>

                    <!-- Range End (Input or Text) -->
                    <div class="w-[160px] shrink-0">
                      <template v-if="index < packagingFeeTiers.length - 1">
                        <div class="flex items-center">
                          <ElInputNumber
                            v-model="tier.maxPrice"
                            :min="
                              (index === 0 ? 0 : (packagingFeeTiers[index - 1]?.maxPrice ?? 0)) +
                              0.01
                            "
                            :controls="false"
                            :precision="2"
                            class="!w-[110px]"
                            :placeholder="t('store.fee.tier.inputPlaceholder')"
                          />
                          <span class="ml-2 text-sm text-gray-500">{{
                            t('store.fee.tier.unitInclude')
                          }}</span>
                        </div>
                      </template>
                      <template v-else>
                        <span class="text-sm text-gray-500 italic block py-1.5">
                          {{ t('store.fee.tier.limitInfinity') }}
                        </span>
                      </template>
                    </div>

                    <!-- Fee Label -->
                    <div class="w-[60px] text-right text-sm text-gray-500 px-2 shrink-0">
                      {{ t('store.fee.tier.fee') }}
                    </div>

                    <!-- Fee Input -->
                    <div class="flex items-center w-[140px] shrink-0">
                      <ElInputNumber
                        v-model="tier.fee"
                        :min="0"
                        :controls="false"
                        :precision="2"
                        class="!w-[110px]"
                      />
                      <span class="ml-2 text-sm text-gray-500">{{ t('store.fee.tier.unit') }}</span>
                    </div>

                    <!-- Delete Action -->
                    <div class="ml-2 w-[30px] flex justify-center shrink-0">
                      <ElButton
                        v-if="
                          packagingFeeTiers.length > 1 && index === packagingFeeTiers.length - 1
                        "
                        type="danger"
                        link
                        :icon="Delete"
                        @click="removeTier(index)"
                      />
                    </div>
                  </div>
                </div>

                <!-- Add Button -->
                <div class="pl-[110px] mt-3">
                  <ElButton
                    v-if="packagingFeeTiers.length < 10"
                    type="primary"
                    link
                    :icon="Plus"
                    @click="addTier"
                  >
                    {{ t('store.fee.tier.add', { current: packagingFeeTiers.length, max: 10 }) }}
                  </ElButton>
                </div>
              </div>

              <!-- 3.2 一口价表单 -->
              <ElFormItem
                v-if="uiOrderMode === 'FIXED'"
                :label="t('store.fee.fixedPackagingFee')"
                class="animate-fade-in"
              >
                <div class="flex items-center gap-2">
                  <ElInputNumber
                    v-model="feeForm.fixedPackagingFee"
                    class="!w-[180px]"
                    :min="0"
                    :controls="false"
                    :precision="2"
                  />
                  <span class="text-gray-500 text-sm">元</span>
                </div>
              </ElFormItem>
            </template>
          </div>
          <div>
            <!-- 4. 其他费用 -->
            <ElFormItem :label="t('store.fee.minimumOrderAmount')">
              <div class="flex items-center gap-2">
                <ElInputNumber
                  v-model="feeForm.minimumOrderAmount"
                  class="!w-[180px]"
                  :min="0"
                  :controls="false"
                  :precision="2"
                />
                <span class="text-gray-500 text-sm">元</span>
              </div>
            </ElFormItem>
            <ElFormItem :label="t('store.fee.deliveryFee')">
              <div class="flex items-center gap-2">
                <ElInputNumber
                  v-model="feeForm.deliveryFee"
                  class="!w-[180px]"
                  :min="0"
                  :controls="false"
                  :precision="2"
                />
                <span class="text-gray-500 text-sm">元</span>
              </div>
            </ElFormItem>
            <ElFormItem :label="t('store.fee.freeDeliveryThreshold')">
              <div class="flex items-center gap-2">
                <ElInputNumber
                  v-model="feeForm.freeDeliveryThreshold"
                  class="!w-[180px]"
                  :min="0"
                  :controls="false"
                  :precision="2"
                />
                <span class="text-gray-500 text-sm">元</span>
              </div>
            </ElFormItem>
          </div>
        </div>
      </ElForm>
    </ElCard>

    <!-- Preview Card (Minor style updates) -->
    <ElCard shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span>{{ t('store.fee.preview.title') }}</span>
          <ElButton type="primary" :loading="calculating" @click="handleCalculate">
            {{ t('store.fee.preview.action') }}
          </ElButton>
        </div>
      </template>
      <ElForm :model="calcForm" label-width="100px">
        <ElFormItem :label="t('store.fee.preview.orderAmount')">
          <ElInputNumber
            v-model="calcForm.orderAmount"
            class="w-full"
            :min="0"
            :controls="false"
            :precision="2"
          />
        </ElFormItem>
        <ElFormItem :label="t('store.fee.preview.itemCount')">
          <ElInputNumber
            v-model="calcForm.itemCount"
            class="w-full"
            :min="0"
            :controls="false"
            :precision="0"
          />
        </ElFormItem>
      </ElForm>
      <div class="flex items-center justify-between">
        <span class="text-sm text-gray-500">{{ t('store.fee.preview.itemsTitle') }}</span>
        <ElButton type="primary" link @click="handleAddItem">
          {{ t('store.fee.preview.addItem') }}
        </ElButton>
      </div>
      <ElTable :data="calcItems" border size="small" class="mt-2">
        <ElTableColumn :label="t('store.fee.preview.skuId')" min-width="120">
          <template #default="{ row }">
            <ElInput v-model="row.skuId" />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('store.fee.preview.quantity')" width="100">
          <template #default="{ row }">
            <ElInputNumber v-model="row.quantity" class="w-full" :min="1" :controls="false" />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('store.fee.preview.packagingFee')" width="140">
          <template #default="{ row }">
            <ElInputNumber
              v-model="row.packagingFee"
              class="w-full"
              :min="0"
              :controls="false"
              :precision="2"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('common.action')" width="80">
          <template #default="{ $index }">
            <ElButton link type="danger" @click="handleRemoveItem($index)">
              {{ t('store.action.delete') }}
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>

      <ElAlert
        v-if="calcResult?.message"
        type="info"
        :title="calcResult.message"
        show-icon
        class="mt-4"
      />

      <ElDescriptions v-if="calcResult" :column="2" border class="mt-4">
        <ElDescriptionsItem :label="t('store.fee.preview.result.totalAmount')">
          {{ calcResult.totalAmount }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('store.fee.preview.result.totalFee')">
          {{ calcResult.totalFee }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('store.fee.preview.result.deliveryFee')">
          {{ calcResult.deliveryFee }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('store.fee.preview.result.packagingFee')">
          {{ calcResult.packagingFee }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('store.fee.preview.result.meetsMinimum')">
          {{ calcResult.meetsMinimum ? t('common.yes') : t('common.no') }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('store.fee.preview.result.shortfall')">
          {{ calcResult.shortfall ?? '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElAlert,
    ElButton,
    ElCard,
    ElDescriptions,
    ElDescriptionsItem,
    ElForm,
    ElFormItem,
    ElIcon,
    ElInput,
    ElInputNumber,
    ElMessage,
    ElRadio,
    ElRadioGroup,
    ElTable,
    ElTableColumn,
    ElTooltip
  } from 'element-plus'
  import { QuestionFilled, Plus, Delete } from '@element-plus/icons-vue'
  import { fetchCalculateStoreFee, fetchStoreFee, fetchUpdateStoreFee } from '@/api/store'
  import { PackagingFeeMode } from '@/enums/PackagingFeeMode'

  defineOptions({ name: 'StoreFeePanel' })

  interface FeeFormState {
    minimumOrderAmount: number
    deliveryFee: number
    packagingFeeMode: PackagingFeeMode
    fixedPackagingFee: number
    freeDeliveryThreshold?: number
  }

  interface PackagingFeeTier {
    minPrice: number
    maxPrice?: number // undefined implies Infinity
    fee: number
  }

  interface FeeItemState {
    skuId: string
    quantity: number
    packagingFee: number
  }

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

  // 2. 费用配置
  const loading = ref(false)
  const saving = ref(false)

  // UI States
  const uiPackagingMode = ref<'ITEM' | 'ORDER'>('ITEM')
  const uiOrderMode = ref<'FIXED' | 'TIERED'>('FIXED')
  const packagingFeeTiers = ref<PackagingFeeTier[]>([{ minPrice: 0, maxPrice: undefined, fee: 0 }])

  const feeForm = ref<FeeFormState>({
    minimumOrderAmount: 0,
    deliveryFee: 0,
    packagingFeeMode: PackagingFeeMode.Fixed,
    fixedPackagingFee: 0,
    freeDeliveryThreshold: undefined
  })

  // 3. 预览计算
  const calculating = ref(false)
  const calcForm = ref({ orderAmount: 0, itemCount: 0 })
  const calcItems = ref<FeeItemState[]>([])
  const calcResult = ref<Api.Store.StoreFeeCalculationResultDto | null>(null)

  // 4. 初始化加载
  const loadFee = async () => {
    if (!props.storeId) {
      return
    }
    loading.value = true
    try {
      const data = await fetchStoreFee(props.storeId)

      // Map API data to UI state
      feeForm.value = {
        minimumOrderAmount: data.minimumOrderAmount ?? 0,
        deliveryFee: data.deliveryFee ?? 0,
        packagingFeeMode: data.packagingFeeMode,
        fixedPackagingFee: data.fixedPackagingFee ?? 0,
        freeDeliveryThreshold: data.freeDeliveryThreshold ?? undefined
      }

      // Initialize UI Modes
      if (data.packagingFeeMode === PackagingFeeMode.PerItem) {
        uiPackagingMode.value = 'ITEM'
      } else {
        uiPackagingMode.value = 'ORDER'
      }
      // Note: Backend doesn't support TIERED yet, so default to FIXED
      uiOrderMode.value = 'FIXED'
    } finally {
      loading.value = false
    }
  }

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

  // 5. 阶梯操作
  const addTier = () => {
    // Find the last tier
    const last = packagingFeeTiers.value[packagingFeeTiers.value.length - 1]

    // If last tier is infinite, we can't extend from it unless we set a limit on it first
    // But in our UI, the 'last tier' is always infinite. To add a tier, we split the LAST one.
    // Logic:
    // Current: 0 -> Infinity
    // Add ->
    // Tier 1: 0 -> (User Input, e.g. 10)
    // Tier 2: 10 -> Infinity

    // Step 1: Set a default maxPrice for current last tier if it's undefined
    if (last.maxPrice === undefined) {
      // Default gap 10?
      const start = last.minPrice
      last.maxPrice = start + 10
    }

    // Step 2: Add new infinite tier
    packagingFeeTiers.value.push({
      minPrice: last.maxPrice as number,
      maxPrice: undefined,
      fee: 0
    })
  }

  const removeTier = (index: number) => {
    // Can only remove the last tier, and merge it into previous
    if (index === packagingFeeTiers.value.length - 1 && index > 0) {
      packagingFeeTiers.value.pop()
      // Reset the new last tier to infinite
      packagingFeeTiers.value[packagingFeeTiers.value.length - 1].maxPrice = undefined
    }
  }

  // 6. 操作处理
  const handleSave = async () => {
    if (!props.storeId) {
      return
    }
    saving.value = true

    // Map UI State back to API Mode
    let apiMode = PackagingFeeMode.Fixed
    if (uiPackagingMode.value === 'ITEM') {
      apiMode = PackagingFeeMode.PerItem
    }

    // Note: If TIERED is selected, we technically can't save it to backend yet.
    // For now, we only save the 'Fixed Fee' part if in FIXED mode.
    // User said "don't worry about API", so we simply proceed.

    try {
      await fetchUpdateStoreFee(props.storeId, {
        minimumOrderAmount: feeForm.value.minimumOrderAmount,
        deliveryFee: feeForm.value.deliveryFee,
        packagingFeeMode: apiMode,
        fixedPackagingFee: feeForm.value.fixedPackagingFee,
        freeDeliveryThreshold: feeForm.value.freeDeliveryThreshold
      })

      // Log Tier Data for debugging/future backend implementation
      if (uiPackagingMode.value === 'ORDER' && uiOrderMode.value === 'TIERED') {
        console.log('Saving Tiered Config (Frontend Only):', packagingFeeTiers.value)
      }

      ElMessage.success(t('store.message.updateSuccess'))
      loadFee()
    } finally {
      saving.value = false
    }
  }

  // ... existing preview logic ...
  const handleAddItem = () => {
    calcItems.value.push({ skuId: '', quantity: 1, packagingFee: 0 })
  }
  const handleRemoveItem = (index: number) => {
    calcItems.value.splice(index, 1)
  }
  const handleCalculate = async () => {
    if (!props.storeId) {
      return
    }
    calculating.value = true
    try {
      calcResult.value = await fetchCalculateStoreFee(props.storeId, {
        orderAmount: calcForm.value.orderAmount,
        itemCount: calcForm.value.itemCount || undefined,
        items: calcItems.value.map((item) => ({
          skuId: item.skuId,
          quantity: item.quantity,
          packagingFee: item.packagingFee
        }))
      })
    } finally {
      calculating.value = false
    }
  }
</script>

<style scoped>
  .store-fee-form :deep(.el-input-number .el-input__inner) {
    padding-right: 50px !important;
    text-align: left;
  }

  /* Hide input number controls */
  .store-fee-form :deep(.el-input-number__decrease),
  .store-fee-form :deep(.el-input-number__increase) {
    display: none;
  }

  .store-fee-form :deep(.el-input-number .el-input__wrapper) {
    padding-right: 0 !important;
    padding-left: 15px !important;
  }
</style>
