import React, { useState, useEffect, useMemo } from 'react';
import { Plus, Trash2, FileText, Clock } from 'lucide-react';

interface RecipeInstructionsEditorProps {
  value: any;
  onChange: (value: any) => void;
}

export const RecipeInstructionsEditor: React.FC<RecipeInstructionsEditorProps> = ({ value, onChange }) => {
  // Initialize with empty steps array if value is empty/null
  const initialSteps = useMemo(() => {
    if (!value) {
      return [{ step: 1, title: '', description: '', duration_minutes: '' }];
    }
    
    // Handle structured format with steps
    if (value && value.steps && Array.isArray(value.steps)) {
      return value.steps.map((step: any, index: number) => ({
        step: step.step || index + 1,
        title: step.title || '',
        description: step.description || '',
        duration_minutes: step.duration_minutes || ''
      }));
    }
    
    // Handle array format
    if (Array.isArray(value)) {
      return value.map((item: any, index: number) => {
        if (typeof item === 'object' && item !== null) {
          return {
            step: item.step || index + 1,
            title: item.title || '',
            description: item.description || '',
            duration_minutes: item.duration_minutes || ''
          };
        }
        return {
          step: index + 1,
          title: '',
          description: typeof item === 'string' ? item : '',
          duration_minutes: ''
        };
      });
    }
    
    // For any other format, start with one empty step
    return [{ step: 1, title: '', description: '', duration_minutes: '' }];
  }, [value]);

  const [steps, setSteps] = useState<any[]>(initialSteps);

  // Update parent when steps change
  useEffect(() => {
    // Format as structured object with steps array
    const formattedSteps = steps.map((step, index) => ({
      ...step,
      step: index + 1 // Ensure steps are numbered sequentially
    }));
    
    onChange({
      steps: formattedSteps
    });
  }, [steps, onChange]);

  const addStep = () => {
    const newStepNumber = steps.length + 1;
    setSteps([...steps, { step: newStepNumber, title: '', description: '', duration_minutes: '' }]);
  };

  const removeStep = (index: number) => {
    if (steps.length <= 1) return; // Don't remove the last step
    const newSteps = steps.filter((_, i) => i !== index);
    // Renumber the steps after removal
    const renumberedSteps = newSteps.map((step, i) => ({
      ...step,
      step: i + 1
    }));
    setSteps(renumberedSteps);
  };

  const updateStep = (index: number, field: string, newValue: string | number) => {
    const newSteps = [...steps];
    newSteps[index] = { ...newSteps[index], [field]: newValue };
    setSteps(newSteps);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium text-[var(--text-primary)]">Pasos de Preparación</h4>
        <button
          type="button"
          onClick={addStep}
          className="flex items-center gap-2 px-3 py-1.5 text-sm bg-[var(--color-primary)] text-white rounded-md hover:bg-[var(--color-primary)]/90 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Agregar Paso
        </button>
      </div>

      <div className="space-y-4 max-h-[600px] overflow-y-auto pr-2">
        {steps.map((step, index) => (
          <div 
            key={`step-editor-${step.step || index}`} 
            className="p-4 border-2 border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/50 hover:border-[var(--color-primary)]/30 transition-all"
          >
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center text-sm font-bold text-[var(--color-primary)]">
                  {step.step || index + 1}
                </div>
                <h5 className="font-medium text-[var(--text-primary)]">Paso {step.step || index + 1}</h5>
              </div>
              {steps.length > 1 && (
                <button
                  type="button"
                  onClick={() => removeStep(index)}
                  className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950 rounded transition-colors"
                  title="Eliminar paso"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              )}
            </div>

            <div className="space-y-3">
              {/* Step Title */}
              <div>
                <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                  Título del paso
                </label>
                <input
                  type="text"
                  value={step.title || ''}
                  onChange={(e) => updateStep(index, 'title', e.target.value)}
                  className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                  placeholder="Ej: Amasado, Fermentación, etc."
                />
              </div>

              {/* Step Description */}
              <div>
                <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                  Descripción
                </label>
                <textarea
                  value={step.description || ''}
                  onChange={(e) => updateStep(index, 'description', e.target.value)}
                  className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                  placeholder="Descripción detallada del paso..."
                  rows={3}
                />
              </div>

              {/* Duration */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    Duración (minutos)
                  </label>
                  <input
                    type="number"
                    value={step.duration_minutes || ''}
                    onChange={(e) => updateStep(index, 'duration_minutes', e.target.value ? parseInt(e.target.value) : '')}
                    className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                    placeholder="0"
                    min="0"
                  />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {steps.length === 0 && (
        <div className="text-center py-8 text-[var(--text-secondary)] bg-[var(--bg-secondary)]/30 rounded-lg border-2 border-dashed border-[var(--border-secondary)]">
          <FileText className="w-12 h-12 mx-auto mb-2 opacity-50" />
          <p className="text-sm">No hay pasos de preparación. Haz clic en "Agregar Paso" para comenzar.</p>
        </div>
      )}
    </div>
  );
};

export default RecipeInstructionsEditor;