'use client';

import { useState } from 'react';
import { Sparkles, Save, Edit3, Palette } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import type { FondoReferencia } from '@/types/project';

interface FondoCardProps {
  fondo: FondoReferencia;
  onGenerate: (fondoId: string) => Promise<void>;
  onUpdateDescription: (fondoId: string, descripcion: string, promptGeneracion: string) => Promise<void>;
  generating: boolean;
  disabled: boolean;
  cacheKey: number;
}

export function FondoCard({ fondo, onGenerate, onUpdateDescription, generating, disabled, cacheKey }: FondoCardProps) {
  const [editing, setEditing] = useState(false);
  const [descripcionDraft, setDescripcionDraft] = useState(fondo.descripcion);
  const [promptDraft, setPromptDraft] = useState(fondo.promptGeneracion);
  const [saving, setSaving] = useState(false);

  const handleStartEdit = () => {
    setDescripcionDraft(fondo.descripcion);
    setPromptDraft(fondo.promptGeneracion);
    setEditing(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await onUpdateDescription(fondo.id, descripcionDraft, promptDraft);
      setEditing(false);
    } finally {
      setSaving(false);
    }
  };

  const isDirty = descripcionDraft !== fondo.descripcion || promptDraft !== fondo.promptGeneracion;

  return (
    <div className={`rounded-lg border overflow-hidden ${fondo.imagenUrl ? 'border-stone-200' : 'border-dashed border-stone-300'}`}>
      {fondo.imagenUrl ? (
        <img
          src={`${fondo.imagenUrl}?v=${cacheKey}`}
          alt={fondo.nombre}
          className="w-full object-cover bg-stone-50"
          style={{ aspectRatio: '16/9' }}
        />
      ) : (
        <div className="w-full bg-stone-50 flex items-center justify-center" style={{ aspectRatio: '16/9' }}>
          <Palette className="w-6 h-6 text-stone-300" />
        </div>
      )}
      <div className="px-3 py-2">
        <div className="flex items-center justify-between mb-1">
          <span className="text-xs font-medium text-stone-700 truncate">{fondo.segmentoId} {fondo.nombre}</span>
          {!editing && (
            <button
              onClick={handleStartEdit}
              className="text-[10px] font-medium text-indigo-500 hover:text-indigo-700 transition-colors flex-shrink-0"
            >
              <Edit3 className="w-3 h-3" />
            </button>
          )}
        </div>

        {editing ? (
          <div className="space-y-2 mt-1">
            <div>
              <label className="text-[10px] font-medium text-stone-500 block mb-0.5">Descripción del escenario</label>
              <textarea
                value={descripcionDraft}
                onChange={(e) => setDescripcionDraft(e.target.value)}
                rows={2}
                className="w-full px-2 py-1.5 text-xs border border-stone-200 rounded bg-white text-stone-700 focus:outline-none focus:ring-1 focus:ring-indigo-400 focus:border-indigo-400 resize-y font-mono transition-colors"
              />
            </div>
            <div>
              <label className="text-[10px] font-medium text-stone-500 block mb-0.5">Prompt de generación (opcional, se auto-genera si vacío)</label>
              <textarea
                value={promptDraft}
                onChange={(e) => setPromptDraft(e.target.value)}
                rows={3}
                placeholder="Dejar vacío para usar el prompt automático basado en la descripción y el estilo visual..."
                className="w-full px-2 py-1.5 text-xs border border-stone-200 rounded bg-white text-stone-700 focus:outline-none focus:ring-1 focus:ring-indigo-400 focus:border-indigo-400 resize-y font-mono transition-colors placeholder:text-stone-300"
              />
            </div>
            <div className="flex items-center justify-end gap-1.5">
              <button
                onClick={() => setEditing(false)}
                className="text-[10px] font-medium text-stone-400 hover:text-stone-600 transition-colors px-2 py-1"
              >
                Cancelar
              </button>
              <Button
                size="sm"
                variant="primary"
                onClick={handleSave}
                loading={saving}
                disabled={!isDirty}
              >
                <Save className="w-3 h-3" />
                Guardar
              </Button>
            </div>
          </div>
        ) : (
          <>
            <p className="text-[10px] text-stone-400 line-clamp-2">{fondo.descripcion}</p>
            {fondo.promptGeneracion && (
              <p className="text-[10px] text-stone-300 mt-0.5 line-clamp-1 font-mono italic">{fondo.promptGeneracion}</p>
            )}
          </>
        )}

        <div className="mt-2 flex gap-1.5">
          <Button
            size="sm"
            variant={fondo.imagenUrl ? 'outline' : 'primary'}
            onClick={() => onGenerate(fondo.id)}
            loading={generating}
            disabled={disabled}
            className="w-full"
          >
            <Sparkles className="w-3 h-3" />
            {fondo.imagenUrl ? 'Regenerar' : 'Generar'}
          </Button>
        </div>
      </div>
    </div>
  );
}
