import React, { useState, useMemo } from 'react';
import { Type, Image as ImageIcon, Trash2, Wand2, Loader2, Lock, Maximize, Layers, ChevronDown, ChevronRight, Check, Sparkles, ArrowUp, ArrowDown, ArrowRight, ZoomIn, Disc3, Pipette, Copy, Eye, EyeOff, Clipboard, ClipboardPaste, FlipHorizontal } from 'lucide-react';
import { TimelineElement, DesignMD } from '../../types';
import { updateElementAtIndex, updateElementKeyframes, updateElementTransition } from '../../utils/updateElement';
import { uploadMedia } from '../../utils/mediaUploader';
import { CHROMA_KEY_PRESETS } from '../../utils/chromaKeyUtils';
import { FileDropZone } from '../ui/FileDropZone';
import { ColorPaletteExtractor } from '../ui/ColorPaletteExtractor';
import { FontPicker } from '../ui/FontPicker';
import { AudioElementProperties } from './AudioElementProperties';
import { AnimatedTextPresets } from '../text/AnimatedTextPresets';
import { FilterPresets } from '../ui/FilterPresets';
import { TextStylePresets } from '../ui/TextStylePresets';
import { CollapsibleSection } from '../ui/CollapsibleSection';
import { FieldInspector } from '../ui/FieldInspector';
import { useColorHistory } from '../../hooks/useColorHistory';
import { removeImageBackground } from '../../utils/backgroundRemoval';

import { TextPropertiesPanel } from './TextPropertiesPanel';
import { ImagePropertiesPanel } from './ImagePropertiesPanel';
import { VideoPropertiesPanel } from './VideoPropertiesPanel';
import { ShapePropertiesPanel } from './ShapePropertiesPanel';
interface ElementPropertiesPanelProps {
  selectedElementId: string;
  setSelectedElementId: (id: string | null) => void;
  timelineElements: TimelineElement[];
  setTimelineElements: React.Dispatch<React.SetStateAction<TimelineElement[]>>;
  timeUnit: 'frames' | 'seconds';
  activeLayerId: string;
  designMD: DesignMD;
  outputFormat?: 'video' | 'image';
}

// ─── Transition Definitions ──────────────────────────────
const TRANSITIONS = [
  { value: 'none', label: 'Corte Rápido', desc: 'Sin transición', icon: '⚡' },
  { value: 'fade', label: 'Fundido', desc: 'Aparece/desaparece suavemente', icon: '🌅' },
  { value: 'slideUp', label: 'Deslizar Arriba', desc: 'Entra desde abajo', icon: '⬆' },
  { value: 'slideDown', label: 'Deslizar Abajo', desc: 'Entra desde arriba', icon: '⬇' },
  { value: 'slideLeft', label: 'Deslizar Izquierda', desc: 'Entra desde la derecha', icon: '⬅' },
  { value: 'slideRight', label: 'Deslizar Derecha', desc: 'Entra desde la izquierda', icon: '➡' },
  { value: 'scale', label: 'Escalar', desc: 'Zoom In / Zoom Out', icon: '🔍' },
  { value: 'bounce', label: 'Rebote', desc: 'Efecto de rebote elástico', icon: '🏀' },
  { value: 'blur', label: 'Desenfoque', desc: 'Aparece con desenfoque', icon: '🌊' },
  { value: 'spin', label: 'Girar', desc: 'Rotación de 360°', icon: '🔄' },
  { value: 'flip', label: 'Voltear', desc: 'Giro 3D horizontal', icon: '🪞' },
] as const;

const TEXT_ONLY_TRANSITIONS = [
  { value: 'typewriter', label: 'Máquina de Escribir', desc: 'Letra por letra', icon: '⌨' },
] as const;


// ─── Transition Picker ──────────────────────────────
const TransitionPicker: React.FC<{
  label: string;
  current: string;
  duration: number;
  isText: boolean;
  onChange: (type: string) => void;
  onDurationChange: (d: number) => void;
}> = ({ label, current, duration, isText, onChange, onDurationChange }) => {
  const [open, setOpen] = useState(false);
  const allTransitions = [...TRANSITIONS, ...(isText ? TEXT_ONLY_TRANSITIONS : [])];
  const selected = allTransitions.find(t => t.value === current) || TRANSITIONS[0];
  const hasTransition = current !== 'none';

  return (
    <div className="space-y-2">
      <label className="block text-[10px] font-medium text-neutral-500 uppercase tracking-wider">{label}</label>
      
      {/* Selected transition pill */}
      <button
        onClick={() => setOpen(!open)}
        className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-xs font-medium transition-all border ${
          hasTransition
            ? 'bg-violet-600/15 border-violet-500/40 text-violet-300 hover:border-violet-400/60'
            : 'bg-neutral-950/50 border-neutral-800 text-neutral-400 hover:border-neutral-700'
        }`}
      >
        <span className="text-sm">{selected.icon}</span>
        <span className="flex-1 text-left">{selected.label}</span>
        <ChevronDown size={12} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>

      {/* Dropdown options */}
      {open && (
        <div className="bg-neutral-950 border border-neutral-800 rounded-lg overflow-hidden shadow-xl">
          {allTransitions.map(t => (
            <button
              key={t.value}
              onClick={() => { onChange(t.value); setOpen(false); }}
              className={`w-full flex items-center gap-2.5 px-3 py-2 text-xs transition-colors ${
                current === t.value
                  ? 'bg-violet-600/20 text-violet-300'
                  : 'text-neutral-400 hover:bg-neutral-800/60 hover:text-white'
              }`}
            >
              <span className="text-sm w-5 text-center">{t.icon}</span>
              <div className="flex-1 text-left">
                <div className="font-medium">{t.label}</div>
                <div className="text-[9px] text-neutral-600">{t.desc}</div>
              </div>
              {current === t.value && <Check size={12} className="text-violet-400" />}
            </button>
          ))}
        </div>
      )}

      {/* Duration slider — only shown when a transition is active */}
      {hasTransition && (
        <div className="pl-1 space-y-1">
          <div className="flex justify-between text-[10px] text-neutral-500">
            <span>Duración</span>
            <span className="font-mono">{duration}f ({(duration / 30).toFixed(1)}s)</span>
          </div>
          <input 
            type="range" min="5" max="60" step="1"
            value={duration} 
            onChange={(e) => onDurationChange(parseInt(e.target.value))}
            className="w-full accent-violet-500 h-1" 
          />
          <div className="flex gap-1">
            {[
              { frames: 8, label: '0.25s' },
              { frames: 15, label: '0.5s' },
              { frames: 30, label: '1s' },
              { frames: 45, label: '1.5s' },
              { frames: 60, label: '2s' },
            ].map(d => (
              <button
                key={d.frames}
                onClick={() => onDurationChange(d.frames)}
                title={d.label}
                className={`flex-1 py-0.5 rounded text-[7px] font-mono transition-colors border ${
                  duration === d.frames
                    ? 'bg-violet-500/20 border-violet-500/40 text-violet-300'
                    : 'bg-neutral-900 border-neutral-800 text-neutral-600 hover:text-neutral-400'
                }`}
              >
                {d.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// ─── Slider Row ──────────────────────────────
const SliderRow: React.FC<{
  label: string;
  value: number;
  min: number;
  max: number;
  step?: number;
  suffix?: string;
  onChange: (v: number) => void;
}> = ({ label, value, min, max, step = 1, suffix = '', onChange }) => {
  const [isEditing, setIsEditing] = React.useState(false);
  const [editVal, setEditVal] = React.useState('');
  const dragRef = React.useRef<{ startX: number; startVal: number } | null>(null);

  const commitEdit = () => {
    const parsed = parseFloat(editVal);
    if (!isNaN(parsed)) onChange(Math.max(min, Math.min(max, parsed)));
    setIsEditing(false);
  };

  return (
    <div>
      <div className="flex justify-between text-[10px] text-neutral-500 mb-0.5">
        <span>{label}</span>
        {isEditing ? (
          <input
            type="text"
            autoFocus
            value={editVal}
            onChange={(e) => setEditVal(e.target.value)}
            onBlur={commitEdit}
            onKeyDown={(e) => { if (e.key === 'Enter') commitEdit(); if (e.key === 'Escape') setIsEditing(false); }}
            className="w-14 bg-neutral-900 border border-violet-500 rounded px-1 text-right font-mono text-[10px] text-white outline-none"
          />
        ) : (
          <span
            className="font-mono cursor-ew-resize select-none hover:text-violet-300 transition-colors"
            title="Click para editar · Arrastra para ajustar"
            onPointerDown={(e) => {
              e.preventDefault();
              dragRef.current = { startX: e.clientX, startVal: value };
              (e.target as HTMLElement).setPointerCapture(e.pointerId);
            }}
            onPointerMove={(e) => {
              if (!dragRef.current) return;
              const delta = (e.clientX - dragRef.current.startX) / 2;
              const newVal = Math.max(min, Math.min(max, dragRef.current.startVal + delta * step));
              onChange(step < 1 ? Math.round(newVal * 10) / 10 : Math.round(newVal));
            }}
            onPointerUp={(e) => {
              if (dragRef.current && Math.abs(e.clientX - dragRef.current.startX) < 3) {
                setEditVal(String(typeof value === 'number' ? (Number.isInteger(value) ? value : value.toFixed(1)) : value));
                setIsEditing(true);
              }
              dragRef.current = null;
              (e.target as HTMLElement).releasePointerCapture(e.pointerId);
            }}
            onWheel={(e) => {
              e.preventDefault();
              const dir = e.deltaY > 0 ? -1 : 1;
              const mult = e.shiftKey ? 10 : 1;
              onChange(Math.max(min, Math.min(max, value + dir * step * mult)));
            }}
          >
            {typeof value === 'number' ? (Number.isInteger(value) ? value : value.toFixed(1)) : value}{suffix}
          </span>
        )}
      </div>
      <input 
        type="range" min={min} max={max} step={step}
        value={value} 
        onChange={(e) => onChange(step < 1 ? parseFloat(e.target.value) : parseInt(e.target.value))}
        className="w-full accent-violet-500 h-1" 
      />
    </div>
  );
};

export const ElementPropertiesPanel: React.FC<ElementPropertiesPanelProps> = ({
  selectedElementId,
  setSelectedElementId,
  timelineElements,
  setTimelineElements,
  timeUnit,
  activeLayerId,
  designMD,
  outputFormat
}) => {
  const [isTranscribing, setIsTranscribing] = useState(false);
  const [isRemovingBg, setIsRemovingBg] = useState(false);
  const [copiedStyle, setCopiedStyle] = useState<Partial<TimelineElement> | null>(null);
  const { recentColors, addColor } = useColorHistory();

  const selectedElementIndex = timelineElements.findIndex(el => el.id === selectedElementId);
  const el = selectedElementIndex !== -1 ? timelineElements[selectedElementIndex] : null;

  if (!el) return null;

  // Delegate audio elements to the dedicated audio panel
  if (el.type === 'audio') {
    return (
      <AudioElementProperties
        element={el}
        elementIndex={selectedElementIndex}
        setTimelineElements={setTimelineElements}
        setSelectedElementId={setSelectedElementId}
        timeUnit={timeUnit}
        activeLayerId={activeLayerId}
        timelineElements={timelineElements}
      />
    );
  }

  const i = selectedElementIndex;

  const update = (updates: Partial<TimelineElement>) => {
    setTimelineElements(prev => updateElementAtIndex(prev, i, updates));
  };

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* Header */}
      <div className="px-4 py-3 border-b border-neutral-800 flex items-center justify-between">
        <h2 className="text-xs font-bold text-white flex items-center gap-2">
          {el.type === 'text' ? <Type size={14} className="text-violet-400" /> : el.type === 'video' ? <Sparkles size={14} className="text-sky-400" /> : <ImageIcon size={14} className="text-emerald-400" />}
          Propiedades
          {el.isBrandElement && (
            <span className="text-[8px] font-bold uppercase tracking-wider text-amber-400 bg-amber-950/40 px-1.5 py-0.5 rounded flex items-center gap-0.5">
              <Lock size={8} /> Marca
            </span>
          )}
        </h2>
        {!el.isBrandElement && (
          <>
          <button
            onClick={() => {
              setTimelineElements(prev => {
                const idx = prev.findIndex(e => e.id === el.id);
                if (idx < prev.length - 1) {
                  const next = [...prev];
                  [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
                  return next;
                }
                return prev;
              });
            }}
            title="Traer al frente"
            className="text-neutral-500 hover:text-violet-400 p-1 rounded-md hover:bg-violet-500/10 transition-colors"
          >
            <ArrowUp size={14} />
          </button>
          <button
            onClick={() => {
              setTimelineElements(prev => {
                const idx = prev.findIndex(e => e.id === el.id);
                if (idx > 0) {
                  const next = [...prev];
                  [next[idx], next[idx - 1]] = [next[idx - 1], next[idx]];
                  return next;
                }
                return prev;
              });
            }}
            title="Enviar al fondo"
            className="text-neutral-500 hover:text-violet-400 p-1 rounded-md hover:bg-violet-500/10 transition-colors"
          >
            <ArrowDown size={14} />
          </button>
          <button
            onClick={() => update({ isHidden: !el.isHidden })}
            title={el.isHidden ? "Mostrar Elemento" : "Ocultar Elemento"}
            className={`p-1 rounded-md transition-colors ${
              el.isHidden
                ? 'text-amber-400 bg-amber-500/10 hover:bg-amber-500/20'
                : 'text-neutral-500 hover:text-sky-400 hover:bg-sky-500/10'
            }`}
          >
            {el.isHidden ? <EyeOff size={14} /> : <Eye size={14} />}
          </button>
          <button
            onClick={() => update({ isLocked: !el.isLocked })}
            title={el.isLocked ? "Desbloquear Elemento" : "Bloquear Elemento"}
            className={`p-1 rounded-md transition-colors ${
              el.isLocked
                ? 'text-red-400 bg-red-500/10 hover:bg-red-500/20'
                : 'text-neutral-500 hover:text-amber-400 hover:bg-amber-500/10'
            }`}
          >
            <Lock size={14} />
          </button>
          <button
            onClick={() => {
              const { id, content, layerId, startFrame, endFrame, isBrandElement, elementName, ...style } = el;
              setCopiedStyle(style);
            }}
            title="Copiar Estilo"
            className="text-neutral-500 hover:text-sky-400 p-1 rounded-md hover:bg-sky-500/10 transition-colors"
          >
            <Clipboard size={14} />
          </button>
          {copiedStyle && (
            <button
              onClick={() => {
                const { type, ...styleProps } = copiedStyle;
                update(styleProps);
              }}
              title="Pegar Estilo"
              className="text-sky-400 hover:text-sky-300 p-1 rounded-md bg-sky-500/10 hover:bg-sky-500/20 transition-colors"
            >
              <ClipboardPaste size={14} />
            </button>
          )}
          <button
            onClick={() => {
              const copy = { ...el, id: 'el-' + Date.now(), isBrandElement: false, isLocked: false, x: (el.x ?? 50) + 2, y: (el.y ?? 50) + 2 };
              setTimelineElements(prev => [...prev, copy]);
              setSelectedElementId(copy.id);
            }}
            title="Duplicar Elemento"
            className="text-neutral-500 hover:text-emerald-400 p-1 rounded-md hover:bg-emerald-500/10 transition-colors"
          >
            <Copy size={14} />
          </button>
          <button
            onClick={() => {
              const mirroredX = 100 - (el.x ?? 50);
              const copy = { ...el, id: 'el-' + Date.now(), isBrandElement: false, isLocked: false, x: mirroredX, flipH: !el.flipH };
              setTimelineElements(prev => [...prev, copy]);
              setSelectedElementId(copy.id);
            }}
            title="Duplicar Espejo (reflejo horizontal)"
            className="text-neutral-500 hover:text-cyan-400 p-1 rounded-md hover:bg-cyan-500/10 transition-colors"
          >
            <FlipHorizontal size={14} />
          </button>
          <button 
            onClick={() => {
              setTimelineElements(prev => prev.filter(e => e.id !== selectedElementId));
              setSelectedElementId(null);
            }}
            title="Eliminar Elemento"
            className="text-neutral-500 hover:text-red-400 p-1 rounded-md hover:bg-red-500/10 transition-colors"
          >
            <Trash2 size={14} />
          </button>
          </>
        )}
      </div>
      
      {/* Element Info Bar */}
      <div className="px-4 py-1.5 border-b border-neutral-800/30 flex items-center gap-3 text-[9px] text-neutral-500 bg-neutral-900/30">
        <span className="flex items-center gap-1">
          <span className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: el.type === 'text' ? '#a78bfa' : el.type === 'image' ? '#34d399' : el.type === 'video' ? '#f472b6' : el.type === 'audio' ? '#38bdf8' : el.type === 'shape' ? '#fbbf24' : '#9ca3af' }} />
          {el.type.charAt(0).toUpperCase() + el.type.slice(1)}
        </span>
        <span className="font-mono">{((el.endFrame - el.startFrame) / 30).toFixed(1)}s</span>
        <span className="font-mono text-neutral-600">F{el.startFrame}–{el.endFrame}</span>
        {el.isLocked && <span className="text-red-400">🔒</span>}
        {!el.isBrandElement && (
          <div className="ml-auto flex items-center gap-1">
            <input
              type="number"
              value={el.startFrame}
              onChange={(e) => update({ startFrame: Math.max(0, parseInt(e.target.value) || 0) })}
              className="w-12 bg-neutral-900 border border-neutral-800 rounded px-1 py-0.5 text-[8px] text-neutral-400 font-mono text-center"
              title="Frame inicial"
            />
            <span className="text-neutral-700">—</span>
            <input
              type="number"
              value={el.endFrame}
              onChange={(e) => update({ endFrame: Math.max(el.startFrame + 1, parseInt(e.target.value) || 0) })}
              className="w-12 bg-neutral-900 border border-neutral-800 rounded px-1 py-0.5 text-[8px] text-neutral-400 font-mono text-center"
              title="Frame final"
            />
          </div>
        )}
      </div>

      {/* Element Name */}
      {!el.isBrandElement && (
        <div className="px-4 py-1 border-b border-neutral-800/20">
          <input
            type="text"
            value={el.elementName ?? ''}
            onChange={(e) => update({ elementName: e.target.value })}
            placeholder={`${el.type === 'text' ? (el.content?.slice(0, 20) || 'Texto') : el.type.charAt(0).toUpperCase() + el.type.slice(1)}`}
            className="w-full bg-transparent border-0 text-[10px] text-neutral-300 placeholder-neutral-600 focus:outline-none py-0.5"
            title="Nombre del elemento"
          />
        </div>
      )}

      {/* Element Notes (collapsible) */}
      {!el.isBrandElement && (
        <div className="px-4 py-0.5 border-b border-neutral-800/20">
          <details>
            <summary className="text-[8px] text-neutral-600 cursor-pointer hover:text-neutral-400 select-none">
              📝 Notas {el.notes ? `(${el.notes.length})` : ''}
            </summary>
            <textarea
              value={el.notes ?? ''}
              onChange={(e) => update({ notes: e.target.value })}
              placeholder="Añadir notas sobre este elemento..."
              className="w-full bg-neutral-950 border border-neutral-800 rounded text-[9px] text-neutral-400 placeholder-neutral-700 p-1.5 mt-1 resize-none outline-none focus:border-violet-500/40"
              rows={2}
              title="Notas del elemento"
            />
          </details>
        </div>
      )}

      <div className="px-4 py-3 overflow-y-auto custom-scrollbar flex-1">
        {el.type === 'text' && (
          <TextPropertiesPanel
            el={el} i={i} update={update}
            timelineElements={timelineElements} setTimelineElements={setTimelineElements}
            timeUnit={timeUnit} activeLayerId={activeLayerId} designMD={designMD} outputFormat={outputFormat}
            isTranscribing={isTranscribing} setIsTranscribing={setIsTranscribing}
            isRemovingBg={isRemovingBg} setIsRemovingBg={setIsRemovingBg}
            addColor={addColor} recentColors={recentColors} selectedElementId={selectedElementId}
          />
        )}
        {(el.type === 'image' || el.type === 'sticker') && (
          <ImagePropertiesPanel
            el={el} i={i} update={update}
            timelineElements={timelineElements} setTimelineElements={setTimelineElements}
            timeUnit={timeUnit} activeLayerId={activeLayerId} designMD={designMD} outputFormat={outputFormat}
            isTranscribing={isTranscribing} setIsTranscribing={setIsTranscribing}
            isRemovingBg={isRemovingBg} setIsRemovingBg={setIsRemovingBg}
            addColor={addColor} recentColors={recentColors} selectedElementId={selectedElementId}
          />
        )}
        {el.type === 'video' && (
          <VideoPropertiesPanel
            el={el} i={i} update={update}
            timelineElements={timelineElements} setTimelineElements={setTimelineElements}
            timeUnit={timeUnit} activeLayerId={activeLayerId} designMD={designMD} outputFormat={outputFormat}
            isTranscribing={isTranscribing} setIsTranscribing={setIsTranscribing}
            isRemovingBg={isRemovingBg} setIsRemovingBg={setIsRemovingBg}
            addColor={addColor} recentColors={recentColors} selectedElementId={selectedElementId}
          />
        )}
        {el.type === 'shape' && (
          <ShapePropertiesPanel
            el={el} i={i} update={update}
            timelineElements={timelineElements} setTimelineElements={setTimelineElements}
            timeUnit={timeUnit} activeLayerId={activeLayerId} designMD={designMD} outputFormat={outputFormat}
            isTranscribing={isTranscribing} setIsTranscribing={setIsTranscribing}
            isRemovingBg={isRemovingBg} setIsRemovingBg={setIsRemovingBg}
            addColor={addColor} recentColors={recentColors} selectedElementId={selectedElementId}
          />
        )}
</div>
    </div>
  );
};
