import { useCallback, useEffect, useRef, useState } from "react";
import { Play, Pause } from "lucide-react";
import type { TimelineSegment } from "@/features/home/model/useTimelineEditor";
import { AppModal, AppModalHeader } from "@/shared/ui/AppModal";

interface ClipTrimmerProps {
  isOpen: boolean;
  segment: TimelineSegment | null;
  materialUrl: string | null;
  onConfirm: (sourceStart: number, sourceEnd: number) => void;
  onClose: () => void;
}

function formatSec(sec: number): string {
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return `${String(m).padStart(2, "0")}:${s.toFixed(1).padStart(4, "0")}`;
}

export function ClipTrimmer({
  isOpen,
  segment,
  materialUrl,
  onConfirm,
  onClose,
}: ClipTrimmerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const [duration, setDuration] = useState(0);
  const [sourceStart, setSourceStart] = useState(0);
  const [sourceEnd, setSourceEnd] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [dragging, setDragging] = useState<"start" | "end" | null>(null);
  const animRef = useRef<number>(0);

  // Reset state when segment changes
  useEffect(() => {
    if (segment && isOpen) {
      setSourceStart(segment.sourceStart);
      setSourceEnd(segment.sourceEnd);
      setCurrentTime(segment.sourceStart);
      setIsPlaying(false);
    }
  }, [segment, isOpen]);

  // Track currentTime during playback
  useEffect(() => {
    if (!isPlaying || !videoRef.current) return;

    const tick = () => {
      if (!videoRef.current) return;
      const t = videoRef.current.currentTime;
      const end = sourceEnd || duration;
      if (t >= end) {
        videoRef.current.pause();
        videoRef.current.currentTime = sourceStart;
        setCurrentTime(sourceStart);
        setIsPlaying(false);
        return;
      }
      setCurrentTime(t);
      animRef.current = requestAnimationFrame(tick);
    };
    animRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(animRef.current);
  }, [isPlaying, sourceStart, sourceEnd, duration]);

  // Seek video when not playing and currentTime changes
  useEffect(() => {
    if (videoRef.current && !isPlaying) {
      videoRef.current.currentTime = currentTime;
    }
  }, [currentTime, isPlaying]);

  const handleLoadedMetadata = useCallback(() => {
    if (videoRef.current) {
      const dur = videoRef.current.duration;
      setDuration(dur);
      if (sourceEnd === 0) {
        setSourceEnd(dur);
      }
    }
  }, [sourceEnd]);

  const togglePlay = useCallback(() => {
    if (!videoRef.current || duration === 0) return;
    if (isPlaying) {
      videoRef.current.pause();
      setIsPlaying(false);
    } else {
      const end = sourceEnd || duration;
      if (videoRef.current.currentTime >= end || videoRef.current.currentTime < sourceStart) {
        videoRef.current.currentTime = sourceStart;
        setCurrentTime(sourceStart);
      }
      videoRef.current.play().catch(() => {});
      setIsPlaying(true);
    }
  }, [isPlaying, sourceStart, sourceEnd, duration]);

  // --- Dual-handle slider logic ---
  const getPositionFromEvent = useCallback(
    (clientX: number) => {
      if (!trackRef.current || duration === 0) return 0;
      const rect = trackRef.current.getBoundingClientRect();
      const ratio = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
      return ratio * duration;
    },
    [duration]
  );

  const handleThumbPointerDown = useCallback(
    (which: "start" | "end", e: React.PointerEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setDragging(which);
      (e.target as HTMLElement).setPointerCapture(e.pointerId);
    },
    []
  );

  const handleTrackPointerMove = useCallback(
    (e: React.PointerEvent) => {
      if (!dragging) return;
      const pos = getPositionFromEvent(e.clientX);
      const minGap = 0.5;
      if (dragging === "start") {
        const clamped = Math.max(0, Math.min(pos, (sourceEnd || duration) - minGap));
        setSourceStart(clamped);
        setCurrentTime(clamped);
      } else {
        const clamped = Math.min(duration, Math.max(pos, sourceStart + minGap));
        setSourceEnd(clamped);
      }
    },
    [dragging, getPositionFromEvent, sourceStart, sourceEnd, duration]
  );

  const handleTrackPointerUp = useCallback(() => {
    setDragging(null);
  }, []);

  const handleConfirm = () => {
    onConfirm(sourceStart, sourceEnd >= duration ? 0 : sourceEnd);
  };

  if (!isOpen || !segment) return null;

  const assignedDur = segment.end - segment.start;
  const effectiveEnd = sourceEnd || duration;
  const clipDur = effectiveEnd - sourceStart;
  const startPct = duration > 0 ? (sourceStart / duration) * 100 : 0;
  const endPct = duration > 0 ? (effectiveEnd / duration) * 100 : 100;
  const playheadPct = duration > 0 ? (currentTime / duration) * 100 : 0;

  return (
    <AppModal
      isOpen={isOpen}
      onClose={onClose}
      panelClassName="w-full max-w-lg mx-4 rounded-2xl border border-white/10 bg-[#171821]/95 shadow-[0_24px_80px_rgba(0,0,0,0.55)] overflow-hidden"
      closeOnOverlay
    >
      <AppModalHeader
        title={`截取设置 - ${segment.materialName}`}
        subtitle="拖拽起止点，精确控制素材片段"
        onClose={onClose}
      />

        {/* Video preview */}
        <div className="px-5 pt-4">
          <div className="relative bg-black rounded-lg overflow-hidden aspect-video group">
            {materialUrl ? (
              <video
                ref={videoRef}
                src={materialUrl}
                className="w-full h-full object-contain"
                onLoadedMetadata={handleLoadedMetadata}
                onEnded={() => setIsPlaying(false)}
                preload="auto"
                muted
              />
            ) : (
              <div className="flex items-center justify-center h-full text-gray-500 text-sm">
                无法加载视频
              </div>
            )}
            {/* Play/Pause overlay */}
            {materialUrl && (
              <button
                onClick={togglePlay}
                className="absolute inset-0 flex items-center justify-center bg-black/0 hover:bg-black/30 transition-colors"
              >
                <div className={`p-3 rounded-full bg-black/60 text-white transition-opacity ${isPlaying ? "opacity-0 group-hover:opacity-100" : "opacity-100"}`}>
                  {isPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6" />}
                </div>
              </button>
            )}
            <div className="absolute bottom-2 right-2 bg-black/70 text-white text-[10px] px-2 py-0.5 rounded pointer-events-none">
              {formatSec(currentTime)}
            </div>
          </div>
        </div>

        {/* Dual-handle range slider */}
        <div className="px-5 py-4 space-y-3">
          <div className="text-xs text-gray-400 flex justify-between">
            <span>源视频时长: {duration > 0 ? formatSec(duration) : "加载中..."}</span>
          </div>

          {/* Custom range track */}
          <div
            ref={trackRef}
            className="relative h-10 cursor-pointer select-none touch-none"
            onPointerMove={handleTrackPointerMove}
            onPointerUp={handleTrackPointerUp}
            onPointerLeave={handleTrackPointerUp}
          >
            {/* Background track */}
            <div className="absolute top-1/2 -translate-y-1/2 left-0 right-0 h-2 bg-white/10 rounded-full" />

            {/* Selected range */}
            <div
              className="absolute top-1/2 -translate-y-1/2 h-2 rounded-full"
              style={{
                left: `${startPct}%`,
                width: `${endPct - startPct}%`,
                backgroundColor: segment.color + "88",
              }}
            />

            {/* Playhead indicator */}
            {duration > 0 && (
              <div
                className="absolute top-1/2 -translate-y-1/2 w-0.5 h-4 bg-white/60 rounded-full pointer-events-none"
                style={{ left: `${playheadPct}%` }}
              />
            )}

            {/* Start thumb */}
            <div
              onPointerDown={(e) => handleThumbPointerDown("start", e)}
              className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-5 h-5 rounded-full bg-purple-500 border-2 border-white shadow-lg cursor-grab active:cursor-grabbing hover:scale-110 transition-transform z-10"
              style={{ left: `${startPct}%` }}
              title={`起点: ${formatSec(sourceStart)}`}
            />

            {/* End thumb */}
            <div
              onPointerDown={(e) => handleThumbPointerDown("end", e)}
              className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-5 h-5 rounded-full bg-pink-500 border-2 border-white shadow-lg cursor-grab active:cursor-grabbing hover:scale-110 transition-transform z-10"
              style={{ left: `${endPct}%` }}
              title={`终点: ${formatSec(effectiveEnd)}`}
            />
          </div>

          {/* Time labels */}
          <div className="flex justify-between text-xs text-gray-400">
            <span className="text-purple-400">{formatSec(sourceStart)}</span>
            <span className="text-pink-400">{formatSec(effectiveEnd)}</span>
          </div>

          {/* Info */}
          <div className="text-[11px] text-gray-500 flex items-center gap-2 flex-wrap">
            <span>截取: {clipDur.toFixed(1)}s</span>
            <span className="text-gray-600">|</span>
            <span>分配: {assignedDur.toFixed(1)}s</span>
            {clipDur < assignedDur && <span className="text-amber-500">(将循环补足)</span>}
            {clipDur > assignedDur && <span className="text-cyan-500">(将截断)</span>}
          </div>
        </div>

        {/* Actions */}
        <div className="flex justify-end gap-2 px-5 pb-4">
          <button
            onClick={onClose}
            className="px-4 py-1.5 text-xs bg-white/10 hover:bg-white/20 rounded-lg text-gray-300 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleConfirm}
            className="px-4 py-1.5 text-xs bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white rounded-lg transition-colors"
          >
            确定
          </button>
        </div>
    </AppModal>
  );
}
