import React from 'react';
import { normalizeExerciseValue } from '../../utils/exerciseInputRules';

const inputClassName = (disabled) =>
  `px-3 py-2 border border-gray-300 dark:border-gray-700 rounded text-center bg-white dark:bg-gray-900 ${
    disabled ? 'opacity-70 cursor-not-allowed bg-gray-100 dark:bg-gray-800' : ''
  }`;

const ExerciseInput = ({ exercise, exIndex, onChange, disabled = false }) => {
  const handleInputChange = (valueIndex, subType = null) => (event) => {
    onChange(exIndex, valueIndex, normalizeExerciseValue(exercise, event.target.value, subType), subType);
  };

  if (exercise.subA && exercise.subB) {
    const [subLabelA = 'a)', subLabelB = 'b)'] = exercise.subLabels || [];

    return (
      <>
        <div className="grid grid-cols-5 gap-2 mb-2">
          <div></div>
          <div className="font-semibold">{subLabelA}</div>
          {exercise.subA.map((val, i) => (
            <input
              key={`a-${i}`}
              type="text"
              inputMode="numeric"
              pattern="[0-9]*"
              autoComplete="off"
              value={val}
              onChange={handleInputChange(i, 'a')}
              disabled={disabled}
              className={inputClassName(disabled)}
            />
          ))}
        </div>
        <div className="grid grid-cols-5 gap-2 mb-2">
          <div></div>
          <div className="font-semibold">{subLabelB}</div>
          {exercise.subB.map((val, i) => (
            <input
              key={`b-${i}`}
              type="text"
              inputMode="numeric"
              pattern="[0-9]*"
              autoComplete="off"
              value={val}
              onChange={handleInputChange(i, 'b')}
              disabled={disabled}
              className={inputClassName(disabled)}
            />
          ))}
        </div>
      </>
    );
  }

  const gridCols =
    exercise.values.length === 4 ? 'grid-cols-6' : exercise.values.length === 5 ? 'grid-cols-7' : 'grid-cols-5';

  return (
    <div className={`grid ${gridCols} gap-2 mb-2`}>
      <div></div>
      <div></div>
      {exercise.values.map((val, i) => (
        <input
          key={i}
          type="text"
          inputMode="numeric"
          pattern="[0-9]*"
          autoComplete="off"
          value={val}
          onChange={handleInputChange(i)}
          disabled={disabled}
          className={inputClassName(disabled)}
        />
      ))}
    </div>
  );
};

export default ExerciseInput;
