import { CheckboxCard, Classes } from '@blueprintjs/core'
import { memo, useEffect, useState, type FC } from 'react'
import type { Checklist as ChecklistType } from '../types'

interface ChecklistProps {
  conditions: ChecklistType
  initChecked: boolean[]
  onInputChange: (conditions: boolean[]) => void
}

const Checklist: FC<ChecklistProps> = ({
  conditions,
  initChecked,
  onInputChange,
}) => {
  const [conditionChecked, setConditionChecked] = useState(initChecked)

  useEffect(() => {
    onInputChange(conditionChecked)
  }, [conditionChecked])

  return (
    <div>
      {conditions.map((condition, i) => (
        <CheckboxCard
          key={i}
          checked={conditionChecked[i]}
          showAsSelectedWhenChecked={false}
          onChange={() =>
            setConditionChecked(prev => [
              ...prev.slice(0, i),
              !prev[i],
              ...prev.slice(i + 1),
            ])
          }
        >
          {condition.name} -{' '}
          <span className={Classes.TEXT_MUTED}>{condition.description}</span>
        </CheckboxCard>
      ))}
    </div>
  )
}

export default memo(Checklist)
