import { useState } from 'react';

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function generateWelfare() {
  // 双色球：6个红球(1-33不重复) + 1个蓝球(1-16)
  const reds = [];
  while (reds.length < 6) {
    const n = randomInt(1, 33);
    if (!reds.includes(n)) reds.push(n);
  }
  reds.sort((a, b) => a - b);
  const blue = randomInt(1, 16);
  return {
    red: reds.map(n => String(n).padStart(2, '0')),
    blue: String(blue).padStart(2, '0')
  };
}

function generateSports() {
  // 大乐透：5个前区(1-35不重复) + 2个后区(1-12不重复)
  const fronts = [];
  while (fronts.length < 5) {
    const n = randomInt(1, 35);
    if (!fronts.includes(n)) fronts.push(n);
  }
  fronts.sort((a, b) => a - b);
  const backs = [];
  while (backs.length < 2) {
    const n = randomInt(1, 12);
    if (!backs.includes(n)) backs.push(n);
  }
  backs.sort((a, b) => a - b);
  return {
    front: fronts.map(n => String(n).padStart(2, '0')),
    back: backs.map(n => String(n).padStart(2, '0'))
  };
}

function RandomPick({ onSubmit, onClose }) {
  const [type, setType] = useState('welfare');
  const [betCount, setBetCount] = useState(5);
  const [multiple, setMultiple] = useState(1);
  const [isAdditional, setIsAdditional] = useState(false);
  const [generated, setGenerated] = useState(null);

  const handleGenerate = () => {
    const nums = [];
    for (let i = 0; i < betCount; i++) {
      nums.push(type === 'welfare' ? generateWelfare() : generateSports());
    }
    setGenerated(nums);
  };

  const refreshOne = (index) => {
    const newGenerated = [...generated];
    newGenerated[index] = type === 'welfare' ? generateWelfare() : generateSports();
    setGenerated(newGenerated);
  };

  const handleTypeChange = (newType) => {
    setType(newType);
    setGenerated(null);
    setIsAdditional(false);
  };

  const unitPrice = type === 'sports' && isAdditional ? 3 : 2;
  const totalCost = (generated ? generated.length : betCount) * multiple * unitPrice;

  const handleSubmit = () => {
    if (!generated) return;
    onSubmit({
      type,
      game: type === 'welfare' ? '双色球' : '大乐透',
      issue: null,
      numbers: generated,
      bet_count: generated.length,
      multiple: Number(multiple),
      is_additional: type === 'sports' ? isAdditional : false,
      cost: totalCost
    });
  };

  return (
    <div className="form-fullscreen">
      <div className="form-header">
        <button className="btn btn-secondary" onClick={onClose}>取消</button>
        <h2>机选号码</h2>
        <div style={{width: '60px'}}></div>
      </div>

      <div className="form-content">
        {/* 彩票类型 */}
        <div className="type-selector">
          <button className={`type-btn ${type === 'welfare' ? 'active' : ''}`} onClick={() => handleTypeChange('welfare')}>
            福利彩票（双色球）
          </button>
          <button className={`type-btn ${type === 'sports' ? 'active' : ''}`} onClick={() => handleTypeChange('sports')}>
            体育彩票（大乐透）
          </button>
        </div>

        {/* 注数和倍数 */}
        <div className="options-section">
          <div className="option-row">
            <label>注数</label>
            <div className="multiple-selector">
              {[1, 2, 3, 5].map(n => (
                <button key={n} className={`multiple-btn ${betCount === n ? 'active' : ''}`} onClick={() => { setBetCount(n); setGenerated(null); }}>{n}</button>
              ))}
              <input type="number" min="1" value={betCount} onChange={(e) => { setBetCount(Math.max(1, Number(e.target.value))); setGenerated(null); }} className="multiple-input" />
            </div>
          </div>
          <div className="option-row">
            <label>倍数</label>
            <div className="multiple-selector">
              {[1, 2, 3, 5, 10].map(m => (
                <button key={m} className={`multiple-btn ${multiple === m ? 'active' : ''}`} onClick={() => setMultiple(m)}>{m}</button>
              ))}
              <input type="number" min="1" value={multiple} onChange={(e) => setMultiple(Math.max(1, Number(e.target.value)))} className="multiple-input" />
            </div>
          </div>
          {type === 'sports' && (
            <div className="option-row">
              <label>追加投注</label>
              <button className={`toggle-btn ${isAdditional ? 'active' : ''}`} onClick={() => setIsAdditional(!isAdditional)}>
                {isAdditional ? '已追加 (+1元/注)' : '未追加'}
              </button>
            </div>
          )}
        </div>

        {/* 生成按钮 */}
        <button className="btn btn-primary" onClick={handleGenerate} style={{width: '100%', padding: '15px', fontSize: '16px', marginBottom: '20px'}}>
          🎲 随机生成
        </button>

        {/* 生成结果 */}
        {generated && (
          <div className="numbers-section">
            {generated.map((num, index) => (
              <div key={index} className="number-display" style={{display: 'flex', alignItems: 'center'}}>
                <div className="number-balls" style={{flex: 1}}>
                  {type === 'welfare' ? (
                    <>
                      {num.red.map((r, i) => <span key={i} className="ball red">{r}</span>)}
                      <span className="ball blue">{num.blue}</span>
                    </>
                  ) : (
                    <>
                      {num.front.map((f, i) => <span key={i} className="ball red">{f}</span>)}
                      {num.back.map((b, i) => <span key={`b${i}`} className="ball blue">{b}</span>)}
                    </>
                  )}
                </div>
                <button className="refresh-one-btn" onClick={() => refreshOne(index)} title="换一注">🔄</button>
              </div>
            ))}
          </div>
        )}

        {/* 费用汇总 */}
        <div className="summary-section">
          <div className="summary-row">
            <span>注数</span>
            <span>{generated ? generated.length : betCount} 注</span>
          </div>
          <div className="summary-row">
            <span>倍数</span>
            <span>{multiple} 倍</span>
          </div>
          <div className="summary-row">
            <span>单价</span>
            <span>{unitPrice} 元/注</span>
          </div>
          <div className="summary-row total">
            <span>合计</span>
            <span>{totalCost} 元</span>
          </div>
        </div>

        {/* 保存按钮 */}
        {generated && (
          <button className="btn btn-primary" onClick={handleSubmit} style={{width: '100%', padding: '15px', fontSize: '18px', marginTop: '20px'}}>
            保存
          </button>
        )}
      </div>
    </div>
  );
}

export default RandomPick;
