import React, { useEffect, useState } from "react"
import CfCheckbox from "./CfCheckbox"

interface CfMultiSelectQuestionProps {
  question: string
  options: Array<{ id: string; label: string }>
  maxSelections: number
  onSelectionChange: (selectedOptions: string[], customOption: string) => void
}

const CfMultiSelectQuestion: React.FC<CfMultiSelectQuestionProps> = ({
  question,
  options,
  maxSelections,
  onSelectionChange,
}) => {
  const [selectedOptions, setSelectedOptions] = useState<string[]>([])
  const [customOptionInput, setCustomOptionInput] = useState("")

  useEffect(() => {
    onSelectionChange(selectedOptions, customOptionInput)
  }, [selectedOptions, customOptionInput, onSelectionChange])

  const handleCheckboxChange = (id: string, isChecked: boolean) => {
    let newSelectedOptions: string[]
    if (isChecked) {
      if (!selectedOptions.includes(id)) {
        newSelectedOptions = [...selectedOptions, id]
        if (newSelectedOptions.length > maxSelections) {
          newSelectedOptions.shift() // Remove the first item if we exceed maxSelections
        }
      } else {
        newSelectedOptions = selectedOptions
      }
    } else {
      newSelectedOptions = selectedOptions.filter(optionId => optionId !== id)
    }
    setSelectedOptions(newSelectedOptions)
  }

  const handleCustomOptionInputChange = (value: string) => {
    setCustomOptionInput(value)
    if (value && !selectedOptions.includes("custom-option-input")) {
      handleCheckboxChange("custom-option-input", true)
    } else if (!value && selectedOptions.includes("custom-option-input")) {
      handleCheckboxChange("custom-option-input", false)
    }
  }

  return (
    <div className="flex flex-col items-start gap-y-2">
      <label className="text-base" htmlFor="custom-option-input">
        {question}
      </label>

      <div className="flex flex-col items-start gap-y-2">
        {options.map(option => (
          <CfCheckbox
            key={option.id}
            id={option.id}
            containerStyle="pr-4"
            label={option.label}
            onChange={(id, isChecked) => handleCheckboxChange(id, isChecked)}
            checked={selectedOptions.includes(option.id)}
            disabled={
              selectedOptions.length >= maxSelections && !selectedOptions.includes(option.id)
            }
          />
        ))}
        <CfCheckbox
          id="custom-option-input"
          containerStyle="pr-4"
          label={customOptionInput}
          onLabelChange={handleCustomOptionInputChange}
          onChange={(id, isChecked) => handleCheckboxChange(id, isChecked)}
          checked={selectedOptions.includes("custom-option-input")}
          disabled={
            selectedOptions.length >= maxSelections &&
            !selectedOptions.includes("custom-option-input")
          }
        />
      </div>
    </div>
  )
}

export default CfMultiSelectQuestion
