import { useState } from 'react';

export default function StepList({ steps, editable, onChange }) {
  const [completed, setCompleted] = useState({});

  const toggle = (i) => setCompleted(prev => ({ ...prev, [i]: !prev[i] }));

  const updateStep = (i, value) => {
    const updated = steps.map((s, idx) => (idx === i ? value : s));
    onChange(updated);
  };

  const addStep = () => onChange([...steps, '']);

  const removeStep = (i) => onChange(steps.filter((_, idx) => idx !== i));

  const moveStep = (i, direction) => {
    const arr = [...steps];
    const j = i + direction;
    if (j < 0 || j >= arr.length) return;
    [arr[i], arr[j]] = [arr[j], arr[i]];
    onChange(arr);
  };

  return (
    <div>
      <h3 className="font-semibold text-lg mb-3">Zubereitung</h3>
      <ol className="space-y-3">
        {steps.map((step, i) => (
          <li key={i} className="flex items-start gap-3">
            {!editable && (
              <button
                onClick={() => toggle(i)}
                className={`mt-1 w-6 h-6 rounded-full border-2 flex-shrink-0 flex items-center justify-center text-xs font-bold transition-colors ${
                  completed[i]
                    ? 'bg-blue-600 border-blue-600 text-white'
                    : 'border-gray-300 text-gray-400'
                }`}
              >
                {completed[i] ? '✓' : i + 1}
              </button>
            )}
            {editable ? (
              <div className="flex-1 flex gap-2">
                <span className="mt-2 text-sm font-bold text-gray-400 w-5">{i + 1}.</span>
                <textarea
                  value={step}
                  onChange={e => updateStep(i, e.target.value)}
                  rows={2}
                  className="flex-1 px-2 py-1 border border-gray-300 rounded text-sm resize-none"
                />
                <div className="flex flex-col gap-1">
                  <button onClick={() => moveStep(i, -1)} className="text-gray-400 hover:text-gray-600 text-xs">&uarr;</button>
                  <button onClick={() => moveStep(i, 1)} className="text-gray-400 hover:text-gray-600 text-xs">&darr;</button>
                  <button onClick={() => removeStep(i)} className="text-red-400 hover:text-red-600 text-xs">&times;</button>
                </div>
              </div>
            ) : (
              <p className={`${completed[i] ? 'line-through text-gray-400' : ''}`}>
                {step}
              </p>
            )}
          </li>
        ))}
      </ol>
      {editable && (
        <button
          onClick={addStep}
          className="mt-2 text-sm text-blue-600 hover:text-blue-700 font-medium"
        >
          + Schritt hinzufügen
        </button>
      )}
    </div>
  );
}
