'use client';

import { useState } from 'react';
import { X, Save, Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Textarea } from '@/components/ui/Input';
import type { IdeaMotriz } from '@/types/project';

interface IdeaMotrizEditorProps {
  ideaMotriz: IdeaMotriz;
  onSave: (ideaMotriz: IdeaMotriz) => void;
  onClose: () => void;
}

export function IdeaMotrizEditor({ ideaMotriz, onSave, onClose }: IdeaMotrizEditorProps) {
  const [edited, setEdited] = useState<IdeaMotriz>(JSON.parse(JSON.stringify(ideaMotriz)));

  const handleSave = () => {
    onSave(edited);
    onClose();
  };

  const updateField = (field: keyof IdeaMotriz, value: any) => {
    setEdited({ ...edited, [field]: value });
  };

  const updateFormato = (field: string, value: any) => {
    setEdited({ 
      ...edited, 
      formato: { ...edited.formato, [field]: value } 
    });
  };

  const updateValor = (index: number, value: string) => {
    const newValores = [...(edited.valores || [])];
    newValores[index] = value;
    setEdited({ ...edited, valores: newValores });
  };

  const addValor = () => {
    setEdited({ ...edited, valores: [...(edited.valores || []), ''] });
  };

  const removeValor = (index: number) => {
    const newValores = (edited.valores || []).filter((_, i) => i !== index);
    setEdited({ ...edited, valores: newValores });
  };

  const updateAntagonista = (field: string, value: string) => {
    setEdited({
      ...edited,
      antagonista: { ...edited.antagonista, [field]: value }
    });
  };

  return (
    <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
      <div className="bg-white rounded-lg shadow-xl shadow-black/10 max-w-3xl w-full max-h-[90vh] overflow-hidden animate-scale-in">
        <div className="flex items-center justify-between px-5 py-4 border-b border-stone-100">
          <h2 className="text-base font-semibold text-stone-900">Editar Idea Motriz</h2>
          <button onClick={onClose} className="p-1 text-stone-400 hover:text-stone-600 transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="p-5 overflow-y-auto max-h-[calc(90vh-140px)] space-y-5">
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1.5">Idea Motriz Central</label>
            <Textarea
              value={edited.ideaMotrizCentral || ''}
              onChange={(e) => updateField('ideaMotrizCentral', e.target.value)}
              placeholder="La idea central que guía toda la historia..."
              rows={3}
            />
          </div>

          {/* Formato */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-stone-600 mb-1.5">Capítulos</label>
              <input
                type="number"
                value={edited.formato?.capitulos || ''}
                onChange={(e) => updateFormato('capitulos', parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 border border-stone-200 rounded-lg bg-white text-stone-900 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-400 transition-colors"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-stone-600 mb-1.5">Duración (minutos)</label>
              <input
                type="number"
                value={edited.formato?.duracionMinutos || ''}
                onChange={(e) => updateFormato('duracionMinutos', parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 border border-stone-200 rounded-lg bg-white text-stone-900 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-400 transition-colors"
              />
            </div>
          </div>

          {/* Narrativa */}
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1.5">Narrativa</label>
            <Textarea
              value={edited.narrativa || ''}
              onChange={(e) => updateField('narrativa', e.target.value)}
              placeholder="Descripción del estilo narrativo..."
              rows={3}
            />
          </div>

          {/* Estilo Visual */}
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1.5">Estilo Visual</label>
            <Textarea
              value={edited.estiloVisual || ''}
              onChange={(e) => updateField('estiloVisual', e.target.value)}
              placeholder="Pixar-style 3D animation, vibrant colors, expressive characters..."
              rows={2}
            />
            <p className="text-[11px] text-stone-400 mt-1">Se inyecta automáticamente en cada prompt de imagen. Si se deja vacío, se usa el estilo por defecto.</p>
          </div>

          {/* Valores */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="block text-sm font-medium text-stone-600">Valores</label>
              <button
                type="button"
                onClick={addValor}
                className="text-indigo-600 hover:text-indigo-700 text-xs font-medium flex items-center gap-1 transition-colors"
              >
                <Plus className="w-3.5 h-3.5" /> Añadir
              </button>
            </div>
            <div className="space-y-2">
              {(edited.valores || []).map((valor, i) => (
                <div key={i} className="flex gap-2">
                  <input
                    type="text"
                    value={valor}
                    onChange={(e) => updateValor(i, e.target.value)}
                    placeholder="Ej: Cooperación, Empatía..."
                    className="flex-1 px-3 py-2 border border-stone-200 rounded-lg bg-white text-stone-900 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-400 transition-colors"
                  />
                  <button
                    type="button"
                    onClick={() => removeValor(i)}
                    className="text-stone-300 hover:text-red-500 px-1.5 transition-colors"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          </div>

          {/* Antagonista */}
          <div className="border border-stone-200 p-4 rounded-lg">
            <h3 className="text-sm font-medium text-stone-700 mb-3">Antagonista</h3>
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-stone-600 mb-1.5">Nombre</label>
                <input
                  type="text"
                  value={edited.antagonista?.nombre || ''}
                  onChange={(e) => updateAntagonista('nombre', e.target.value)}
                  className="w-full px-3 py-2 border border-stone-200 rounded-lg bg-white text-stone-900 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-400 transition-colors"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-stone-600 mb-1.5">Descripción</label>
                <Textarea
                  value={edited.antagonista?.descripcion || ''}
                  onChange={(e) => updateAntagonista('descripcion', e.target.value)}
                  rows={2}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-stone-600 mb-1.5">Representación Visual</label>
                <input
                  type="text"
                  value={edited.antagonista?.representacionVisual || ''}
                  onChange={(e) => updateAntagonista('representacionVisual', e.target.value)}
                  className="w-full px-3 py-2 border border-stone-200 rounded-lg bg-white text-stone-900 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-400 transition-colors"
                />
              </div>
            </div>
          </div>

          {/* Expansión */}
          <div>
            <label className="block text-sm font-medium text-stone-600 mb-1.5">Expansión</label>
            <Textarea
              value={edited.expansion || ''}
              onChange={(e) => updateField('expansion', e.target.value)}
              placeholder="Ideas para expandir la serie..."
              rows={2}
            />
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-stone-100">
          <Button variant="ghost" size="sm" onClick={onClose}>
            Cancelar
          </Button>
          <Button size="sm" onClick={handleSave}>
            <Save className="w-3.5 h-3.5" />
            Guardar
          </Button>
        </div>
      </div>
    </div>
  );
}
