'use client'

import { useEffect, useState } from 'react'
import { AlertDialog, AlertDialogContent, AlertDialogTitle } from '@/components/ui/alert-dialog'
import { Button, IconButton } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import Image from 'next/image'
import { useBuyCreateImageCount } from '@/hooks/useUser'
import { useQueryClient } from '@tanstack/react-query'
import { userKeys, walletKeys } from '@/lib/query-keys'
import { toast } from 'sonner'
import { useUpdateWalletBalance } from '@/hooks/useWallet'
import { useSetAtom } from 'jotai'
import { isChargeDrawerOpenAtom } from '@/atoms/im'

interface GeneralBuyTimesDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onConfirm?: (quantity: number, totalPrice: number) => void
  pricePerTime?: number
  maxQuantity?: number
  minQuantity?: number
}

const GeneralBuyTimesDialog = ({
  open,
  onOpenChange,
  pricePerTime = 70,
  maxQuantity = 999,
  minQuantity = 1,
}: GeneralBuyTimesDialogProps) => {
  const [quantity, setQuantity] = useState(1)
  const [inputValue, setInputValue] = useState('1')
  const totalPrice = quantity * pricePerTime
  const [loading, setLoading] = useState(false)

  const queryClient = useQueryClient()
  const { checkSufficient } = useUpdateWalletBalance()
  const setIsChargeDrawerOpen = useSetAtom(isChargeDrawerOpenAtom)

  useEffect(() => {
    if (open) {
      setQuantity(10)
      setInputValue('10')
    }
  }, [open])

  const { mutateAsync: buyCreateImageCount } = useBuyCreateImageCount()

  const handleQuantityChange = (newQuantity: number) => {
    // 自动限制在最小值和最大值之间
    let finalQuantity: number
    if (newQuantity < minQuantity) {
      finalQuantity = minQuantity
    } else if (newQuantity > maxQuantity) {
      finalQuantity = maxQuantity
    } else {
      finalQuantity = newQuantity
    }

    setQuantity(finalQuantity)
    setInputValue(finalQuantity.toString())
  }

  const handleDecrease = () => {
    handleQuantityChange(quantity - 1)
  }

  const handleIncrease = () => {
    handleQuantityChange(quantity + 1)
  }

  const handleConfirm = async () => {
    if (!checkSufficient(totalPrice)) {
      setIsChargeDrawerOpen(true)
      return
    }

    setLoading(true)
    try {
      await buyCreateImageCount({ count: quantity })
      await queryClient.invalidateQueries({ queryKey: userKeys.albumCreateCount() })
      toast.success(`Creation times + ${quantity}`)
      onOpenChange(false)
      queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  const handleCancel = () => {
    onOpenChange(false)
  }

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent className="bg-surface-base-normal w-full max-w-[400px] rounded-2xl border-0 p-6">
        <AlertDialogTitle />
        {/* 头部区域 */}
        <div className="relative flex items-center justify-center px-10">
          {/* 中心图标 */}
          <div className="relative flex h-[148px] w-[148px] items-center justify-center">
            <Image
              src="/icons/buy-times.png"
              alt="Buy Generation Attempts"
              width={148}
              height={148}
            />
          </div>
        </div>

        {/* 标题 */}
        <div className="py-4">
          <h2 className="txt-title-l text-txt-primary-normal text-center">
            Buy Generation Attempts
          </h2>
        </div>

        {/* 价格区域 */}
        <div className="flex items-center justify-between px-0 py-3">
          <div className="txt-label-m text-txt-primary-normal">Price per attempt</div>
          <div className="flex items-center gap-1">
            <div className="relative h-4 w-4">
              <Image
                src="/icons/diamond.svg"
                alt="diamond"
                width={16}
                height={16}
                className="h-full w-full"
              />
            </div>
            <div className="text-txt-primary-normal flex items-center">
              <span className="txt-numMonotype-m">{pricePerTime}</span>
              {/* <span className="txt-label-l">/time</span> */}
            </div>
          </div>
        </div>

        {/* 数量选择区域 */}
        <div className="mt-4 flex items-center justify-between">
          <div className="txt-label-m text-txt-primary-normal">Quantity</div>
          <div className="flex items-center gap-2">
            {/* 减少按钮 */}
            <Button
              variant="tertiary"
              disabled={quantity <= minQuantity}
              className="!w-12 min-w-0 rounded-sm px-0"
              onClick={handleDecrease}
            >
              <i className="iconfont icon-reduce" />
            </Button>

            {/* 数量输入框 */}
            <div className="w-20">
              <Input
                value={inputValue}
                onChange={(e) => {
                  const value = e.target.value

                  // 如果输入为空，允许暂时为空
                  if (value === '') {
                    setInputValue('')
                    return
                  }

                  // 只能输入正整数
                  if (!/^\d+$/.test(value)) {
                    return
                  }

                  const numValue = Number(value)

                  // 更新输入值
                  setInputValue(Math.min(maxQuantity, Number(value)).toString())

                  // 实时更新数量（用于计算总价），但允许输入过程
                  if (numValue >= minQuantity && numValue <= maxQuantity) {
                    setQuantity(numValue)
                  } else if (numValue > maxQuantity) {
                    setQuantity(maxQuantity)
                  } else if (numValue < minQuantity && numValue > 0) {
                    // 输入过程中如果小于最小值但大于0，暂时保持输入值，但数量用最小值计算
                    setQuantity(minQuantity)
                  }
                }}
                onBlur={(e) => {
                  // 失去焦点时，确保值在有效范围内
                  const value = e.target.value
                  if (value === '' || Number(value) === 0 || Number(value) < minQuantity) {
                    setQuantity(minQuantity)
                    setInputValue(minQuantity.toString())
                  } else if (Number(value) > maxQuantity) {
                    setQuantity(maxQuantity)
                    setInputValue(maxQuantity.toString())
                  }
                }}
                size="large"
                className="txt-numMonotype-m text-center"
              />
            </div>

            {/* 增加按钮 */}
            <Button
              variant="tertiary"
              disabled={quantity >= maxQuantity}
              className="!w-12 min-w-0 rounded-sm px-0"
              onClick={handleIncrease}
            >
              <i className="iconfont icon-add" />
            </Button>
          </div>
        </div>

        {/* 分割线 */}
        <Separator className="bg-outline-normal my-4" />

        {/* 总价区域 */}
        <div className="flex items-center justify-between py-3">
          <div className="txt-label-m text-txt-primary-normal">Total</div>
          <div className="flex items-center gap-1">
            <div className="relative h-4 w-4">
              <Image
                src="/icons/diamond.svg"
                alt="diamond"
                width={16}
                height={16}
                className="h-full w-full"
              />
            </div>
            <span className="txt-numMonotype-m text-txt-primary-normal font-bold">
              {totalPrice}
            </span>
          </div>
        </div>

        {/* 按钮区域 */}
        <div className="flex items-center gap-4 pt-4">
          <Button onClick={handleCancel} variant="tertiary" block className="flex-1">
            Cancel
          </Button>
          <Button
            onClick={handleConfirm}
            variant="primary"
            block
            className="flex-1"
            loading={loading}
          >
            Purchase
          </Button>
        </div>
      </AlertDialogContent>
    </AlertDialog>
  )
}

export default GeneralBuyTimesDialog
