import React, { useState } from "react"

function chunk<T>(array: T[], size: number): T[][] {
  return Array.from({ length: Math.ceil(array.length / size) }, (_, index) =>
    array.slice(index * size, index * size + size),
  )
}

interface CfRadioButtonProps {
  options: string[]
  name: string
  onChange?: (selectedOption: string) => void
}

export default function CfRadioButton({ options, name, onChange }: CfRadioButtonProps) {
  const [selectedOption, setSelectedOption] = useState<string | null>(null)

  const handleOptionChange = (option: string) => {
    setSelectedOption(option)
    if (onChange) {
      onChange(option)
    }
  }

  return (
    <div className="flex flex-col gap-y-4 w-full">
      {chunk(options, 3).map((group, groupIndex) => (
        <div key={groupIndex} className="flex justify-between gap-x-10">
          {group.map(option => (
            <label key={option} className="flex items-center gap-x-2 cursor-pointer flex-1">
              <input
                type="radio"
                name={name}
                value={option}
                checked={selectedOption === option}
                onChange={() => handleOptionChange(option)}
                className="hidden"
              />
              <div
                className={`flex h-6 w-6 flex-shrink-0 flex-col items-center justify-center rounded-full border-2 border-solid ${
                  selectedOption === option ? "border-yellow-400" : "border-white/10"
                } p-0.5`}
              >
                {selectedOption === option && (
                  <div className="h-4 w-4 flex-shrink-0 rounded-full bg-yellow-400" />
                )}
              </div>
              <div className={selectedOption === option ? "text-white" : "text-white/60"}>
                {option}
              </div>
            </label>
          ))}
        </div>
      ))}
    </div>
  )
}
