import { useEffect, useMemo, useState, type RefObject } from "react";
import StepProgress from "./StepProgress";
import type { SessionStep } from "../lib/api";

interface WalkthroughPlayerProps {
    steps: SessionStep[];
    videoRef: RefObject<HTMLVideoElement>;
    onSeekMs: (timestampMs: number) => void;
    onExit: () => void;
}

function WalkthroughPlayer({ steps, videoRef, onSeekMs, onExit }: WalkthroughPlayerProps) {
    const [currentStepIndex, setCurrentStepIndex] = useState(0);
    const [pausedForStep, setPausedForStep] = useState(false);

    const currentStep = useMemo(() => steps[currentStepIndex], [steps, currentStepIndex]);

    useEffect(() => {
        if (!currentStep) return;
        onSeekMs(currentStep.timestamp_start_ms);
        const video = videoRef.current;
        if (!video) return;
        setPausedForStep(false);
        void video.play();
    }, [currentStepIndex, currentStep, onSeekMs, videoRef]);

    useEffect(() => {
        const video = videoRef.current;
        if (!video || !currentStep) return;

        const handleTimeUpdate = () => {
            if (pausedForStep) return;
            const currentMs = video.currentTime * 1000;
            if (currentMs >= currentStep.timestamp_end_ms) {
                video.pause();
                setPausedForStep(true);
            }
        };

        video.addEventListener("timeupdate", handleTimeUpdate);
        return () => video.removeEventListener("timeupdate", handleTimeUpdate);
    }, [videoRef, currentStep, pausedForStep]);

    const goToStep = (index: number) => {
        if (index < 0 || index >= steps.length) return;
        setCurrentStepIndex(index);
    };

    const continueToNext = () => {
        if (currentStepIndex < steps.length - 1) {
            goToStep(currentStepIndex + 1);
            return;
        }
        onExit();
    };

    useEffect(() => {
        if (!pausedForStep) return;
        if (!currentStep?.autoplay) return;

        const timer = window.setTimeout(() => {
            if (currentStepIndex < steps.length - 1) {
                setCurrentStepIndex((index) => Math.min(index + 1, steps.length - 1));
                return;
            }
            onExit();
        }, 650);

        return () => window.clearTimeout(timer);
    }, [pausedForStep, currentStep?.autoplay, currentStepIndex, steps.length, onExit]);

    if (!currentStep || steps.length === 0) return null;

    return (
        <div
            style={{
                position: "absolute",
                left: "16px",
                right: "16px",
                bottom: "16px",
                zIndex: 20,
                pointerEvents: "none",
            }}
        >
            <div
                className="glass"
                style={{
                    pointerEvents: "auto",
                    maxWidth: "560px",
                    margin: "0 auto",
                    padding: "14px",
                    borderRadius: "12px",
                    display: "grid",
                    gap: "10px",
                    border: "1px solid rgba(255,255,255,0.15)",
                    background: "rgba(8, 14, 30, 0.88)",
                }}
            >
                <StepProgress current={currentStepIndex} total={steps.length} />
                <div>
                    <div style={{ fontSize: "15px", fontWeight: 700, marginBottom: "4px" }}>
                        {currentStep.title}
                    </div>
                    <div style={{ fontSize: "13px", color: "var(--text-dim)", lineHeight: 1.45 }}>
                        {currentStep.description}
                    </div>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", gap: "8px" }}>
                    <button
                        onClick={() => goToStep(currentStepIndex - 1)}
                        disabled={currentStepIndex === 0}
                        style={{
                            padding: "8px 12px",
                            borderRadius: "6px",
                            border: "1px solid var(--border)",
                            background: "rgba(255,255,255,0.04)",
                            color: "var(--text-main)",
                            cursor: currentStepIndex === 0 ? "not-allowed" : "pointer",
                            opacity: currentStepIndex === 0 ? 0.45 : 1,
                        }}
                    >
                        Previous
                    </button>
                    <div style={{ display: "flex", gap: "8px" }}>
                        <button
                            onClick={onExit}
                            style={{
                                padding: "8px 12px",
                                borderRadius: "6px",
                                border: "1px solid var(--border)",
                                background: "transparent",
                                color: "var(--text-dim)",
                                cursor: "pointer",
                            }}
                        >
                            Exit
                        </button>
                        <button
                            onClick={continueToNext}
                            disabled={!pausedForStep}
                            style={{
                                padding: "8px 12px",
                                borderRadius: "6px",
                                border: "1px solid #3b82f6",
                                background: pausedForStep
                                    ? "rgba(59,130,246,0.25)"
                                    : "rgba(59,130,246,0.1)",
                                color: pausedForStep ? "#dbeafe" : "#93c5fd",
                                cursor: pausedForStep ? "pointer" : "not-allowed",
                            }}
                        >
                            {currentStepIndex < steps.length - 1 ? "Continue" : "Finish"}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default WalkthroughPlayer;
