import React, { useEffect, useState, useRef, useCallback } from 'react';
import { Modal, Typography, Spin, Button } from '@douyinfe/semi-ui';
import { QRCodeSVG } from 'qrcode.react';
import { API } from '../../helpers';
import { useTranslation } from 'react-i18next';

const { Text } = Typography;

const POLL_INTERVAL = 2000;

export default function QRCodePayModal({ visible, qrCodeUrl, tradeNo, onClose, onSuccess, title, subtitle, statusApiPath }) {
  const { t } = useTranslation();
  const [status, setStatus] = useState('pending');
  const [countdown, setCountdown] = useState(300);
  const timerRef = useRef(null);
  const pollRef = useRef(null);

  const pollStatus = useCallback(async () => {
    if (!tradeNo) return;
    try {
      const res = await API.get(`${statusApiPath}?trade_no=${tradeNo}`);
      const { data } = res.data;
      if (data?.status === 'success') {
        setStatus('success');
        clearInterval(pollRef.current);
        clearInterval(timerRef.current);
        if (onSuccess) {
          setTimeout(onSuccess, 1000);
        }
      } else if (data?.status === 'expired') {
        setStatus('expired');
        clearInterval(pollRef.current);
        clearInterval(timerRef.current);
      }
    } catch (e) {
      // 忽略轮询错误
    }
  }, [tradeNo, onSuccess, statusApiPath]);

  useEffect(() => {
    if (visible && tradeNo && status === 'pending') {
      pollRef.current = setInterval(pollStatus, POLL_INTERVAL);
      timerRef.current = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            setStatus('expired');
            clearInterval(pollRef.current);
            clearInterval(timerRef.current);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }

    return () => {
      clearInterval(pollRef.current);
      clearInterval(timerRef.current);
    };
  }, [visible, tradeNo, status, pollStatus]);

  useEffect(() => {
    if (visible) {
      setStatus('pending');
      setCountdown(300);
    }
  }, [visible]);

  const formatCountdown = (seconds) => {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  const renderContent = () => {
    if (status === 'success') {
      return (
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <Text style={{ fontSize: 18, color: '#28a745' }}>
            {t('支付成功！')}
          </Text>
        </div>
      );
    }

    if (status === 'expired') {
      return (
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <Text style={{ fontSize: 16, color: '#dc3545' }}>
            {t('二维码已过期，请重新发起支付')}
          </Text>
          <div style={{ marginTop: 16 }}>
            <Button onClick={onClose}>{t('关闭')}</Button>
          </div>
        </div>
      );
    }

    return (
      <div style={{ textAlign: 'center' }}>
        <div style={{ display: 'inline-block', padding: 16, background: '#fff', borderRadius: 8 }}>
          <QRCodeSVG
            value={qrCodeUrl}
            size={256}
            level='M'
            includeMargin={false}
          />
        </div>
        <div style={{ marginTop: 16 }}>
          <Text type="secondary">
            {subtitle || t('请扫描二维码完成支付')}
          </Text>
        </div>
        <div style={{ marginTop: 8 }}>
          <Spin size="small" />
          <Text type="secondary" style={{ marginLeft: 8 }}>
            {t('等待支付中...')} ({formatCountdown(countdown)})
          </Text>
        </div>
      </div>
    );
  };

  return (
    <Modal
      title={title || t('扫码支付')}
      visible={visible}
      onCancel={onClose}
      footer={null}
      width={400}
      centered
    >
      {renderContent()}
    </Modal>
  );
}
