import { useState, useEffect, useRef } from 'react';
import { showToast } from './Toast';

function TicketForm({ initialData, onSubmit, onCancel, editMode }) {
  const [type, setType] = useState('welfare'); // welfare 或 sports
  const [numbers, setNumbers] = useState([createEmptyNumber('welfare')]);
  const [multiple, setMultiple] = useState(1);
  const [isAdditional, setIsAdditional] = useState(false);
  const [issue, setIssue] = useState('');
  const inputRefs = useRef({});

  function createEmptyNumber(lotteryType) {
    if (lotteryType === 'welfare') {
      // 双色球：6红+1蓝
      return { red: ['', '', '', '', '', ''], blue: '' };
    } else {
      // 大乐透：5前区+2后区
      return { front: ['', '', '', '', ''], back: ['', ''] };
    }
  }

  useEffect(() => {
    if (initialData?.numbers) {
      setNumbers(initialData.numbers);
      if (initialData.type) setType(initialData.type);
      if (initialData.multiple) setMultiple(initialData.multiple);
      if (initialData.is_additional) setIsAdditional(initialData.is_additional);
      if (initialData.issue) setIssue(initialData.issue);
    }
  }, [initialData]);

  const handleTypeChange = (newType) => {
    setType(newType);
    setNumbers([createEmptyNumber(newType)]);
    setIsAdditional(false);
  };

  const addNumber = () => {
    const newIndex = numbers.length;
    setNumbers([...numbers, createEmptyNumber(type)]);
    // 新增后聚焦到第一个输入框
    setTimeout(() => {
      const firstKey = type === 'welfare' ? `${newIndex}-red-0` : `${newIndex}-front-0`;
      if (inputRefs.current[firstKey]) {
        inputRefs.current[firstKey].focus();
      }
    }, 0);
  };

  const removeNumber = (index) => {
    if (numbers.length > 1) {
      setNumbers(numbers.filter((_, i) => i !== index));
    }
  };

  // 获取下一个输入框的key
  const getNextInputKey = (rowIndex, field, subIndex) => {
    if (type === 'welfare') {
      if (field === 'red' && subIndex < 5) {
        return `${rowIndex}-red-${subIndex + 1}`;
      } else if (field === 'red' && subIndex === 5) {
        return `${rowIndex}-blue`;
      }
    } else {
      if (field === 'front' && subIndex < 4) {
        return `${rowIndex}-front-${subIndex + 1}`;
      } else if (field === 'front' && subIndex === 4) {
        return `${rowIndex}-back-0`;
      } else if (field === 'back' && subIndex === 0) {
        return `${rowIndex}-back-1`;
      }
    }
    return null;
  };

  const updateNumber = (index, field, subIndex, value) => {
    // 只允许数字，最多2位
    const cleaned = value.replace(/\D/g, '').slice(0, 2);
    const newNumbers = [...numbers];
    if (subIndex !== null) {
      newNumbers[index][field][subIndex] = cleaned;
    } else {
      newNumbers[index][field] = cleaned;
    }
    setNumbers(newNumbers);

    // 输入两位数后自动跳转到下一个输入框
    if (cleaned.length === 2) {
      const nextKey = getNextInputKey(index, field, subIndex);
      if (nextKey && inputRefs.current[nextKey]) {
        inputRefs.current[nextKey].focus();
      }
    }
  };

  // 计算注数（只计算填写完整的号码）
  const betCount = numbers.filter(n => {
    if (type === 'welfare') {
      return n.red.every(r => r !== '') && n.blue !== '';
    } else {
      return n.front.every(f => f !== '') && n.back.every(b => b !== '');
    }
  }).length;

  // 计算总金额
  const unitPrice = type === 'sports' && isAdditional ? 3 : 2;
  const totalCost = betCount * multiple * unitPrice;

  const handleSubmit = () => {
    if (betCount === 0) {
      showToast('请至少填写一注完整的号码', 'error');
      return;
    }

    // 格式化号码，补零
    const formattedNumbers = numbers
      .filter(n => {
        if (type === 'welfare') {
          return n.red.every(r => r !== '') && n.blue !== '';
        } else {
          return n.front.every(f => f !== '') && n.back.every(b => b !== '');
        }
      })
      .map(n => {
        if (type === 'welfare') {
          return {
            red: n.red.map(r => r.padStart(2, '0')),
            blue: n.blue.padStart(2, '0')
          };
        } else {
          return {
            front: n.front.map(f => f.padStart(2, '0')),
            back: n.back.map(b => b.padStart(2, '0'))
          };
        }
      });

    onSubmit({
      type,
      game: type === 'welfare' ? '双色球' : '大乐透',
      issue: issue || null,
      numbers: formattedNumbers,
      bet_count: betCount,
      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={onCancel}>取消</button>
        <h2>{editMode ? '编辑彩票' : '添加彩票'}</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>
            <input
              type="text"
              value={issue}
              onChange={(e) => setIssue(e.target.value)}
              placeholder="如：2026001"
              className="issue-input"
              style={{flex: 1, padding: '10px', borderRadius: '8px', border: '1px solid #ddd', background: '#fff', color: '#333'}}
            />
          </div>
        </div>

        {/* 号码输入 */}
        <div className="numbers-section">
          {numbers.map((num, index) => (
            <div key={index} className="number-row">
              {type === 'welfare' ? (
                <div className="number-inputs">
                  <div className="input-group red">
                    {num.red.map((r, i) => (
                      <input
                        key={i}
                        ref={el => inputRefs.current[`${index}-red-${i}`] = el}
                        type="text"
                        inputMode="numeric"
                        value={r}
                        onChange={(e) => updateNumber(index, 'red', i, e.target.value)}
                        placeholder={`红${i + 1}`}
                      />
                    ))}
                  </div>
                  <div className="input-group blue">
                    <input
                      ref={el => inputRefs.current[`${index}-blue`] = el}
                      type="text"
                      inputMode="numeric"
                      value={num.blue}
                      onChange={(e) => updateNumber(index, 'blue', null, e.target.value)}
                      placeholder="蓝"
                    />
                  </div>
                  {numbers.length > 1 && (
                    <button className="remove-btn" onClick={() => removeNumber(index)}>×</button>
                  )}
                </div>
              ) : (
                <div className="number-inputs">
                  <div className="input-group front">
                    {num.front.map((f, i) => (
                      <input
                        key={i}
                        ref={el => inputRefs.current[`${index}-front-${i}`] = el}
                        type="text"
                        inputMode="numeric"
                        value={f}
                        onChange={(e) => updateNumber(index, 'front', i, e.target.value)}
                        placeholder={`前${i + 1}`}
                      />
                    ))}
                  </div>
                  <div className="input-group back">
                    {num.back.map((b, i) => (
                      <input
                        key={i}
                        ref={el => inputRefs.current[`${index}-back-${i}`] = el}
                        type="text"
                        inputMode="numeric"
                        value={b}
                        onChange={(e) => updateNumber(index, 'back', i, e.target.value)}
                        placeholder={`后${i + 1}`}
                      />
                    ))}
                  </div>
                  {numbers.length > 1 && (
                    <button className="remove-btn" onClick={() => removeNumber(index)}>×</button>
                  )}
                </div>
              )}
            </div>
          ))}

          <button className="add-number-btn" onClick={addNumber}>+ 添加一注</button>
        </div>

        {/* 倍数和追加 */}
        <div className="options-section">
          <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>

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

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

export default TicketForm;
