import { CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { Alert, Button, Card, Typography } from 'antd'
import { formatAdminDateTime } from '@/utils/admin-time'
import type { ClaimAffiliateDashFlowInfo } from '@/types/claim'
import { normalizeUid } from './claim-snapshot'
import type { ClaimSnapshot } from './claim-snapshot'
import { ClaimProductItems, InfoTile, UidEditRow } from './claim-shared'

export function AffiliateDashClaimPanel({
  affiliateDash,
  expectedUid,
  taskLastError,
  qrCodeDataUrl,
  submittingUid,
  submittingSubmit,
  uidInput,
  onUidChange,
  onResubmitUid,
  onSubmit,
}: {
  affiliateDash: ClaimAffiliateDashFlowInfo
  expectedUid: string
  taskLastError?: string
  qrCodeDataUrl: string
  submittingUid: boolean
  submittingSubmit: boolean
  uidInput: string
  onUidChange: (value: string) => void
  onResubmitUid: () => void
  onSubmit: () => void
}) {
  const bound = Boolean(affiliateDash.bound)
  const expectedAccount = String(
    expectedUid || affiliateDash.expectedGameAccount || affiliateDash.gameAccount || '',
  ).trim()
  const boundAccount = String(affiliateDash.boundAccount || '').trim()
  const boundAccountMatched = Boolean(
    bound &&
    expectedAccount &&
    boundAccount &&
    normalizeUid(boundAccount) === normalizeUid(expectedAccount),
  )
  const bindMismatch = Boolean(
    affiliateDash.bindMismatch ||
    (bound && boundAccount && expectedAccount && !boundAccountMatched),
  )
  const canSubmit = Boolean(bound && boundAccountMatched && !bindMismatch)
  const displayBoundAccount = boundAccount || '-'

  return (
    <Card className="claim-content-card">
      <div className="claim-feifei-main">
        <Typography.Title level={2}>
          {canSubmit ? '第 3 步：确认并提交发货' : '第 2 步：绑定领取账号'}
        </Typography.Title>
        <p>
          {canSubmit
            ? '账号绑定成功，确认无误后提交发货'
            : bindMismatch
              ? '绑定账号与填写 UID 不一致，请核对 UID 后用正确账号重新绑定'
              : bound
                ? '已扫码，系统正在确认绑定账号'
                : '打开绑定链接完成绑定，系统将自动确认'}
        </p>
      </div>

      <UidEditRow
        uidInput={uidInput}
        submitting={submittingUid}
        onChange={onUidChange}
        onSubmit={onResubmitUid}
      />

      {taskLastError ? (
        <Alert
          type="warning"
          showIcon
          message="上次操作遇到问题"
          description={taskLastError}
          style={{ marginBottom: 16 }}
        />
      ) : null}

      {bindMismatch ? (
        <Alert
          type="warning"
          showIcon
          message="绑定账号与填写 UID 不一致"
          description={`当前识别到 ${displayBoundAccount}，请使用你填写的 UID（${expectedAccount || '-'}）对应账号重新扫码绑定。`}
          style={{ marginBottom: 16 }}
        />
      ) : null}

      {bound && !bindMismatch && !boundAccountMatched ? (
        <Alert
          type="info"
          showIcon
          message="已扫码，正在确认绑定账号"
          description="系统还没有拿到可校验的绑定 UID，请稍等自动刷新。"
          style={{ marginBottom: 16 }}
        />
      ) : null}

      {canSubmit ? (
        <Alert
          type="success"
          showIcon
          icon={<CheckCircleOutlined />}
          message={`已绑定账号：${displayBoundAccount}`}
          description={affiliateDash.gameChannel ? `渠道：${affiliateDash.gameChannel}` : undefined}
          style={{ marginBottom: 16 }}
        />
      ) : null}

      {!canSubmit ? (
        <div
          className="claim-bind-area"
          style={{
            marginBottom: 16,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 20,
          }}
        >
          <span
            style={{
              color: '#ff4d4f',
              writingMode: 'vertical-rl',
              textOrientation: 'upright',
              fontSize: 17,
              fontWeight: 600,
              letterSpacing: 8,
            }}
          >
            Q区用Q扫
          </span>
          {qrCodeDataUrl ? (
            <img
              src={qrCodeDataUrl}
              alt="绑定二维码"
              style={{ width: 220, height: 220, borderRadius: 8 }}
            />
          ) : (
            <Typography.Text type="secondary">绑定二维码生成中，请稍候自动刷新…</Typography.Text>
          )}
          <span
            style={{
              color: '#ff4d4f',
              writingMode: 'vertical-rl',
              textOrientation: 'upright',
              fontSize: 17,
              fontWeight: 600,
              letterSpacing: 8,
            }}
          >
            V区用V扫
          </span>
        </div>
      ) : (
        <Button
          type="primary"
          size="large"
          loading={submittingSubmit}
          disabled={submittingSubmit}
          onClick={onSubmit}
          style={{ marginBottom: 16 }}
        >
          提交发货
        </Button>
      )}
    </Card>
  )
}

export function AffiliateDashResultStep({ snapshot }: { snapshot: ClaimSnapshot }) {
  const affiliateDash = snapshot.affiliateDash
  const success = Boolean(affiliateDash && !snapshot.isRedeemFailed)

  return (
    <Card className="claim-content-card">
      <div className="claim-result-header">
        {!success ? (
          <ExclamationCircleOutlined className="claim-large-icon claim-icon-warning" />
        ) : (
          <CheckCircleOutlined className="claim-large-icon claim-icon-success" />
        )}
        <div>
          <Typography.Title level={2}>{snapshot.resultTitle}</Typography.Title>
          <p className="claim-muted">{snapshot.resultDescription}</p>
        </div>
      </div>

      <div className="claim-info-grid">
        <InfoTile label="领取商品" value={snapshot.product?.title || '-'} />
        <InfoTile
          label="绑定账号"
          value={affiliateDash?.boundAccount || affiliateDash?.gameAccount || '-'}
        />
        <InfoTile label="结果时间" value={formatAdminDateTime(snapshot.task?.redeemedAt || null)} />
      </div>

      <ClaimProductItems product={snapshot.product} />
    </Card>
  )
}
