'use client'
import {useForm} from 'react-hook-form'
import Center from '@/components/composites/purchase/long/center'
import Right from '@/components/composites/purchase/long/right'
import {Form} from '@/components/ui/form'
import * as z from 'zod'
import {zodResolver} from '@hookform/resolvers/zod'
import {ProductItem} from '@/actions/product'

// 定义表单验证架构
const schema = z.object({
  type: z.enum(['1', '2']).default('2'),
  live: z.string(),
  quota: z.number().min(500, '购买数量不能少于 500 个'),
  expire: z.string(),
  daily_limit: z.number().min(100, '每日限额不能少于 100 个'),
  pay_type: z.enum(['wechat', 'alipay', 'balance']),
})

// 从架构中推断类型
export type Schema = z.infer<typeof schema>

export default function LongForm({skuList}: {skuList: ProductItem['skus']}) {
  if (!skuList) throw new Error('没有套餐数据')

  const map = new Map<string, string>()
  // const _modeList = new Set<string>()
  const _liveList = new Set<number>()
  const _expireList = new Set<number>()
  for (const sku of skuList) {
    const params = new URLSearchParams(sku.code)
    // _modeList.add(params.get('mode') || '')
    _liveList.add(Number(params.get('live')))
    _expireList.add(Number(params.get('expire')))
    map.set(sku.code, sku.price)
  }
  // const modeList = Array.from(_modeList).filter(Boolean)
  const liveList = Array.from(_liveList).filter(Boolean).map(String)
  const expireList = Array.from(_expireList).filter(Boolean).map(String)

  const form = useForm<Schema>({
    resolver: zodResolver(schema),
    defaultValues: {
      type: '2', // 默认为包量套餐
      live: liveList[0], // 分钟
      expire: '0', // 天
      quota: 500,
      daily_limit: 100,
      pay_type: 'balance', // 余额支付
    },
  })

  return (
    <Form form={form} className="flex flex-col lg:flex-row gap-4">
      <Center {...{liveList, map, expireList}}/>
      <Right/>
    </Form>
  )
}
