'use client'
import {useForm} from 'react-hook-form'
import Center from '@/components/composites/purchase/long/center'
import {Form} from '@/components/ui/form'
import * as z from 'zod'
import {zodResolver} from '@hookform/resolvers/zod'
import {ProductItem} from '@/actions/product'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, parsePurchaseSkuList} from '../shared/sku'
import {PurchaseSidePanel} from '../shared/side-panel'

const schema = z.object({
  type: z.enum(['1', '2']).default('2'),
  live: z.string(),
  quota: z.number().min(1, '购买数量不能少于 1 个'),
  expire: z.string(),
  daily_limit: z.number().min(1, '每日限额不能少于 1 个'),
  pay_type: z.enum(['wechat', 'alipay', 'balance']),
})
export type Schema = z.infer<typeof schema>

export default function LongForm({skuList}: {skuList: ProductItem['skus']}) {
  const skuData = parsePurchaseSkuList('long', skuList)
  const defaultMode = skuData.modeList.includes('2') ? '2' : '1'
  const defaultLive = getAvailablePurchaseLives(skuData, {mode: defaultMode})[0] || ''
  const defaultExpire = defaultMode === '1'
    ? getAvailablePurchaseExpires(skuData, {mode: defaultMode, live: defaultLive})[0] || '0'
    : '0'
  const defaultCountMin = getPurchaseSkuCountMin(skuData, {
    mode: defaultMode,
    live: defaultLive,
    expire: defaultExpire,
  })

  const form = useForm<Schema>({
    resolver: zodResolver(schema),
    defaultValues: {
      type: defaultMode,
      live: defaultLive,
      expire: defaultExpire,
      quota: defaultCountMin,
      daily_limit: defaultCountMin,
      pay_type: 'balance', // 余额支付
    },
  })

  return (
    <Form form={form} className="flex flex-col lg:flex-row gap-4">
      <Center skuData={skuData}/>
      <PurchaseSidePanel kind="long"/>
    </Form>
  )
}
