import React, { useState, useEffect, useRef } from 'react';
import { View, Input } from '@tarojs/components';
import { ROOM_CODE_LENGTH } from '../../../constants';
import './index.scss';

interface RoomCodeInputProps {
  value?: string;
  onChange?: (value: string) => void;
  onComplete?: (value: string) => void;
  length?: number;
}

/**
 * 房间码输入组件
 */
const RoomCodeInput: React.FC<RoomCodeInputProps> = ({
  value = '',
  onChange,
  onComplete,
  length = ROOM_CODE_LENGTH,
}) => {
  const [code, setCode] = useState(value);
  const [isFocused, setIsFocused] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  // 当外部value变化时更新内部状态
  useEffect(() => {
    setCode(value);
  }, [value]);

  // 处理输入变化
  const handleChange = (e) => {
    const newValue = e.detail.value.toUpperCase().slice(0, length);
    setCode(newValue);
    onChange && onChange(newValue);

    // 当输入完成时触发onComplete
    if (newValue.length === length) {
      onComplete && onComplete(newValue);
    }
  };

  // 处理输入框聚焦
  const handleFocus = () => {
    setIsFocused(true);
  };

  // 处理输入框失焦
  const handleBlur = () => {
    setIsFocused(false);
  };

  // 点击输入框容器时聚焦到输入框
  const handleContainerClick = () => {
    inputRef.current?.focus();
  };

  // 生成数字显示单元格
  const renderCells = () => {
    const cells = [];
    for (let i = 0; i < length; i++) {
      const char = code[i] || '';
      const isCellActive = isFocused && i === code.length;

      cells.push(
        <View 
          key={i} 
          className={`room-code-input__cell ${isCellActive ? 'room-code-input__cell--active' : ''}`}
        >
          {char}
          {isCellActive && <View className='room-code-input__cursor'></View>}
        </View>
      );
    }
    return cells;
  };

  return (
    <View className='room-code-input' onClick={handleContainerClick}>
      <View className='room-code-input__cells'>
        {renderCells()}
      </View>
      <Input
        className='room-code-input__input'
        type='text'
        maxlength={length}
        value={code}
        onInput={handleChange}
        onFocus={handleFocus}
        onBlur={handleBlur}
        ref={inputRef}
      />
    </View>
  );
};

export default RoomCodeInput; 