'use client';

import { Infinity } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import type { AnimationConfig } from '@/types/animate';

interface Props {
  config: AnimationConfig;
  onChange: (config: AnimationConfig) => void;
}

const EASINGS = [
  { value: 'linear', label: 'Linear' },
  { value: 'ease', label: 'Ease' },
  { value: 'ease-in', label: 'Ease In' },
  { value: 'ease-out', label: 'Ease Out' },
  { value: 'ease-in-out', label: 'Ease In Out' },
  { value: 'cubic-bezier', label: 'Cubic Bézier' },
  { value: 'steps(4, end)', label: 'Steps (4)' },
  { value: 'steps(8, end)', label: 'Steps (8)' },
];

const DIRECTIONS: { value: AnimationConfig['direction']; label: string }[] = [
  { value: 'normal', label: 'Normal' },
  { value: 'reverse', label: 'Reverse' },
  { value: 'alternate', label: 'Alt' },
  { value: 'alternate-reverse', label: 'Alt-Rev' },
];

const FILL_MODES: { value: AnimationConfig['fillMode']; label: string }[] = [
  { value: 'none', label: 'None' },
  { value: 'forwards', label: 'Fwd' },
  { value: 'backwards', label: 'Bwd' },
  { value: 'both', label: 'Both' },
];

const inputCls =
  'w-full bg-transparent border border-border/40 rounded-lg px-3 py-2 text-xs font-mono outline-none focus:border-primary/50 transition-colors text-foreground/80 placeholder:text-muted-foreground/30';

const pillCls = (active: boolean) =>
  cn(
    'flex-1 py-1.5 rounded-lg border text-[10px] font-mono transition-all',
    active
      ? 'bg-primary/10 border-primary/40 text-primary'
      : 'border-border/30 text-muted-foreground hover:border-primary/30 hover:text-foreground'
  );

export function AnimationSettings({ config, onChange }: Props) {
  const set = <K extends keyof AnimationConfig>(key: K, value: AnimationConfig[K]) =>
    onChange({ ...config, [key]: value });

  const isInfinite = config.iterationCount === 'infinite';
  const isCubic = config.easing.startsWith('cubic-bezier');

  const cubicValues = (() => {
    const m = config.easing.match(/cubic-bezier\(([^)]+)\)/);
    if (!m) return [0.25, 0.1, 0.25, 1.0];
    return m[1].split(',').map(Number);
  })();

  const setCubic = (index: number, val: number) => {
    const v = [...cubicValues];
    v[index] = val;
    set('easing', `cubic-bezier(${v.join(',')})`);
  };

  const easingSelectValue = isCubic ? 'cubic-bezier' : config.easing;

  return (
    <div className="space-y-4">

      <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest block">
        Settings
      </span>

      {/* Name */}
      <div>
        <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Name</label>
        <input
          type="text"
          value={config.name}
          onChange={(e) => {
            const val = e.target.value.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9-_]/g, '');
            set('name', val || 'myAnimation');
          }}
          className={inputCls}
        />
      </div>

      {/* Duration + Delay */}
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Duration (ms)</label>
          <input
            type="number"
            min={50}
            max={10000}
            step={50}
            value={config.duration}
            onChange={(e) => set('duration', Math.max(50, Number(e.target.value)))}
            className={inputCls}
          />
        </div>
        <div>
          <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Delay (ms)</label>
          <input
            type="number"
            min={0}
            max={5000}
            step={50}
            value={config.delay}
            onChange={(e) => set('delay', Math.max(0, Number(e.target.value)))}
            className={inputCls}
          />
        </div>
      </div>

      {/* Easing */}
      <div>
        <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Easing</label>
        <select
          value={easingSelectValue}
          onChange={(e) => {
            const v = e.target.value;
            set('easing', v === 'cubic-bezier' ? 'cubic-bezier(0.25,0.1,0.25,1)' : v);
          }}
          className="w-full bg-transparent border border-border/40 rounded-lg px-3 py-2 text-xs font-mono outline-none focus:border-primary/50 transition-colors text-foreground/80 cursor-pointer"
        >
          {EASINGS.map((e) => (
            <option key={e.value} value={e.value}>
              {e.label}
            </option>
          ))}
        </select>
      </div>

      {/* Cubic-bezier inputs */}
      {isCubic && (
        <div>
          <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">
            cubic-bezier(P1x, P1y, P2x, P2y)
          </label>
          <div className="grid grid-cols-4 gap-1.5">
            {(['P1x', 'P1y', 'P2x', 'P2y'] as const).map((label, i) => (
              <div key={label}>
                <label className="text-[9px] text-muted-foreground/40 font-mono block mb-1">{label}</label>
                <input
                  type="number"
                  min={i % 2 === 0 ? 0 : -1}
                  max={i % 2 === 0 ? 1 : 2}
                  step={0.01}
                  value={cubicValues[i] ?? 0}
                  onChange={(e) => setCubic(i, Number(e.target.value))}
                  className="w-full bg-transparent border border-border/40 rounded-lg px-2 py-1.5 text-[10px] font-mono outline-none focus:border-primary/50 transition-colors text-foreground/80 text-center"
                />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Iterations */}
      <div>
        <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Iterations</label>
        <div className="flex gap-1.5">
          <input
            type="number"
            min={1}
            max={999}
            value={isInfinite ? '' : (config.iterationCount as number)}
            disabled={isInfinite}
            onChange={(e) => set('iterationCount', Math.max(1, Number(e.target.value)))}
            placeholder="1"
            className={cn(inputCls, 'flex-1', isInfinite && 'opacity-30')}
          />
          <button
            onClick={() => set('iterationCount', isInfinite ? 1 : 'infinite')}
            title="Toggle infinite"
            className={cn(
              'w-9 h-9 flex items-center justify-center rounded-lg border text-xs transition-all shrink-0',
              isInfinite
                ? 'bg-primary/10 border-primary/40 text-primary'
                : 'border-border/40 text-muted-foreground/50 hover:border-primary/30 hover:text-primary'
            )}
          >
            <Infinity className="w-3.5 h-3.5" />
          </button>
        </div>
      </div>

      {/* Direction */}
      <div>
        <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Direction</label>
        <div className="flex gap-1">
          {DIRECTIONS.map(({ value, label }) => (
            <button key={value} onClick={() => set('direction', value)} className={pillCls(config.direction === value)}>
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Fill Mode */}
      <div>
        <label className="text-[9px] text-muted-foreground/50 font-mono block mb-1.5">Fill Mode</label>
        <div className="flex gap-1">
          {FILL_MODES.map(({ value, label }) => (
            <button key={value} onClick={() => set('fillMode', value)} className={pillCls(config.fillMode === value)}>
              {label}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
