'use client'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '../ui/alert-dialog'
import { IconButton, Button } from '../ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'
import { Input } from '../ui/input'
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form'
import Image from 'next/image'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'
import Decimal from 'decimal.js'

export interface AlbumPriceFormData {
  unlockMethod: 'pay' | 'free'
  price?: string
}

const schema = z
  .object({
    unlockMethod: z.enum(['pay', 'free']),
    price: z.string().optional(),
  })
  .refine(
    (data) => {
      // 如果选择了 "pay"，price 必须填写且有效
      if (data.unlockMethod === 'pay') {
        if (!data.price || data.price.trim() === '') {
          return false
        }
        if (Number(data.price) < 20) {
          return false
        }
      }
      return true
    },
    {
      message: 'At least 20 diamonds',
      path: ['price'],
    }
  )

interface AlbumPriceSettingProps {
  defaultUnlockPrice?: number
  onConfirm: (data: AlbumPriceFormData) => Promise<void>
  children?: React.ReactNode
}

const AlbumPriceSetting = ({ defaultUnlockPrice, onConfirm, children }: AlbumPriceSettingProps) => {
  const [isOpen, setIsOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(false)

  console.log('defaultUnlockPrice', defaultUnlockPrice)

  useEffect(() => {
    if (isOpen) {
      if (defaultUnlockPrice === undefined) {
        form.setValue('unlockMethod', 'pay')
        form.setValue('price', '20')
        return
      }
      if (defaultUnlockPrice) {
        form.setValue('unlockMethod', 'pay')
        form.setValue('price', new Decimal(defaultUnlockPrice).div(100).toString())
      } else {
        form.setValue('unlockMethod', 'free')
        form.setValue('price', '')
      }
    }
  }, [isOpen, defaultUnlockPrice])

  const form = useForm<AlbumPriceFormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      unlockMethod: 'pay',
      price: '',
    },
  })
  const unlockMethod = form.watch('unlockMethod')

  useEffect(() => {
    if (unlockMethod === 'free') {
      const priceValue = form.getValues('price')
      if (!priceValue) {
        form.setValue('price', '20')
      }
    }
  }, [unlockMethod])

  const handleSubmit = async (data: AlbumPriceFormData) => {
    setIsLoading(true)
    try {
      console.log('保存数据:', data)
      const result = {
        unlockMethod: data.unlockMethod,
        price: data.unlockMethod === 'pay' ? data.price : undefined,
      }
      await onConfirm(result)
      setIsOpen(false)
      form.reset()
    } catch (error) {
      console.error('保存失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleCancel = () => {
    setIsOpen(false)
    form.reset()
  }

  return (
    <AlertDialog open={isOpen} onOpenChange={setIsOpen}>
      <AlertDialogTrigger asChild>
        {children || (
          <IconButton variant="tertiary" size="small">
            <i className="iconfont icon-icon-setting" />
          </IconButton>
        )}
      </AlertDialogTrigger>
      <AlertDialogContent className="bg-surface-base-normal w-[400px] rounded-2xl p-6">
        <AlertDialogHeader>
          <AlertDialogTitle className="txt-title-l text-txt-primary-normal pl-10 text-center">
            How to Unlock
          </AlertDialogTitle>
        </AlertDialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            <AlertDialogDescription asChild>
              <div className="space-y-6">
                {/* 方法选择器 */}
                <FormField
                  control={form.control}
                  name="unlockMethod"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="txt-label-m text-txt-primary-normal">
                        <div className="flex items-center gap-1">
                          <div>How to Unlock</div>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <IconButton iconfont="icon-question" variant="tertiary" size="mini" />
                            </TooltipTrigger>
                            <TooltipContent className="max-w-[300px]">
                              <div>
                                <p className="break-words">
                                  Users can unlock your character's images, giving you a share of
                                  the revenue.
                                </p>
                                <p className="break-words">
                                  CrushLevel keeps 20% of each image's sales as a service fee.
                                </p>
                                <p className="break-words">
                                  Offering a few free images can encourage users to interact with
                                  your character.
                                </p>
                              </div>
                            </TooltipContent>
                          </Tooltip>
                        </div>
                      </FormLabel>
                      <FormControl>
                        <Select value={field.value} onValueChange={field.onChange}>
                          <SelectTrigger className="w-full">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="pay">Paid Unlock</SelectItem>
                            <SelectItem value="free">Free</SelectItem>
                          </SelectContent>
                        </Select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* 价格输入框 */}
                {form.watch('unlockMethod') === 'pay' && (
                  <FormField
                    control={form.control}
                    name="price"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="txt-label-m text-txt-primary-normal">
                          Unlock Price
                        </FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            value={field.value || ''}
                            type="text"
                            placeholder="20~9999"
                            onInput={(e) => {
                              const target = e.target as HTMLInputElement
                              // 只允许输入数字
                              let value = target.value.replace(/[^0-9]/g, '')

                              // 如果为空，允许继续输入
                              if (value === '') {
                                target.value = ''
                                field.onChange('')
                                return
                              }

                              // 转换为数字并限制范围
                              const numValue = parseInt(value)
                              if (numValue > 99999) {
                                value = '99999'
                              }

                              target.value = value
                              field.onChange(value)
                            }}
                            prefixIcon={
                              <div className="flex items-center justify-center p-1">
                                <Image
                                  src="/icons/diamond.svg"
                                  alt="Diamond"
                                  width={16}
                                  height={16}
                                />
                              </div>
                            }
                            error={!!form.formState.errors.price}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>
            </AlertDialogDescription>

            <AlertDialogFooter className="flex gap-4 pt-4">
              <Button
                type="button"
                variant="tertiary"
                size="large"
                className="flex-1"
                onClick={handleCancel}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                size="large"
                className="flex-1"
                loading={isLoading}
              >
                Confirm
              </Button>
            </AlertDialogFooter>
          </form>
        </Form>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export default AlbumPriceSetting
