'use client';

import { useEffect } from 'react';
import { useEditor } from '@/store/editor';

export function KeyboardShortcuts() {
  const setPlaying = useEditor((s) => s.setPlaying);
  const setCurrentTime = useEditor((s) => s.setCurrentTime);
  const currentTime = useEditor((s) => s.currentTime);
  const undo = useEditor((s) => s.undo);
  const redo = useEditor((s) => s.redo);
  const splitClipAtCurrent = useEditor((s) => s.splitClipAtCurrent);
  const selection = useEditor((s) => s.selection);
  const clips = useEditor((s) => s.clips);
  const updateClip = useEditor((s) => s.updateClip);
  const pushHistory = useEditor((s) => s.pushHistory);
  const setToast = useEditor((s) => s.setToast);
  const tracks = useEditor((s) => s.tracks);
  const assets = useEditor((s) => s.assets);
  const removeClip = useEditor((s) => s.removeClip);

  useEffect(() => {
    function handler(e: KeyboardEvent) {
      // Skip if focused on input/textarea
      const target = e.target as HTMLElement | null;
      if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) {
        return;
      }
      const s = useEditor.getState();

      // Undo / Redo
      if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === 'z') {
        e.preventDefault();
        undo();
        return;
      }
      if (
        ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'z') ||
        ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'y')
      ) {
        e.preventDefault();
        redo();
        return;
      }

      // Play/Pause
      if (e.code === 'Space') {
        e.preventDefault();
        setPlaying(!s.playing);
        return;
      }

      // J / K / L — rewind / pause / forward
      if (e.key.toLowerCase() === 'j') {
        e.preventDefault();
        setCurrentTime(s.currentTime - (e.shiftKey ? 5 : 1));
        return;
      }
      if (e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setPlaying(false);
        return;
      }
      if (e.key.toLowerCase() === 'l') {
        e.preventDefault();
        setCurrentTime(s.currentTime + (e.shiftKey ? 5 : 1));
        return;
      }

      // I / O — set in/out on selected clip
      if (e.key.toLowerCase() === 'i') {
        if (selection.clipId) {
          const clip = clips.find((c) => c.id === selection.clipId);
          if (clip) {
            pushHistory('ตั้ง in-point');
            const offset = s.currentTime - clip.start;
            updateClip(clip.id, { sourceIn: Math.max(0, clip.sourceIn + offset), duration: Math.max(0.1, clip.duration - offset), start: s.currentTime });
            setToast({ message: 'ตั้ง in-point', level: 'success' });
          }
        }
        return;
      }
      if (e.key.toLowerCase() === 'o') {
        if (selection.clipId) {
          const clip = clips.find((c) => c.id === selection.clipId);
          if (clip) {
            pushHistory('ตั้ง out-point');
            const newDur = Math.max(0.1, s.currentTime - clip.start);
            updateClip(clip.id, { duration: newDur });
            setToast({ message: 'ตั้ง out-point', level: 'success' });
          }
        }
        return;
      }

      // S — split
      if (e.key.toLowerCase() === 's') {
        e.preventDefault();
        splitClipAtCurrent();
        return;
      }

      // Delete / Backspace — delete selected clip
      if ((e.key === 'Delete' || e.key === 'Backspace') && selection.clipId) {
        e.preventDefault();
        removeClip(selection.clipId);
        return;
      }

      // Left/Right arrows — nudge 1 frame (1/30s)
      if (e.key === 'ArrowLeft') {
        e.preventDefault();
        setCurrentTime(Math.max(0, currentTime - 1 / 30));
        return;
      }
      if (e.key === 'ArrowRight') {
        e.preventDefault();
        setCurrentTime(currentTime + 1 / 30);
        return;
      }
    }
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [
    setPlaying,
    setCurrentTime,
    currentTime,
    undo,
    redo,
    splitClipAtCurrent,
    selection,
    clips,
    updateClip,
    pushHistory,
    setToast,
    tracks,
    assets,
    removeClip,
  ]);

  return null;
}