import React, { useState } from "react";
import { useEditor } from "./EditorContext";
import VideoPlayer from "../../components/VideoPlayer";
import HotspotOverlay from "../../components/HotspotOverlay";
import ClickRippleOverlay from "../../components/ClickRippleOverlay";
import WalkthroughPlayer from "../../components/WalkthroughPlayer";
import TerminalPlayer from "../../components/TerminalPlayer";
import Timeline from "../../components/Timeline";

interface EditorMainProps {
    videoRef: React.RefObject<HTMLVideoElement>;
}

const EditorMain: React.FC<EditorMainProps> = ({ videoRef }) => {
    const {
        editorMode,
        activeTab,
        videoUrl,
        playing,
        setPlaying,
        currentFrame,
        totalFrames,
        togglePlay,
        placingHotspot,
        setPlacingHotspot,
        placingHotspotStyle,
        setPlacingHotspotStyle,
        handleStageClick,
        hotspots,
        editingHotspots,
        setEditingHotspots,
        selectedHotspotId,
        setSelectedHotspotId,
        seekToFrame,
        steps,
        handleSelectStep,
        splitSelectedStepAtCurrentFrame,
        walkthroughMode,
        walkthroughSteps,
        seekToTimestamp,
        setWalkthroughMode,
        terminalUrl,
        currentTime,
        duration,
        fps,
        markers,
        isProcessing,
        clicks,
        showClickRipples,
        handleUpdateHotspot,
        handleDeleteHotspot,
        handleVideoLoadError,
    } = useEditor();

    const editEnabled = editorMode === "edit";
    const editableHotspots = editEnabled && editingHotspots;
    const canPlaceHotspot = editEnabled && placingHotspot;
    const allowHotspotNavigation = editorMode === "preview";

    const [toolTooltip, setToolTooltip] = useState<{
        key: "hotspot" | "callout" | "chapter";
        label: string;
        rect: { left: number; top: number; width: number; height: number };
    } | null>(null);

    const startPlacing = (style: "pulse" | "callout") => {
        setWalkthroughMode(false);
        setEditingHotspots(true);
        setSelectedHotspotId(null);
        setPlacingHotspotStyle(style);

        // Toggle off if user clicks the already-active tool.
        if (placingHotspot && placingHotspotStyle === style) {
            setPlacingHotspot(false);
            return;
        }

        setPlacingHotspot(true);
    };

    const toolActive = (tool: "hotspot" | "callout") => {
        if (!editEnabled) return false;
        if (!placingHotspot) return false;
        if (tool === "hotspot") return placingHotspotStyle === "pulse";
        return placingHotspotStyle === "callout";
    };

    const showCanvasTools =
        editEnabled && !isProcessing && (activeTab === "video" || activeTab === "both");

    return (
        <div
            style={{
                flex: 1,
                display: "flex",
                flexDirection: "column",
                position: "relative",
                minHeight: 0,
                overflow: "hidden",
            }}
        >
            <div
                style={{
                    flex: 1,
                    display: "flex",
                    flexDirection: "column",
                    minHeight: 0,
                    overflow: "hidden",
                    position: "relative",
                }}
            >
                {toolTooltip && (
                    <div
                        style={{
                            position: "fixed",
                            left: toolTooltip.rect.left + toolTooltip.rect.width / 2,
                            top: toolTooltip.rect.top + toolTooltip.rect.height + 10,
                            transform: "translateX(-50%)",
                            padding: "10px 12px",
                            borderRadius: "12px",
                            background: "rgba(10, 12, 18, 0.92)",
                            color: "#fff",
                            fontSize: "12px",
                            fontWeight: 800,
                            boxShadow: "0 18px 50px rgba(0,0,0,0.55)",
                            whiteSpace: "nowrap",
                            pointerEvents: "none",
                            zIndex: 10000,
                        }}
                    >
                        {toolTooltip.label}
                    </div>
                )}

                {showCanvasTools && (
                    <div
                        style={{
                            flexShrink: 0,
                            padding: "14px 0 12px",
                            borderBottom: "1px solid var(--border-default)",
                            background: "color-mix(in srgb, var(--bg-surface) 92%, transparent)",
                            display: "flex",
                            flexDirection: "column",
                            alignItems: "center",
                            gap: "10px",
                        }}
                    >
                        <div style={{ display: "flex", justifyContent: "center", width: "100%" }}>
                            <div
                                style={{
                                    height: "44px",
                                    padding: "6px",
                                    borderRadius: "16px",
                                    border: "1px solid var(--border-default)",
                                    background:
                                        "color-mix(in srgb, var(--bg-surface) 92%, transparent)",
                                    boxShadow: "0 14px 40px rgba(0,0,0,0.45)",
                                    display: "flex",
                                    gap: "6px",
                                    alignItems: "center",
                                }}
                            >
                                {(
                                    [
                                        {
                                            key: "hotspot" as const,
                                            label: "Hotspot",
                                            active: toolActive("hotspot"),
                                            onClick: () => startPlacing("pulse"),
                                            icon: (
                                                <svg
                                                    width="22"
                                                    height="22"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    strokeWidth="2"
                                                >
                                                    <circle cx="12" cy="12" r="8" />
                                                </svg>
                                            ),
                                        },
                                        {
                                            key: "callout" as const,
                                            label: "Callout",
                                            active: toolActive("callout"),
                                            onClick: () => startPlacing("callout"),
                                            icon: (
                                                <svg
                                                    width="22"
                                                    height="22"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    strokeWidth="2"
                                                    strokeLinejoin="round"
                                                >
                                                    <path d="M5 6h14v9H9l-4 3V6z" />
                                                </svg>
                                            ),
                                        },
                                        {
                                            key: "chapter" as const,
                                            label: "Chapter",
                                            active: false,
                                            onClick: () => splitSelectedStepAtCurrentFrame(),
                                            icon: (
                                                <svg
                                                    width="22"
                                                    height="22"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    strokeWidth="2"
                                                    strokeLinejoin="round"
                                                >
                                                    <path d="M5 7h14" />
                                                    <path d="M7 11h10" />
                                                    <path d="M9 15h6" />
                                                </svg>
                                            ),
                                        },
                                    ] as const
                                ).map((tool) => (
                                    <button
                                        key={tool.key}
                                        type="button"
                                        onClick={tool.onClick}
                                        onMouseEnter={(e) => {
                                            const rect = e.currentTarget.getBoundingClientRect();
                                            setToolTooltip({
                                                key: tool.key,
                                                label: tool.label,
                                                rect: {
                                                    left: rect.left,
                                                    top: rect.top,
                                                    width: rect.width,
                                                    height: rect.height,
                                                },
                                            });
                                        }}
                                        onMouseLeave={() => setToolTooltip(null)}
                                        style={{
                                            width: "40px",
                                            height: "40px",
                                            borderRadius: "14px",
                                            border: "none",
                                            background: tool.active
                                                ? "color-mix(in srgb, var(--text-primary) 8%, transparent)"
                                                : "transparent",
                                            color: "var(--text-primary)",
                                            cursor: "pointer",
                                            display: "grid",
                                            placeItems: "center",
                                            transition: "background 140ms var(--ease-out)",
                                        }}
                                        aria-label={tool.label}
                                    >
                                        {tool.icon}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {canPlaceHotspot && (
                            <div
                                style={{
                                    fontSize: "12px",
                                    fontWeight: 500,
                                    color: "var(--accent-1)",
                                    background: "var(--bg-elevated)",
                                    border: "1px solid var(--accent-1)",
                                    borderRadius: "var(--radius-md)",
                                    padding: "8px 14px",
                                    boxShadow: "var(--shadow-glow)",
                                }}
                            >
                                Click on the video to place hotspot
                            </div>
                        )}
                    </div>
                )}

                <div
                    style={{
                        flex: 1,
                        minHeight: 0,
                        backgroundColor: "#000",
                        display: "flex",
                        justifyContent: "center",
                        alignItems: activeTab === "both" ? "stretch" : "center",
                        padding: "40px",
                        overflow: "hidden",
                        gap: "20px",
                        position: "relative",
                    }}
                >
                    {(activeTab === "video" || activeTab === "both") && (
                        <div
                            style={{
                                flex: activeTab === "both" ? 1 : undefined,
                                width: activeTab === "both" ? undefined : "100%",
                                maxWidth: activeTab === "both" ? "700px" : "1100px",
                                position: "relative",
                                display: "flex",
                                flexDirection: "column",
                                alignItems: "center",
                                height: "100%",
                                minHeight: 0,
                            }}
                        >
                            <div
                                style={{
                                    flex: 1,
                                    minHeight: 0,
                                    width: "100%",
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "center",
                                }}
                            >
                                {isProcessing ? (
                                    <div
                                        style={{
                                            width: "100%",
                                            aspectRatio: "16/9",
                                            background: "var(--bg-elevated)",
                                            borderRadius: "var(--radius-xl)",
                                            display: "flex",
                                            flexDirection: "column",
                                            alignItems: "center",
                                            justifyContent: "center",
                                            color: "var(--text-tertiary)",
                                            border: "1px solid var(--border-default)",
                                        }}
                                    >
                                        <div
                                            style={{
                                                width: "28px",
                                                height: "28px",
                                                border: "2px solid var(--border-strong)",
                                                borderTopColor: "var(--accent-1)",
                                                borderRadius: "50%",
                                                animation: "spin 1s linear infinite",
                                                marginBottom: "16px",
                                            }}
                                        />
                                        <div
                                            style={{
                                                fontWeight: 500,
                                                color: "var(--text-primary)",
                                                fontSize: "14px",
                                            }}
                                        >
                                            Processing recording...
                                        </div>
                                        <div
                                            style={{
                                                fontSize: "12px",
                                                marginTop: "8px",
                                                color: "var(--text-muted)",
                                            }}
                                        >
                                            This may take a moment
                                        </div>
                                        <style>{`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`}</style>
                                    </div>
                                ) : (
                                    <VideoPlayer
                                        src={videoUrl}
                                        videoRef={videoRef}
                                        playing={playing}
                                        currentFrame={currentFrame}
                                        totalFrames={totalFrames}
                                        onTogglePlay={togglePlay}
                                        onPlay={() => setPlaying(true)}
                                        onPause={() => setPlaying(false)}
                                        onEnded={() => setPlaying(false)}
                                        onLoadError={handleVideoLoadError}
                                        onStageClick={
                                            canPlaceHotspot ? handleStageClick : undefined
                                        }
                                    >
                                        <HotspotOverlay
                                            hotspots={hotspots}
                                            currentFrame={currentFrame}
                                            editable={editableHotspots}
                                            selectedHotspotId={
                                                editableHotspots ? selectedHotspotId : null
                                            }
                                            onSelectHotspot={
                                                editableHotspots ? setSelectedHotspotId : undefined
                                            }
                                            onUpdateHotspot={
                                                editableHotspots ? handleUpdateHotspot : undefined
                                            }
                                            onDeleteHotspot={
                                                editableHotspots ? handleDeleteHotspot : undefined
                                            }
                                            onSeekToFrame={seekToFrame}
                                            onNavigateToStep={
                                                allowHotspotNavigation
                                                    ? (destination, hotspotId) => {
                                                          if (destination.type === "step") {
                                                              handleSelectStep(destination.stepId);
                                                              return;
                                                          }
                                                          if (destination.type === "this_step") {
                                                              return;
                                                          }

                                                          const currentStepIndex = steps.findIndex(
                                                              (step) =>
                                                                  (step.hotspot_ids ?? []).includes(
                                                                      hotspotId
                                                                  )
                                                          );
                                                          if (currentStepIndex < 0) return;
                                                          const next = steps[currentStepIndex + 1];
                                                          if (!next) return;
                                                          handleSelectStep(next.id);
                                                      }
                                                    : undefined
                                            }
                                        />
                                        <ClickRippleOverlay
                                            clicks={clicks}
                                            currentTimeMs={currentTime * 1000}
                                            enabled={showClickRipples && !editableHotspots}
                                        />
                                        {walkthroughMode && (
                                            <WalkthroughPlayer
                                                steps={walkthroughSteps}
                                                videoRef={videoRef}
                                                onSeekMs={(timestampMs) =>
                                                    seekToTimestamp(timestampMs / 1000)
                                                }
                                                onExit={() => {
                                                    setWalkthroughMode(false);
                                                    setPlaying(false);
                                                    videoRef.current?.pause();
                                                }}
                                            />
                                        )}
                                    </VideoPlayer>
                                )}
                            </div>
                        </div>
                    )}

                    {(activeTab === "terminal" || activeTab === "both") && terminalUrl && (
                        <div
                            style={{
                                flex: activeTab === "both" ? 1 : undefined,
                                width: activeTab === "both" ? undefined : "100%",
                                maxWidth: activeTab === "both" ? "600px" : "900px",
                                height: activeTab === "both" ? "100%" : "500px",
                                borderRadius: "12px",
                                overflow: "hidden",
                                boxShadow: "0 20px 50px rgba(0,0,0,0.5)",
                            }}
                        >
                            <TerminalPlayer
                                castUrl={terminalUrl}
                                showControls={activeTab === "terminal"}
                                playing={activeTab === "both" ? playing : undefined}
                                seekTo={activeTab === "both" ? currentTime : undefined}
                            />
                        </div>
                    )}
                </div>
            </div>

            <Timeline
                currentTime={currentTime}
                duration={duration}
                currentFrame={currentFrame}
                totalFrames={totalFrames}
                fps={fps}
                onSeekTime={seekToTimestamp}
                onSeekFrame={seekToFrame}
                markers={markers}
            />
        </div>
    );
};

export default EditorMain;
