import { useState } from 'react';
import { useForm } from '../../context/FormContext';
import { Plus } from 'lucide-react';

export default function FillBlank({ field, sectionId }) {
  const { formState, toggleOption, addCustomOption } = useForm();
  const [customInput, setCustomInput] = useState('');

  const fieldState = formState.sections[sectionId]?.[field.id] || { selected: [], customOptions: [] };
  const allOptions = [...(field.options || []), ...(fieldState.customOptions || [])];
  const selected = fieldState.selected || [];

  const filledSentence = field.sentence?.replace(
    /____________/g,
    selected.length > 0
      ? selected.join(' / ')
      : '____________'
  );

  const handleAddCustom = () => {
    if (customInput.trim()) {
      addCustomOption(sectionId, field.id, customInput.trim());
      setCustomInput('');
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddCustom();
    }
  };

  return (
    <div className="fill-blank" id={`field-${field.id}`}>
      <div className="fill-blank__label">{field.label}</div>

      {field.sentence && (
        <div className="fill-blank__sentence">
          {filledSentence.split('____________').map((part, i, arr) => (
            <span key={i}>
              {part}
              {i < arr.length - 1 && (
                <span className={`fill-blank__blank ${selected.length > 0 ? 'fill-blank__blank--filled' : ''}`}>
                  {selected.length > 0 ? selected.join(' / ') : '____________'}
                </span>
              )}
            </span>
          ))}
        </div>
      )}

      <div className="fill-blank__options">
        {allOptions.map(option => (
          <button
            key={option}
            type="button"
            className={`option-btn ${selected.includes(option) ? 'option-btn--selected' : ''}`}
            onClick={() => toggleOption(sectionId, field.id, option, field.multiSelect)}
            title={option}
          >
            {option}
          </button>
        ))}
      </div>

      <div className="fill-blank__custom">
        <input
          type="text"
          className="fill-blank__custom-input"
          placeholder="Add your own option..."
          value={customInput}
          onChange={e => setCustomInput(e.target.value)}
          onKeyDown={handleKeyDown}
        />
        <button
          type="button"
          className="fill-blank__custom-add"
          onClick={handleAddCustom}
          title="Add custom option"
        >
          <Plus size={14} />
        </button>
      </div>
    </div>
  );
}
