import { useState } from "react"
import CheckmarkIcon from "./assets/CheckmarkIcon"

export default function CfCheckbox({
  className = "",
  containerStyle = "",
  id,
  label,
  onLabelChange,
  onChange,
  disabled = false,
  checked,
}: CfCheckboxProps) {
  const [inputValue, setInputValue] = useState(label)

  const handleCheckboxToggle = () => {
    if (!disabled) {
      const newCheckedState = !checked
      if (onChange) {
        onChange(id, newCheckedState)
      }
      if (onLabelChange) {
        onLabelChange(inputValue)
      }
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value)
    if (onLabelChange) {
      onLabelChange(e.target.value)
    }
  }
  return (
    <div
      className={`cf-checkbox flex items-start justify-start pt-[9.3px] ${className}`}
      data-label={label}
    >
      <label
        htmlFor={id}
        className={`flex flex-row items-center gap-x-2 gap-y-2 ${containerStyle} ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`}
      >
        <div className="flex flex-row items-start gap-x-2">
          <input
            type="checkbox"
            className="hidden"
            checked={checked}
            id={id}
            onChange={handleCheckboxToggle}
          />
          <div className="flex flex-row h-4 w-4 flex-shrink-0  items-center rounded-sm border border-solid border-white/10 bg-white/5">
            {checked && (
              <div className="flex h-4 w-4 flex-shrink-0 flex-row items-center rounded-sm border border-solid border-white/10 bg-yellow-400 ">
                <CheckmarkIcon className="h-[12px] w-[12px] flex-shrink-0" />
              </div>
            )}
          </div>
          {
            <div className="flex flex-row items-start gap-x-2 flex-wrap">
              {id === "custom-option-input" ? (
                <div className="min-w-[324px] rounded-sm border border-solid border-white/10 bg-white/5 px-[11px] py-[7px] focus-within:[box-shadow:0_0_4px_#1e40af]">
                  <input
                    className="font-source_code_pro w-full leading-tight text-stone-400 [min-width:0] [outline:none] placeholder:text-[#B6AFAF]"
                    placeholder="Other pain point..."
                    type="text"
                    value={inputValue}
                    onChange={handleInputChange}
                  />
                </div>
              ) : (
                <div className="text-white/70">{label}</div>
              )}
            </div>
          }
        </div>
      </label>
    </div>
  )
}

interface CfCheckboxProps {
  id: string
  className?: string
  containerStyle: string
  label: string
  onLabelChange?: (label: string) => void
  onChange?: (id: string, isChecked: boolean) => void
  disabled?: boolean
  checked?: boolean
}
