import React, { useCallback, useEffect, useRef, useState } from 'react';
import VideoPlayer, { type VideoPlayerHandle } from './components/player/VideoPlayer';
import VideoList from './components/sidebar/VideoList';
import CaptureList from './components/sidebar/CaptureList';
import AnnotationPanel from './components/sidebar/AnnotationPanel';
import MemoOverlay from './components/overlay/MemoOverlay';
import AddAnnotationModal from './components/AddAnnotationModal';
import HelpOverlay from './components/HelpOverlay';
import GeoSearch from './components/geo/GeoSearch';
import StationVerify from './components/geo/StationVerify';
import { usePlayerStore } from './store/playerStore';
import { useAnnotations } from './hooks/useAnnotations';

export default function App() {
  const [showModal, setShowModal] = useState(false);
  const [modalTime, setModalTime] = useState(0);
  const [showHelp, setShowHelp] = useState(false);
  const [memoTime, setMemoTime] = useState(0);
  const [rightTab, setRightTab] = useState<'annotation' | 'geo' | 'station'>('annotation');
  // 좌/우 패널: UI 에서 숨김(코드 보존). 다시 표시하려면 true 로.
  const SHOW_LEFT_PANEL = false;
  const SHOW_RIGHT_PANEL = false;
  const playerRef = useRef<VideoPlayerHandle>(null);
  const rafRef = useRef<number>(0);

  // RAF loop for MemoOverlay — avoids timeupdate (~4fps) imprecision
  useEffect(() => {
    const tick = () => {
      const video = playerRef.current?.getVideoElement();
      if (video) setMemoTime(video.currentTime);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, []);

  const { source, currentTime, fps } = usePlayerStore();
  const currentFrame = Math.round(currentTime * (fps || 30));

  const videoId =
    source?.kind === 'server'
      ? source.videoId
      : source?.kind === 'local'
      ? source.file.name
      : null;

  const { annotations, create, update, remove } = useAnnotations(videoId);

  const handleAddMemo = useCallback((time: number) => {
    setModalTime(time);
    setShowModal(true);
  }, []);

  const handleAnnotationCreate = async (
    type: 'subtitle' | 'memo',
    text: string,
    timeStart: number,
    timeEnd: number
  ) => {
    await create({
      type,
      text,
      timeStart,
      timeEnd,
      position: { x: 10, y: 10 },
      size: { width: 30, height: 10 },
      style: { fontSize: 14, color: '#ffffff', backgroundColor: 'rgba(0,0,0,0.75)' },
    });
  };

  const handleExport = (format: string) => {
    if (!videoId) return;
    window.open(`/api/annotations/${videoId}/export?format=${format}`, '_blank');
  };

  const handleSeek = (time: number) => {
    playerRef.current?.seekTo(time);
  };

  return (
    <div className="flex h-screen bg-gray-950 text-white overflow-hidden">
      {/* Left sidebar — top: video list, bottom: captures (UI 숨김, 코드 보존) */}
      {SHOW_LEFT_PANEL && (
      <div className="w-56 flex-shrink-0 bg-gray-900 border-r border-gray-800 flex flex-col">
        <div className="px-4 py-3 border-b border-gray-800">
          <h1 className="text-sm font-bold text-white">StationPlayer</h1>
          <p className="text-xs text-gray-500">스테이션 기반 동영상 플레이어</p>
          <p className="text-xs text-gray-600 mt-0.5">v1.0.0 · {new Date(__BUILD_TIME__).toLocaleString('ko-KR', { month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit' })}</p>
        </div>
        {/* 상단: 서버 영상 목록 */}
        <div className="flex-1 overflow-y-auto border-b border-gray-700 min-h-0">
          <div className="px-4 py-2 text-xs text-gray-500 uppercase tracking-wide">서버 영상</div>
          <VideoList
            onSelect={(id, name) => playerRef.current?.loadServerStream(id, name)}
          />
        </div>
        {/* 하단: 캡처 프레임 미리보기 */}
        <div className="flex-1 overflow-y-auto min-h-0">
          <div className="px-4 py-2 text-xs text-gray-500 uppercase tracking-wide">캡처 프레임</div>
          <CaptureList onSeek={handleSeek} />
        </div>
      </div>
      )}

      {/* Main — player + memo overlay */}
      <div className="flex-1 flex flex-col min-w-0 relative">
        <VideoPlayer
          ref={playerRef}
          onAddMemo={handleAddMemo}
          onToggleHelp={() => setShowHelp(h => !h)}
        />

        {/* Memo overlay — positioned absolute over the player area */}
        <MemoOverlay
          annotations={annotations}
          currentTime={memoTime}
          onUpdate={(id, pos) => update(id, { position: pos })}
          onDelete={remove}
          containerRef={{ current: null }}
        />
      </div>

      {/* Right sidebar — annotation + geo (UI 숨김, 코드 보존) */}
      {SHOW_RIGHT_PANEL && (
      <div className="w-64 flex-shrink-0 bg-gray-900 border-l border-gray-800 flex flex-col">
        {/* 탭 헤더 */}
        <div className="flex border-b border-gray-800 flex-shrink-0">
          <button
            className={`flex-1 py-2.5 text-xs font-semibold transition-colors ${rightTab === 'annotation' ? 'text-white border-b-2 border-blue-500' : 'text-gray-500 hover:text-gray-300'}`}
            onClick={() => setRightTab('annotation')}
          >
            주석
          </button>
          <button
            className={`flex-1 py-2.5 text-xs font-semibold transition-colors ${rightTab === 'geo' ? 'text-white border-b-2 border-blue-500' : 'text-gray-500 hover:text-gray-300'}`}
            onClick={() => setRightTab('geo')}
          >
            지리정보
          </button>
          <button
            className={`flex-1 py-2.5 text-xs font-semibold transition-colors ${rightTab === 'station' ? 'text-white border-b-2 border-yellow-500' : 'text-gray-500 hover:text-gray-300'}`}
            onClick={() => setRightTab('station')}
          >
            측점
          </button>
        </div>
        <div className="flex-1 min-h-0 overflow-hidden">
          {rightTab === 'annotation' && (
            <AnnotationPanel
              annotations={annotations}
              currentTime={currentTime}
              onSeek={handleSeek}
              onDelete={remove}
              onExport={handleExport}
            />
          )}
          {rightTab === 'geo' && (
            <GeoSearch
              currentFrame={currentFrame}
              fps={fps}
              onSeekToFrame={(frame) => handleSeek(frame / fps)}
            />
          )}
          {rightTab === 'station' && (
            <StationVerify
              fps={fps}
              onSeekToFrame={(frame) => handleSeek(frame / (fps || 30))}
            />
          )}
        </div>
      </div>
      )}

      {/* Add annotation modal */}
      {showModal && (
        <AddAnnotationModal
          currentTime={modalTime}
          onAdd={handleAnnotationCreate}
          onClose={() => setShowModal(false)}
        />
      )}

      {/* Help overlay */}
      {showHelp && <HelpOverlay onClose={() => setShowHelp(false)} />}
    </div>
  );
}
