import { useState, useEffect } from "react";
import { View } from "@tarojs/components";
import RadioBlockItem from "@/components/wemeta-radio-block-item/index";
export type TRadioItem = {
  text: string
  value: string
  checked: boolean
};
interface Props {
  value: string
  radioList: TRadioItem[];
  onChange: (current: string) => void;
}
export default function Index({ value, radioList, onChange }: Props) {

  const [_radioList, setRadioList] = useState(radioList)

  const onRadioClick = (item: TRadioItem)=> {
    if(item.checked) return false
    const list = _radioList.map(radioItem=> {
      return {
        ...radioItem,
        checked: item.text === radioItem.text
      }
    })
    setRadioList(list)
    onChange(item.value)
    return false;
  }
  
  useEffect(()=> {
    const list = _radioList.map(radioItem=> {
      return {
        ...radioItem,
        checked: value  === radioItem.value
      }
    })
    setRadioList(list) 
  }, [value])


  return (
      <View className="flex flex-col rounded-20 bg-white">
      {_radioList.map((item, index) => {
        return (
          <View
            onClick={() => {
              onRadioClick(item);
            }}
            key={index}
          >
            <RadioBlockItem
              text={item.text}
              checked={item.checked}
              last={index === _radioList.length - 1}
            ></RadioBlockItem>
          </View>
        );
      })}
    </View>
  );
}