'use client'
import {FormField} from '@/components/ui/form'
import {RadioGroup} from '@/components/ui/radio-group'
import FormOption from '@/components/composites/purchase/option'
import {Schema} from '@/components/composites/purchase/long/form'
import {useEffect, useMemo} from 'react'
import {useFormContext, useWatch} from 'react-hook-form'
import {Card} from '@/components/ui/card'
import {BillingMethodField} from '../shared/billing-method-field'
import {FeatureList} from '../shared/feature-list'
import {NumberStepperField} from '../shared/number-stepper-field'
import {getAvailablePurchaseExpires, getAvailablePurchaseLives, getPurchaseSkuCountMin, getPurchaseSkuPrice, hasPurchaseSku, PurchaseSkuData} from '../shared/sku'

export default function Center({skuData}: {
  skuData: PurchaseSkuData
}) {
  const {setValue, getValues} = useFormContext<Schema>()
  const type = useWatch<Schema>({name: 'type'}) as Schema['type']
  const live = useWatch<Schema>({name: 'live'}) as Schema['live']
  const expire = useWatch<Schema>({name: 'expire'}) as Schema['expire']
  const {modeList, priceMap} = skuData
  const liveList = type === '1'
    ? getAvailablePurchaseLives(skuData, {mode: type, expire})
    : getAvailablePurchaseLives(skuData, {mode: type})
  const expireList = type === '1'
    ? getAvailablePurchaseExpires(skuData, {mode: type, live})
    : []

  const currentCountMin = useMemo(() => {
    if (!type || !live) return 0
    const expireValue = type === '1' ? expire : '0'
    const countMin = getPurchaseSkuCountMin(skuData, {
      mode: type,
      live,
      expire: expireValue,
    })
    return countMin
  }, [type, live, expire, skuData])

  useEffect(() => {
    if (currentCountMin <= 0) return
    const targetField = type === '1' ? 'daily_limit' : 'quota'
    const currentValue = getValues(targetField)
    if (currentValue !== currentCountMin) {
      setValue(targetField, currentCountMin, {shouldValidate: true})
    }
  }, [currentCountMin, type, setValue, getValues])

  useEffect(() => {
    const nextType = modeList.includes(type) ? type : modeList[0]
    if (!nextType) {
      return
    }
    if (nextType !== type) {
      setValue('type', nextType)
      return
    }
    const nextLiveList = nextType === '1'
      ? getAvailablePurchaseLives(skuData, {mode: nextType, expire})
      : getAvailablePurchaseLives(skuData, {mode: nextType})
    const nextLive = nextLiveList.includes(live) ? live : nextLiveList[0]

    if (nextLive && nextLive !== live) {
      setValue('live', nextLive)
      return
    }

    if (nextType === '2') {
      if (expire !== '0') {
        setValue('expire', '0')
      }
      return
    }

    const nextExpireList = getAvailablePurchaseExpires(skuData, {mode: nextType, live: nextLive})
    if (!nextExpireList.includes(expire) && nextExpireList[0]) {
      setValue('expire', nextExpireList[0])
    }
  }, [expire, live, modeList, setValue, skuData, type])

  return (
    <Card className="flex-auto p-6 flex flex-col gap-6 relative">
      <BillingMethodField modeList={modeList} timeDailyLimit={100}/>

      {/* IP 时效 */}
      <FormField<Schema, 'live'>
        name="live"
        label="IP 有效时间"
        description="提取出的 IP 可用时间"
      >
        {({id, field}) => (
          <RadioGroup
            id={id}
            value={field.value}
            onValueChange={(value) => {
              field.onChange(value)

              if (type !== '1') {
                return
              }

              const nextExpireList = getAvailablePurchaseExpires(skuData, {mode: type, live: value})
              if (!nextExpireList.includes(expire) && nextExpireList[0]) {
                setValue('expire', nextExpireList[0])
              }
            }}
            className="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-4">
            {liveList.map((live) => {
              const priceExpire = type === '1' && !hasPurchaseSku(skuData, {mode: type, live, expire})
                ? getAvailablePurchaseExpires(skuData, {mode: type, live})[0] || '0'
                : String(expire)
              const price = getPurchaseSkuPrice(priceMap, {
                mode: type,
                live,
                expire: priceExpire,
              })
              return (
                <FormOption
                  key={live}
                  id={`${id}-${live}`}
                  value={live}
                  label={`${Number(live) / 60} 小时`}
                  description={price && `￥${price}/IP`}
                  compare={field.value}
                />
              )
            })}
          </RadioGroup>
        )}
      </FormField>

      {/* 套餐时效 */}
      {type === '1' && (
        <FormField name="expire" label="套餐有效时间" description="有效时间内可用于提取 IP">
          {({id, field}) => (
            <RadioGroup
              id={id}
              value={field.value}
              onValueChange={(value) => {
                field.onChange(value)

                const nextLiveList = getAvailablePurchaseLives(skuData, {mode: type, expire: value})
                if (!nextLiveList.includes(live) && nextLiveList[0]) {
                  setValue('live', nextLiveList[0])
                }
              }}
              className="flex gap-4 flex-wrap">
              {expireList.map(day => (
                <FormOption
                  key={day}
                  id={`${id}-${day}`}
                  value={day}
                  label={`${day} 天`}
                  compare={field.value}
                />
              ))}
            </RadioGroup>
          )}
        </FormField>
      )}

      {/* 每日提取上限/购买数量 */}
      {type === '1' ? (
        <NumberStepperField
          name="daily_limit"
          label="IP 每日提取上限"
          description="本套餐每日可提取 IP 的最大数量"
          min={currentCountMin}
          step={100}
        />
      ) : (
        <NumberStepperField
          name="quota"
          label="IP 总提取上限"
          description="本套餐总计可提取 IP 的最大数量"
          min={currentCountMin}
          step={100}
        />
      )}

      <FeatureList/>
    </Card>
  )
}
