import { useEffect, useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { notifyRedeemSuccess } from '../lib/useRedeemSuccessBus';

function formatAmount(n: number) {
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

export default function RedeemSuccessPage() {
  const navigate = useNavigate();
  const location = useLocation();

  const result = useMemo(() => {
    const stateResult = (location.state as { result?: Record<string, unknown> })?.result;
    if (stateResult) return stateResult;
    try {
      const cached = sessionStorage.getItem('lastRedeemResult');
      return cached ? (JSON.parse(cached) as Record<string, unknown>) : null;
    } catch {
      return null;
    }
  }, [location.state]);

  const storeName = (location.state as { storeName?: string })?.storeName || '当前门店';
  const user = (location.state as { user?: { nickname?: string; phone?: string; userNo?: string } })?.user;
  const userLabel = user?.nickname || user?.phone || '—';
  const amount = Number(result?.amount ?? 0);
  const redeemNo = String(result?.redeemNo || '—');
  const createdAt = result?.createdAt
    ? new Date(String(result.createdAt)).toLocaleString('zh-CN')
    : new Date().toLocaleString('zh-CN');

  // v3.5.1 #2：核销成功后广播事件，通知门店信息页 / 提现页即时刷新
  useEffect(() => {
    notifyRedeemSuccess({
      redeemNo: redeemNo !== '—' ? redeemNo : undefined,
      amount,
    });
  }, [redeemNo, amount]);

  return (
    <div className="shop-success-page">
      <header className="shop-success-header">
        <button type="button" className="shop-redeem-back" onClick={() => navigate('/')} aria-label="返回">
          <span className="material-symbols-outlined">arrow_back</span>
        </button>
        <h1 className="app-page-title">杜康好客</h1>
      </header>

      <section className="shop-success-hero">
        <div className="shop-success-icon-wrap">
          <span className="material-symbols-outlined">check_circle</span>
        </div>
        <h2 className="shop-success-title">核销成功</h2>
        <p className="shop-success-amount">¥ {formatAmount(amount)}</p>
        <p className="shop-success-sub">已入账到余额</p>
        <p className="shop-success-note">核销成功，账单通知已发送至老板手机</p>
      </section>

      <div className="shop-success-details">
        <div className="shop-success-detail-row">
          <span className="shop-success-detail-label">核销门店</span>
          <span className="shop-success-detail-value">{storeName}</span>
        </div>
        <div className="shop-success-detail-row">
          <span className="shop-success-detail-label">核销用户</span>
          <div className="shop-success-user">
            <div className="shop-success-user-avatar">
              <span className="material-symbols-outlined">person</span>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="shop-success-detail-value">{userLabel}</div>
            </div>
          </div>
        </div>
        <div className="shop-success-detail-row">
          <span className="shop-success-detail-label">核销时间</span>
          <span className="shop-success-detail-value" style={{ fontWeight: 400, color: 'var(--color-on-surface-variant)' }}>
            {createdAt}
          </span>
        </div>
        <div className="shop-success-detail-row">
          <span className="shop-success-detail-label">订单编号</span>
          <span className="shop-success-detail-value" style={{ fontFamily: 'monospace', fontWeight: 400 }}>
            {redeemNo}
          </span>
        </div>
      </div>

      <div className="shop-success-actions">
        <button type="button" className="shop-success-primary-btn" onClick={() => navigate('/')}>
          <span>继续核销</span>
          <span className="material-symbols-outlined" style={{ fontSize: 20 }}>qr_code_scanner</span>
        </button>
        <button type="button" className="shop-success-outline-btn" onClick={() => navigate('/')}>
          <span>返回首页</span>
          <span className="material-symbols-outlined" style={{ fontSize: 20 }}>home</span>
        </button>
      </div>

      <div className="shop-success-brand">
        <div className="shop-success-brand-icon">
          <span className="material-symbols-outlined shop-fill-icon" style={{ fontSize: 12 }}>verified</span>
        </div>
        <p className="shop-success-brand-text">山西领势酒业有限责任公司</p>
      </div>
    </div>
  );
}
