'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(s)
      if (e.key === 'Delete' || e.key === 'Backspace') {
        const ids = selection.clipIds?.length
          ? selection.clipIds
          : selection.clipId
            ? [selection.clipId]
            : [];
        if (ids.length > 0) {
          e.preventDefault();
          useEditor.getState().removeClips(ids);
          return;
        }
      }

      // Cmd/Ctrl+A — select all clips
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'a') {
        e.preventDefault();
        useEditor.getState().setClipIds(useEditor.getState().clips.map((c) => c.id));
        return;
      }

      // Cmd/Ctrl+D — duplicate selected clips
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'd') {
        const ids = selection.clipIds?.length
          ? selection.clipIds
          : selection.clipId
            ? [selection.clipId]
            : [];
        if (ids.length > 0) {
          e.preventDefault();
          useEditor.getState().duplicateClips(ids);
          return;
        }
      }

      // Cmd/Ctrl+G — group selected clips
      if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === 'g') {
        const ids = selection.clipIds?.length
          ? selection.clipIds
          : selection.clipId
            ? [selection.clipId]
            : [];
        if (ids.length > 0) {
          e.preventDefault();
          const groupId = `g-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
          const idSet = new Set(ids);
          useEditor.setState((s) => ({
            clips: s.clips.map((c) => (idSet.has(c.id) ? { ...c, groupId } : c)),
          }));
          useEditor.getState().setToast({ message: `จัดกลุ่ม ${ids.length} คลิป`, level: 'success' });
          return;
        }
      }

      // Cmd/Ctrl+Shift+G — ungroup
      if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'g') {
        const ids = selection.clipIds?.length
          ? selection.clipIds
          : selection.clipId
            ? [selection.clipId]
            : [];
        if (ids.length > 0) {
          e.preventDefault();
          const idSet = new Set(ids);
          useEditor.setState((s) => ({
            clips: s.clips.map((c) => (idSet.has(c.id) ? { ...c, groupId: undefined } : c)),
          }));
          useEditor.getState().setToast({ message: 'เลิกจัดกลุ่ม', level: 'success' });
          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;
}