import { Button, Input, Space, Tooltip } from 'antd'
import type { ClaimProductInfo } from '@/types/claim'

export function ClaimProductItems({
  product,
  compact = false,
}: {
  product: ClaimProductInfo | null
  compact?: boolean
}) {
  const items = getProductItems(product)
  const hasMultipleItems = Boolean(product?.isBundle || items.length > 1)

  if (!items.length) {
    return null
  }

  return (
    <div className={compact ? 'claim-product-items compact' : 'claim-product-items'}>
      <div className="claim-product-items-header">
        <span>{hasMultipleItems ? '包含商品' : '商品明细'}</span>
        {hasMultipleItems ? <strong>{items.length} 项</strong> : null}
      </div>

      <div className="claim-product-items-list">
        {items.map((item) => (
          <div key={item.key} className="claim-product-item-row">
            <span>{item.name}</span>
            <strong>x{item.quantity}</strong>
          </div>
        ))}
      </div>
    </div>
  )
}

export function UidEditRow({
  uidInput,
  submitting,
  onChange,
  onSubmit,
}: {
  uidInput: string
  submitting: boolean
  onChange: (value: string) => void
  onSubmit: () => void
}) {
  return (
    <Space.Compact style={{ width: '100%', marginBottom: 16 }}>
      <Input
        size="large"
        value={uidInput}
        maxLength={15}
        placeholder="游戏编号"
        onChange={(event) => onChange(event.target.value.replace(/\D/g, '').slice(0, 15))}
        onPressEnter={onSubmit}
      />
      <Tooltip title="游戏编号填错时，修改为正确编号后点击「更新 UID」即可">
        <Button size="large" loading={submitting} onClick={onSubmit}>
          更新 UID
        </Button>
      </Tooltip>
    </Space.Compact>
  )
}

export function InfoTile({ label, value }: { label: string; value: string }) {
  return (
    <div className="claim-info-item">
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  )
}

export function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="claim-role-panel-item">
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  )
}

function getProductItems(product: ClaimProductInfo | null) {
  const items = Array.isArray(product?.items) ? product.items : []
  return items
    .map((item) => ({
      key: item.cloudSkuId || item.name,
      name: String(item.name || '').trim(),
      quantity: Math.max(1, Number(item.quantity || 1) || 1),
    }))
    .filter((item) => item.name)
}
