import { Icon } from '@iconify-icon/react';
import { useEffect, useRef, useState } from 'react';

interface Item {
  name: string;
  icon: string;
  level: 'primary' | 'secondary';
}

interface Props {
  label: string;
  items: Item[];
  accent?: 'cyan' | 'acid' | 'magenta';
  bpm?: number;
  index?: number;
}

const accentMap = {
  cyan: 'var(--color-cyan)',
  acid: 'var(--color-acid)',
  magenta: 'var(--color-magenta)',
};

export default function RackModule({
  label,
  items,
  accent = 'cyan',
  bpm = 174,
  index = 0,
}: Props) {
  const color = accentMap[accent];
  const [levels, setLevels] = useState<number[]>([]);
  const rafRef = useRef<number | null>(null);

  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setLevels([0.6, 0.5, 0.7, 0.4]);
      return;
    }
    const start = performance.now() + index * 137;
    const tick = (now: number) => {
      const t = (now - start) / 1000;
      setLevels([
        0.5 + 0.3 * Math.abs(Math.sin(t * 2.1)),
        0.4 + 0.35 * Math.abs(Math.sin(t * 2.8 + 1)),
        0.6 + 0.25 * Math.abs(Math.sin(t * 1.5 + 2)),
        0.3 + 0.4 * Math.abs(Math.sin(t * 3.2 + 0.5)),
      ]);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
    };
  }, [index]);

  return (
    <article
      className="relative bg-[color:var(--color-surface)] border border-[color:var(--color-border)] rounded-sm overflow-hidden"
      style={{ boxShadow: `inset 0 1px 0 rgba(255,255,255,0.03)` }}
    >
      {/* Top bar : LED + label + BPM */}
      <div
        className="flex items-center justify-between px-4 py-2.5 border-b border-[color:var(--color-border)] bg-[color:var(--color-surface-2)]"
        style={{ boxShadow: `inset 0 -1px 0 ${color}22` }}
      >
        <div className="flex items-center gap-2.5">
          <span
            className="led"
            style={{ background: color, boxShadow: `0 0 8px ${color}` }}
          />
          <span
            className="font-stencil text-sm uppercase tracking-[0.25em]"
            style={{ color, textShadow: `0 0 10px ${color}80` }}
          >
            {label}
          </span>
        </div>
        <span className="font-mono text-[10px] uppercase tracking-widest text-[color:var(--color-text-dim)]">
          [{bpm} bpm]
        </span>
      </div>

      {/* Body : VU meter (vertical bars) + pads grid */}
      <div className="flex gap-4 p-4">
        {/* VU meter */}
        <div
          className="flex flex-col gap-1 w-3 pt-1"
          aria-hidden="true"
          style={{ justifyContent: 'flex-end' }}
        >
          {[0.9, 0.75, 0.6, 0.45, 0.3, 0.15].map((threshold, i) => {
            const on = (levels[i % 4] ?? 0) > threshold;
            return (
              <span
                key={i}
                className="block w-full h-1 rounded-[1px] transition-opacity"
                style={{
                  background: on ? color : `${color}20`,
                  boxShadow: on ? `0 0 6px ${color}` : 'none',
                }}
              />
            );
          })}
        </div>

        {/* Pads grid */}
        <div className="grid grid-cols-3 sm:grid-cols-4 gap-2 flex-1 content-start">
          {items.map((item) => (
            <button
              key={item.name}
              type="button"
              className="group relative aspect-square flex flex-col items-center justify-center gap-1 bg-[color:var(--color-bg)] border border-[color:var(--color-border)] rounded-sm transition-all hover:translate-y-px active:translate-y-0.5"
              style={{
                boxShadow: `inset 0 -2px 0 ${color}15`,
              }}
              title={item.name}
              onMouseEnter={(e) => {
                (e.currentTarget.style.borderColor = `${color}aa`);
                (e.currentTarget.style.boxShadow = `0 0 20px ${color}44, inset 0 -2px 0 ${color}66`);
              }}
              onMouseLeave={(e) => {
                (e.currentTarget.style.borderColor = '');
                (e.currentTarget.style.boxShadow = `inset 0 -2px 0 ${color}15`);
              }}
            >
              <Icon icon={item.icon} width="20" height="20" />
              <span className="text-[9px] font-mono uppercase tracking-wider text-[color:var(--color-text-muted)] group-hover:text-[color:var(--color-text)] transition-colors truncate max-w-full px-1">
                {item.name}
              </span>
              <span
                className="absolute top-1 right-1 w-1 h-1 rounded-full opacity-30 group-hover:opacity-100 transition-opacity"
                style={{ background: color, boxShadow: `0 0 4px ${color}` }}
              />
            </button>
          ))}
        </div>
      </div>

      {/* Bottom bar : screws / decoration */}
      <div className="flex items-center justify-between px-4 py-1.5 border-t border-[color:var(--color-border)] bg-[color:var(--color-surface-2)]">
        <span className="font-mono text-[9px] text-[color:var(--color-text-dim)] uppercase tracking-widest">
          CH_{String(index + 1).padStart(2, '0')}
        </span>
        <div className="flex gap-2">
          {[0, 1].map((i) => (
            <span
              key={i}
              className="w-1.5 h-1.5 rounded-full bg-[color:var(--color-border)]"
            />
          ))}
        </div>
      </div>
    </article>
  );
}
