import React, { useState, useEffect } from 'react'
import { View, Text } from '@tarojs/components'
import { InputNumber } from '@nutui/nutui-react-taro'
import { Checkbox } from '@nutui/nutui-react-taro'
import './NumberInterval.scss'

interface NumberIntervalProps {
  value: { min: number, max: number, organizer_joined: boolean }
  onChange: (value: { min: number, max: number, organizer_joined: boolean }) => void
  min: number
  max: number
}

const NumberInterval: React.FC<NumberIntervalProps> = ({
  value,
  onChange,
  min,
  max
}) => {
  const [organizer_joined, setOrganizerJoined] = useState(true);
  const [minParticipants, setMinParticipants] = useState(1);
  const [maxParticipants, setMaxParticipants] = useState(1);

  useEffect(() => {
    if (value) {
      setOrganizerJoined(value.organizer_joined);
      setMinParticipants(value.min);
      setMaxParticipants(value.max);
    }
    console.log(value, 'valuevaluevaluevaluevaluevalue');
  }, [value]);

  const handleChange = (value: { min: number | string, max: number | string, organizer_joined: boolean }) => {
    const toNumber = (v: number | string): number => typeof v === 'string' ? Number(v) : v
    const { min, max, organizer_joined } = value;
    onChange({ min: toNumber(min), max: toNumber(max), organizer_joined })
  }
  
  
  return (
    <View className='participants-control-section'>
      <View className='participant-control'>
        <Text className='control-label'>最小成局数</Text>
        <View className='control-buttons'>
          <InputNumber
            className="format-width"
            value={minParticipants}
            min={min}
            max={maxParticipants}
            onChange={(value) => handleChange({ min: value, max: maxParticipants, organizer_joined: organizer_joined })}
            formatter={(value) => `${value}人`}
          />
        </View>
      </View>
      <View className='participant-control'>
        <Text className='control-label'>球局总人数</Text>
        <View className='control-buttons'>
          <InputNumber
            className="format-width"
            value={maxParticipants}
            onChange={(value) => handleChange({ min: minParticipants, max: value, organizer_joined: organizer_joined })}
            min={minParticipants}
            max={max}
            formatter={(value) => `${value}人`}
          />
        </View>
      </View>
      <View className='participant-control'>
        <View className='participant-control-checkbox-wrapper'>
        <Checkbox 
            className='participant-control-checkbox'
            checked={organizer_joined}
            onChange={(checked) => handleChange({ min: minParticipants, max: maxParticipants, organizer_joined: checked })}
        />
        我也参与此球局
        </View>
      </View>
    </View>
  )
}

export default NumberInterval 