import React, { useState } from 'react';
import { ChevronDown, Check } from 'lucide-react';

export 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;

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

export 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>
      
      <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>

      {open && (
        <div className="bg-neutral-950 border border-neutral-800 rounded-lg overflow-hidden shadow-xl mt-1">
          {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>
      )}

      {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 mt-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>
  );
};

export 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>
  );
};
