import { useState, useEffect, useRef, useCallback } from 'react';
import { Scissors, Play, Pause, RotateCcw, Check, AlertCircle, Image, ChevronsLeft, ChevronLeft, ChevronRight, ChevronsRight } from 'lucide-react';
import { processApi, jobsApi } from '../api/client';

function formatTime(seconds) {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  const ms = Math.floor((seconds % 1) * 10);
  return `${mins}:${secs.toString().padStart(2, '0')}.${ms}`;
}

function formatTimeDetailed(seconds) {
  return seconds.toFixed(2);
}

export default function VideoTrimmer({ jobId, onTrimComplete, onCancel }) {
  const videoRef = useRef(null);
  const [videoInfo, setVideoInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [trimming, setTrimming] = useState(false);

  // Trim range state
  const [startTime, setStartTime] = useState(0);
  const [endTime, setEndTime] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [cacheBuster, setCacheBuster] = useState(Date.now());

  // Frame preview state
  const [startFrameUrl, setStartFrameUrl] = useState(null);
  const [endFrameUrl, setEndFrameUrl] = useState(null);
  const [loadingStartFrame, setLoadingStartFrame] = useState(false);
  const [loadingEndFrame, setLoadingEndFrame] = useState(false);

  // Load video info
  useEffect(() => {
    const loadVideoInfo = async () => {
      try {
        setLoading(true);
        const response = await processApi.getVideoInfo(jobId);
        setVideoInfo(response.data);
        setEndTime(response.data.duration);
      } catch (err) {
        setError(err.response?.data?.detail || 'Failed to load video info');
      } finally {
        setLoading(false);
      }
    };
    loadVideoInfo();
  }, [jobId]);

  // Update current time while playing
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      setCurrentTime(video.currentTime);
      // Stop at end time
      if (video.currentTime >= endTime) {
        video.pause();
        video.currentTime = startTime;
        setIsPlaying(false);
      }
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    return () => video.removeEventListener('timeupdate', handleTimeUpdate);
  }, [startTime, endTime]);

  // Load frame previews with debouncing
  const loadStartFrame = useCallback(async (time) => {
    setLoadingStartFrame(true);
    try {
      const url = processApi.getFrameUrl(jobId, time);
      setStartFrameUrl(`${url}&t=${Date.now()}`);
    } finally {
      setLoadingStartFrame(false);
    }
  }, [jobId]);

  const loadEndFrame = useCallback(async (time) => {
    setLoadingEndFrame(true);
    try {
      const url = processApi.getFrameUrl(jobId, time);
      setEndFrameUrl(`${url}&t=${Date.now()}`);
    } finally {
      setLoadingEndFrame(false);
    }
  }, [jobId]);

  // Load initial frames when video info is loaded
  useEffect(() => {
    if (videoInfo) {
      loadStartFrame(0);
      loadEndFrame(videoInfo.duration - 0.1);
    }
  }, [videoInfo, loadStartFrame, loadEndFrame]);

  const handlePlayPause = () => {
    const video = videoRef.current;
    if (!video) return;

    if (isPlaying) {
      video.pause();
    } else {
      if (video.currentTime < startTime || video.currentTime >= endTime) {
        video.currentTime = startTime;
      }
      video.play();
    }
    setIsPlaying(!isPlaying);
  };

  const handleSeek = (time) => {
    const video = videoRef.current;
    if (!video) return;
    video.currentTime = time;
    setCurrentTime(time);
  };

  const handleStartChange = (value) => {
    const newStart = Math.max(0, Math.min(parseFloat(value) || 0, endTime - 0.1));
    setStartTime(newStart);
    handleSeek(newStart);
    loadStartFrame(newStart);
  };

  const handleEndChange = (value) => {
    const maxDuration = videoInfo?.duration || 0;
    const newEnd = Math.min(maxDuration, Math.max(parseFloat(value) || 0, startTime + 0.1));
    setEndTime(newEnd);
    handleSeek(Math.max(0, newEnd - 0.5));
    loadEndFrame(newEnd - 0.1);
  };

  const adjustStart = (delta) => {
    const newStart = Math.max(0, Math.min(startTime + delta, endTime - 0.1));
    setStartTime(newStart);
    handleSeek(newStart);
    loadStartFrame(newStart);
  };

  const adjustEnd = (delta) => {
    const maxDuration = videoInfo?.duration || 0;
    const newEnd = Math.min(maxDuration, Math.max(endTime + delta, startTime + 0.1));
    setEndTime(newEnd);
    handleSeek(Math.max(0, newEnd - 0.5));
    loadEndFrame(newEnd - 0.1);
  };

  const handleTrim = async () => {
    if (trimming) return;

    try {
      setTrimming(true);
      // reprocess=false for manual workflow - user will manually proceed to next step
      const response = await processApi.trim(jobId, startTime, endTime, false);
      if (response.data.success) {
        // Update cache buster to reload video with new trimmed version
        setCacheBuster(Date.now());
        // Update video info with new duration
        if (response.data.new_duration) {
          setVideoInfo(prev => ({ ...prev, duration: response.data.new_duration }));
          setEndTime(response.data.new_duration);
          setStartTime(0);
          // Reload frame previews
          loadStartFrame(0);
          loadEndFrame(response.data.new_duration - 0.1);
        }
        onTrimComplete?.(response.data);
      } else {
        setError(response.data.message);
      }
    } catch (err) {
      setError(err.response?.data?.detail || 'Trim failed');
    } finally {
      setTrimming(false);
    }
  };

  const handleReset = () => {
    if (videoInfo) {
      setStartTime(0);
      setEndTime(videoInfo.duration);
      handleSeek(0);
      loadStartFrame(0);
      loadEndFrame(videoInfo.duration - 0.1);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-500"></div>
        <span className="ml-3 text-gray-400">Loading video...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-red-900/20 border border-red-800/50 rounded-xl">
        <div className="flex items-center gap-2 text-red-400">
          <AlertCircle size={18} />
          <span>{error}</span>
        </div>
        <button
          onClick={onCancel}
          className="mt-3 px-4 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600"
        >
          Close
        </button>
      </div>
    );
  }

  const trimmedDuration = endTime - startTime;
  // Add cache buster to ensure video is reloaded after trimming
  const videoUrl = `${jobsApi.downloadOriginal(jobId)}?t=${cacheBuster}`;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Scissors className="text-red-400" size={20} />
          <h3 className="font-semibold text-white">Video Trimmer</h3>
        </div>
        <div className="text-sm text-gray-400">
          Original: {formatTime(videoInfo?.duration || 0)}
        </div>
      </div>

      {/* Video Preview */}
      <div className="relative aspect-[9/16] max-h-[400px] bg-black rounded-lg overflow-hidden mx-auto">
        <video
          key={cacheBuster}
          ref={videoRef}
          src={videoUrl}
          className="w-full h-full object-contain"
          onPlay={() => setIsPlaying(true)}
          onPause={() => setIsPlaying(false)}
        />

        {/* Play button overlay */}
        <button
          onClick={handlePlayPause}
          className="absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 hover:opacity-100 transition-opacity"
        >
          {isPlaying ? (
            <Pause className="text-white" size={48} />
          ) : (
            <Play className="text-white" size={48} />
          )}
        </button>
      </div>

      {/* Frame Preview Section */}
      <div className="flex justify-between gap-4">
        {/* Start Frame Preview */}
        <div className="space-y-2">
          <div className="text-sm text-gray-400 flex items-center gap-1">
            <Image size={14} />
            시작 프레임
          </div>
          <div className="relative w-[68px] h-[120px] bg-gray-800 rounded-lg overflow-hidden border-2 border-green-500/50">
            {loadingStartFrame ? (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-green-500"></div>
              </div>
            ) : startFrameUrl ? (
              <img src={startFrameUrl} alt="Start frame" className="w-full h-full object-cover" />
            ) : null}
          </div>
        </div>

        {/* End Frame Preview */}
        <div className="space-y-2">
          <div className="text-sm text-gray-400 flex items-center gap-1 justify-end">
            <Image size={14} />
            종료 프레임
          </div>
          <div className="relative w-[68px] h-[120px] bg-gray-800 rounded-lg overflow-hidden border-2 border-red-500/50">
            {loadingEndFrame ? (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-red-500"></div>
              </div>
            ) : endFrameUrl ? (
              <img src={endFrameUrl} alt="End frame" className="w-full h-full object-cover" />
            ) : null}
          </div>
        </div>
      </div>

      {/* Timeline */}
      <div className="space-y-3">
        {/* Progress bar */}
        <div className="relative h-8 bg-gray-800 rounded-lg overflow-hidden">
          {/* Selected range */}
          <div
            className="absolute h-full bg-red-500/30"
            style={{
              left: `${(startTime / (videoInfo?.duration || 1)) * 100}%`,
              width: `${((endTime - startTime) / (videoInfo?.duration || 1)) * 100}%`,
            }}
          />

          {/* Current position indicator */}
          <div
            className="absolute top-0 bottom-0 w-1 bg-white"
            style={{
              left: `${(currentTime / (videoInfo?.duration || 1)) * 100}%`,
            }}
          />

          {/* Click to seek */}
          <div
            className="absolute inset-0 cursor-pointer"
            onClick={(e) => {
              const rect = e.currentTarget.getBoundingClientRect();
              const x = e.clientX - rect.left;
              const percent = x / rect.width;
              const time = percent * (videoInfo?.duration || 0);
              handleSeek(Math.max(startTime, Math.min(endTime, time)));
            }}
          />
        </div>

        {/* Start/End controls with precise inputs */}
        <div className="grid grid-cols-2 gap-6">
          {/* Start Time Control */}
          <div className="space-y-2">
            <label className="block text-sm text-gray-400">
              시작: <span className="text-green-400 font-mono">{formatTimeDetailed(startTime)}초</span>
            </label>
            <div className="flex items-center gap-1">
              <button
                onClick={() => adjustStart(-0.5)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="-0.5초"
              >
                <ChevronsLeft size={16} />
              </button>
              <button
                onClick={() => adjustStart(-0.1)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="-0.1초"
              >
                <ChevronLeft size={16} />
              </button>
              <input
                type="number"
                min="0"
                max={endTime - 0.1}
                step="0.1"
                value={startTime.toFixed(1)}
                onChange={(e) => handleStartChange(e.target.value)}
                className="w-16 px-2 py-1 bg-gray-800 border border-gray-600 rounded text-white text-center font-mono text-sm"
              />
              <button
                onClick={() => adjustStart(0.1)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="+0.1초"
              >
                <ChevronRight size={16} />
              </button>
              <button
                onClick={() => adjustStart(0.5)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="+0.5초"
              >
                <ChevronsRight size={16} />
              </button>
            </div>
            <input
              type="range"
              min="0"
              max={videoInfo?.duration || 0}
              step="0.1"
              value={startTime}
              onChange={(e) => handleStartChange(e.target.value)}
              className="w-full accent-green-500"
            />
          </div>

          {/* End Time Control */}
          <div className="space-y-2">
            <label className="block text-sm text-gray-400">
              종료: <span className="text-red-400 font-mono">{formatTimeDetailed(endTime)}초</span>
            </label>
            <div className="flex items-center gap-1">
              <button
                onClick={() => adjustEnd(-0.5)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="-0.5초"
              >
                <ChevronsLeft size={16} />
              </button>
              <button
                onClick={() => adjustEnd(-0.1)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="-0.1초"
              >
                <ChevronLeft size={16} />
              </button>
              <input
                type="number"
                min={startTime + 0.1}
                max={videoInfo?.duration || 0}
                step="0.1"
                value={endTime.toFixed(1)}
                onChange={(e) => handleEndChange(e.target.value)}
                className="w-16 px-2 py-1 bg-gray-800 border border-gray-600 rounded text-white text-center font-mono text-sm"
              />
              <button
                onClick={() => adjustEnd(0.1)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="+0.1초"
              >
                <ChevronRight size={16} />
              </button>
              <button
                onClick={() => adjustEnd(0.5)}
                className="p-1.5 bg-gray-700 hover:bg-gray-600 rounded text-gray-300"
                title="+0.5초"
              >
                <ChevronsRight size={16} />
              </button>
            </div>
            <input
              type="range"
              min="0"
              max={videoInfo?.duration || 0}
              step="0.1"
              value={endTime}
              onChange={(e) => handleEndChange(e.target.value)}
              className="w-full accent-red-500"
            />
          </div>
        </div>

        {/* Duration info */}
        <div className="flex items-center justify-between text-sm">
          <span className="text-gray-400">
            자를 영상 길이: <span className="text-white font-medium">{formatTime(trimmedDuration)}</span>
          </span>
          <span className="text-gray-400">
            제거할 길이: <span className="text-red-400">{formatTime((videoInfo?.duration || 0) - trimmedDuration)}</span>
          </span>
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center justify-between pt-2">
        <button
          onClick={handleReset}
          className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white transition-colors"
        >
          <RotateCcw size={16} />
          초기화
        </button>

        <div className="flex items-center gap-3">
          <button
            onClick={onCancel}
            className="px-4 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors"
          >
            취소
          </button>
          <button
            onClick={handleTrim}
            disabled={trimming || trimmedDuration < 1}
            className="flex items-center gap-2 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {trimming ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                자르는 중...
              </>
            ) : (
              <>
                <Check size={16} />
                영상 자르기
              </>
            )}
          </button>
        </div>
      </div>

      {/* Help text */}
      <p className="text-xs text-gray-500 text-center">
        « » 0.5초 이동 · ‹ › 0.1초 이동 · 프레임 미리보기로 정확한 지점 확인
      </p>
    </div>
  );
}
