import { useEffect, useState } from "react"
import { useLocation, useNavigate } from "react-router-dom"
import { toast } from "sonner"
import { type CreateOrderRequest, createOrder } from "@/api/order"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import Wrap from "@/components/wrap"
import type { Product } from "@/lib/models/product"
import { cn } from "@/lib/utils"
import alipay from "../_assets/alipay.svg"
import balance from "../_assets/balance.svg"
import wechat from "../_assets/wechat.svg"

// ============ 工具函数 ============
function randomChars(length: number): string {
  const chars = "abcdefghijklmnopqrstuvwxyz"
  let result = ""
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

function randomDigits(length: number): string {
  let result = ""
  for (let i = 0; i < length; i++) {
    result += Math.floor(Math.random() * 10).toString()
  }
  return result
}

// ============ 模式切换 Tab ============
function ModeTabs({
  mode,
  onModeChange,
}: {
  mode: "single" | "batch"
  onModeChange: (mode: "single" | "batch") => void
}) {
  return (
    <div className="flex bg-gray-50 rounded-xl p-1 w-48">
      <button
        className={cn(
          "flex-1 py-2 text-sm font-medium rounded-lg transition-all cursor-pointer",
          mode === "single"
            ? "bg-white text-blue-600 shadow-sm"
            : "text-gray-500 hover:text-gray-700",
        )}
        onClick={() => onModeChange("single")}
      >
        单个注册
      </button>
      <button
        className={cn(
          "flex-1 py-2 text-sm font-medium rounded-lg transition-all cursor-pointer",
          mode === "batch"
            ? "bg-white text-blue-600 shadow-sm"
            : "text-gray-500 hover:text-gray-700",
        )}
        onClick={() => onModeChange("batch")}
      >
        批量注册
      </button>
    </div>
  )
}

// ============ 连接设备数选择器 ============
function ConnectCountSelector({
  value,
  onChange,
  label,
  hint,
  disabled,
}: {
  value: number
  onChange: (value: number) => void
  label: string
  hint?: string
  disabled?: boolean
}) {
  return (
    <div className="flex items-center gap-6">
      <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
        {label}：
      </Label>
      <div className="flex items-center gap-4 flex-1">
        <Button
          variant="outline"
          size="icon"
          className="h-8 w-8 rounded-full"
          disabled={disabled || value <= 1}
          onClick={() => onChange(Math.max(1, value - 1))}
        >
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M20 12H4"
            />
          </svg>
        </Button>
        <Input
          type="number"
          min={1}
          value={value}
          disabled={disabled}
          onChange={e => {
            const parsed = Number.parseInt(e.target.value, 10)
            if (!Number.isNaN(parsed)) onChange(Math.max(1, parsed))
          }}
          className="w-20 h-8 text-center text-lg font-semibold text-gray-700"
        />
        <Button
          variant="outline"
          size="icon"
          className="h-8 w-8 rounded-full"
          disabled={disabled}
          onClick={() => onChange(value + 1)}
        >
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 4v16m8-8H4"
            />
          </svg>
        </Button>
        {hint && <span className="text-xs text-gray-400">{hint}</span>}
      </div>
    </div>
  )
}

// ============ 优惠券选择器 ============
function CouponSelector() {
  return (
    <div className="flex items-center gap-6">
      <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
        选择优惠券：
      </Label>
      <Select>
        <SelectTrigger className="h-10 rounded-xl border-gray-200 flex-1 max-w-xs">
          <SelectValue placeholder="请选择优惠券" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="none">暂无可用优惠券</SelectItem>
        </SelectContent>
      </Select>
      <span className="text-xs text-gray-400 whitespace-nowrap">
        淘宝每次下单获得优惠券
      </span>
    </div>
  )
}

// ============ 批量注册说明 ============
function BatchInfo() {
  return (
    <div className="flex items-start gap-6">
      <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28 pt-1">
        说明：
      </Label>
      <div className="flex-1 text-sm text-gray-600 leading-relaxed p-2 bg-blue-50/70 rounded-xl border border-blue-100">
        <p>
          批量注册的账号会使用【账号前缀】+【开始数】+【个数】顺序进行注册，
        </p>
        <p className="mt-1">
          如：注册账号前缀为【user】开始数为【2】个数为【10】，则注册的账号为：
          <span className="text-blue-600 font-medium">
            {" "}
            user2，user3，user4，....user11
          </span>
        </p>
      </div>
    </div>
  )
}

// ============ 主页面 ============
export default function BuyPage() {
  const location = useLocation()
  const navigate = useNavigate()
  const product = location.state?.product as Product | undefined

  // 模式
  const [mode, setMode] = useState<"single" | "batch">("single")

  // 单个注册
  const [account, setAccount] = useState("")
  const [pwd, setPwd] = useState("")
  const [connectCount, setConnectCount] = useState(1)

  // 批量注册
  const [batchAccount, setBatchAccount] = useState("")
  const [batchPwd, setBatchPwd] = useState("")
  const [batchStart, setBatchStart] = useState(1)
  const [batchCount, setBatchCount] = useState(1)
  const [batchConnectCount, setBatchConnectCount] = useState(1)

  const [payType, setPayType] = useState("100")
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (!product) {
      navigate("/product", { replace: true })
      return
    }
    const acct = randomChars(2) + randomDigits(4)
    const pw = randomDigits(3)
    setAccount(acct)
    setPwd(pw)
    setBatchAccount(randomChars(3))
    setBatchPwd(pw)
  }, [navigate, product])

  if (!product) return null

  const packageId = Number(product.id)
  const isTest = product.isTest ?? false
  const isDayCard = product.card === "天"
  // 天卡首单（0.1元）连接数固定为1；大于0.1元的天卡连接数可增减、手输入
  const isFirstOrderDayCard = isDayCard && product.price <= 0.1

  const displayConnectCount = isFirstOrderDayCard ? 1 : connectCount

  const clampMinPrice = (total: number, count: number): number => {
    if (
      !isFirstOrderDayCard &&
      !isTest &&
      product.minPrice !== undefined &&
      product.minPrice > 0
    ) {
      const minCost = product.minPrice * count
      if (total < minCost) return minCost
    }
    return total
  }

  const singleTotal = clampMinPrice(
    product.price * displayConnectCount,
    displayConnectCount,
  )
  const batchTotal = clampMinPrice(
    product.price * batchConnectCount * batchCount,
    batchConnectCount * batchCount,
  )
  const total = mode === "single" ? singleTotal : batchTotal

  // 批量预览
  const batchPreview = (() => {
    if (!batchAccount) return ""
    const end = batchStart + batchCount - 1
    if (batchCount <= 4) {
      const items: string[] = []
      for (let i = batchStart; i <= end; i++) {
        items.push(`${batchAccount}${i}`)
      }
      return items.join(", ")
    }
    return `${batchAccount}${batchStart}, ${batchAccount}${batchStart + 1}, ${batchAccount}${batchStart + 2}...${batchAccount}${end}`
  })()

  const handlePay = async () => {
    if (mode === "single") {
      if (!account.trim() || !pwd.trim()) {
        toast.error("账号和密码不能为空")
        return
      }
    } else {
      if (!batchAccount.trim() || !batchPwd.trim()) {
        toast.error("账号前缀和密码不能为空")
        return
      }
      if (batchCount > 500) {
        toast.error("一次最多注册500个")
        return
      }
    }

    setSubmitting(true)
    try {
      const oPayType = Number(payType)
      const useBalance = oPayType === 1 ? 1 : 0
      const payChannel = oPayType === 70 ? 30 : 50

      const params: CreateOrderRequest = {
        PackageId: packageId,
        OrderType: mode === "single" ? 1 : 2,
        Account: mode === "single" ? account.trim() : batchAccount.trim(),
        Pwd: mode === "single" ? pwd.trim() : batchPwd.trim(),
        ConnectCount:
          mode === "single" ? displayConnectCount : batchConnectCount,
        CouponId: 0,
        UseAccountAmount: useBalance,
        OPayType: oPayType,
        PayChannel: payChannel,
        Price: product.price,
        ...(mode === "batch" && {
          MinPostfix: batchStart,
          MaxPostfix: batchCount,
        }),
      }

      const result = await createOrder(params)

      if (result.success) {
        toast.success("购买成功！")
      } else {
        toast.error(result.message)
      }
    } catch {
      toast.error("网络错误，请重试")
    } finally {
      setSubmitting(false)
    }
  }

  const handleBack = () => navigate(-1)

  // 天卡首单(0.1元)不显示批量注册；天卡>0.1元时显示（juipnet：应付款!=0.1时显示批量tab）
  const showTabs = !isTest && !isFirstOrderDayCard

  return (
    <Wrap className="bg-white min-h-screen flex items-start justify-center pt-16">
      <div className="w-full max-w-2xl px-8">
        {/* 标题 */}
        <div className="text-center mb-6 space-y-2">
          <h4 className="text-2xl font-bold">
            <span className="text-gray-800">{product.title}</span>
            <span className="text-orange-500 ml-2">¥{total.toFixed(2)}</span>
          </h4>
          <p className="text-sm text-amber-600">
            请务必选好所需物品，换货会产生费用
          </p>
          {isDayCard && (
            <p className="text-sm text-amber-600">天卡不支持退款，请谨慎购买</p>
          )}
        </div>

        {/* Tab 切换 */}
        {showTabs && (
          <div className="flex justify-center mb-3">
            <ModeTabs mode={mode} onModeChange={setMode} />
          </div>
        )}

        <div className="space-y-5 mb-20">
          {mode === "single" ? (
            // ====== 单个注册 ======
            <>
              {/* IP产品账号 */}
              <div className="flex items-center gap-6">
                <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                  IP产品账号：
                </Label>
                <Input
                  value={account}
                  onChange={e => setAccount(e.target.value)}
                  placeholder="4-10位字母或数字"
                  className="h-10 rounded-xl border-gray-200 flex-1"
                />
                <span className="text-xs text-gray-400 whitespace-nowrap">
                  4至10位字母或数字或组合
                </span>
              </div>

              {/* IP产品密码 */}
              <div className="flex items-center gap-6">
                <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                  IP产品密码：
                </Label>
                <Input
                  value={pwd}
                  onChange={e => setPwd(e.target.value)}
                  placeholder="1-10位字母或数字"
                  className="h-10 rounded-xl border-gray-200 flex-1"
                />
                <span className="text-xs text-gray-400 whitespace-nowrap">
                  1至10位字母或数字或组合
                </span>
              </div>

              {/* 连接设备数：测试卡不显示；天卡首单(0.1元)显示但禁用 */}
              {!isTest && (
                <ConnectCountSelector
                  value={displayConnectCount}
                  onChange={setConnectCount}
                  label="连接设备数"
                  hint="一个账号可同时在线设备数"
                  disabled={isFirstOrderDayCard}
                />
              )}
            </>
          ) : (
            // ====== 批量注册 ======
            <>
              {/* 批量说明 */}
              <BatchInfo />

              {/* IP账号前缀 */}
              <div className="flex items-center gap-6">
                <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                  IP账号前缀：
                </Label>
                <Input
                  value={batchAccount}
                  onChange={e => setBatchAccount(e.target.value)}
                  placeholder="3-8位字母或数字"
                  className="h-10 rounded-xl border-gray-200 flex-1"
                />
                <span className="text-xs text-gray-400 whitespace-nowrap">
                  3至8位字母或数字或组合
                </span>
              </div>

              {/* 开始号 */}
              <div className="flex items-center gap-6">
                <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                  开始号：
                </Label>
                <Input
                  type="number"
                  value={batchStart}
                  onChange={e =>
                    setBatchStart(Number.parseInt(e.target.value, 10) || 1)
                  }
                  className="h-10 rounded-xl border-gray-200 flex-1 max-w-32"
                />
                <span className="text-xs text-gray-400">
                  本批次账号的起始账号
                </span>
              </div>

              {/* 注册个数 */}
              <div className="flex items-center gap-6">
                <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                  注册个数：
                </Label>
                <Input
                  type="number"
                  value={batchCount}
                  onChange={e =>
                    setBatchCount(
                      Math.min(500, Number.parseInt(e.target.value, 10) || 1),
                    )
                  }
                  className="h-10 rounded-xl border-gray-200 flex-1 max-w-32"
                />
              </div>

              {/* 账号预览 */}
              {batchPreview && (
                <div className="flex items-center gap-6">
                  <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                    即将生成的账号：
                  </Label>
                  <span className="text-sm text-gray-700 font-medium">
                    {batchPreview}
                  </span>
                </div>
              )}

              {/* IP产品密码 */}
              <div className="flex items-center gap-6">
                <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                  IP产品密码：
                </Label>
                <Input
                  value={batchPwd}
                  onChange={e => setBatchPwd(e.target.value)}
                  placeholder="1-10位字母或数字"
                  className="h-10 rounded-xl border-gray-200 flex-1"
                />
                <span className="text-xs text-gray-400 whitespace-nowrap">
                  1至10位字母或数字或组合
                </span>
              </div>

              {/* 单账号连接设备数 */}
              <ConnectCountSelector
                value={batchConnectCount}
                onChange={setBatchConnectCount}
                label="单账号连接设备数"
                hint="每个账号可同时在线设备的数量"
              />
            </>
          )}

          {/* 优惠券 */}
          {!isTest && <CouponSelector />}

          {/* 余额 */}
          <div className="flex items-center gap-6">
            <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
              余额：
            </Label>
            <div className="flex items-center gap-2 flex-1">
              <span className="text-sm text-gray-600">
                当前账户余额
                <span className="font-bold text-orange-500 ml-1">¥10.00</span>
              </span>
              <Button
                variant="link"
                className="text-sm text-blue-500 p-0 h-auto font-medium"
                onClick={() => navigate("/admin")}
              >
                去充值
              </Button>
            </div>
          </div>

          {/* 支付方式 */}
          <div className="flex items-center gap-6">
            <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
              支付方式：
            </Label>
            <RadioGroup
              value={payType}
              onValueChange={setPayType}
              className="flex gap-8"
            >
              <div className="flex items-center gap-2">
                <RadioGroupItem value="100" id="alipay" />
                <Label
                  htmlFor="alipay"
                  className="cursor-pointer text-sm text-gray-700 flex items-center gap-1.5"
                >
                  <img src={alipay} alt="支付宝" className="w-5 h-5" />
                  支付宝
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <RadioGroupItem value="70" id="wechat" />
                <Label
                  htmlFor="wechat"
                  className="cursor-pointer text-sm text-gray-700 flex items-center gap-1.5"
                >
                  <img src={wechat} alt="微信" className="w-5 h-5" />
                  微信
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <RadioGroupItem value="1" id="balance" />
                <Label
                  htmlFor="balance"
                  className="cursor-pointer text-sm text-gray-700 flex items-center gap-1.5"
                >
                  <img src={balance} alt="余额" className="w-5 h-5" />
                  余额
                </Label>
              </div>
            </RadioGroup>
          </div>

          {/* 总金额 / 应付款 */}
          <div className="space-y-2">
            <div className="flex items-center gap-6">
              <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                总金额：
              </Label>
              <span className="font-medium text-gray-800">
                ¥{total.toFixed(2)}
              </span>
            </div>
            <div className="flex items-center gap-6">
              <Label className="text-sm font-medium text-gray-700 whitespace-nowrap w-28">
                应付款：
              </Label>
              <span className="text-xl font-bold text-orange-500">
                ¥{total.toFixed(2)}
              </span>
            </div>
          </div>

          <div className="flex gap-4">
            <Button
              variant="outline"
              className="flex-1 h-12 rounded-xl text-base border-gray-200 hover:bg-gray-50"
              onClick={handleBack}
            >
              上一步
            </Button>
            <Button
              className="flex-1 h-12 rounded-xl text-base bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90 transition-all"
              onClick={handlePay}
              disabled={submitting}
            >
              {submitting ? "提交中..." : "确认支付"}
            </Button>
          </div>
        </div>
      </div>
    </Wrap>
  )
}
