import { useState } from "react";
import { formatTimestamp } from "../hooks/useVideoFrames";
import type { TimelineMarker } from "../lib/api";

interface TimelineProps {
    currentTime: number;
    duration: number;
    currentFrame: number;
    totalFrames: number;
    fps: number;
    onSeekTime: (seconds: number) => void;
    onSeekFrame: (frame: number) => void;
    markers?: TimelineMarker[];
}

// Linear-style markers with accent colors
const MARKER_COLORS: Record<TimelineMarker["type"], string> = {
    command: "var(--status-success)", // green for terminal commands
    click: "var(--accent-1)", // purple for clicks
    file_change: "var(--status-warning)", // amber for file changes
    marker: "var(--accent-2)",
    shortcut: "var(--status-danger)",
    keypress: "var(--text-secondary)",
    mouse_scroll: "var(--accent-3)",
    app_focus: "var(--accent-4)",
    dom_navigation: "var(--accent-5)",
    dom_action: "var(--accent-2)",
};

function Timeline({
    currentTime,
    duration,
    currentFrame,
    totalFrames,
    fps,
    onSeekFrame,
    onSeekTime,
    markers = [],
}: TimelineProps) {
    const [frameInput, setFrameInput] = useState("");
    const [timestampInput, setTimestampInput] = useState("");
    const [hoveredMarker, setHoveredMarker] = useState<string | null>(null);

    const progress = duration > 0 ? (currentTime / duration) * 100 : 0;

    const handleScrub = (event: React.MouseEvent<HTMLDivElement>) => {
        if (!duration) return;
        const rect = event.currentTarget.getBoundingClientRect();
        const percent = (event.clientX - rect.left) / rect.width;
        onSeekTime(Math.max(0, Math.min(duration, percent * duration)));
    };

    const handleFrameJump = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const targetFrame = Number(frameInput);
        if (!Number.isFinite(targetFrame)) return;
        onSeekFrame(targetFrame);
        setFrameInput("");
    };

    const handleTimestampJump = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const targetSeconds = Number(timestampInput);
        if (!Number.isFinite(targetSeconds)) return;
        onSeekTime(targetSeconds);
        setTimestampInput("");
    };

    return (
        <footer
            style={{
                height: "160px",
                padding: "16px 24px",
                display: "flex",
                flexDirection: "column",
                gap: "12px",
                borderTop: "1px solid var(--border-default)",
                background: "var(--bg-surface)",
            }}
        >
            <div
                style={{
                    display: "flex",
                    justifyContent: "space-between",
                    color: "var(--text-tertiary)",
                    fontSize: "11px",
                    fontFamily: "var(--font-mono)",
                    fontWeight: 500,
                }}
            >
                <span>{formatTimestamp(currentTime)}</span>
                <span>{formatTimestamp(duration)}</span>
            </div>

            <div
                onClick={handleScrub}
                style={{
                    position: "relative",
                    height: "44px",
                    background: "var(--bg-elevated)",
                    borderRadius: "var(--radius-lg)",
                    border: "1px solid var(--border-default)",
                    cursor: "pointer",
                    overflow: "visible",
                }}
            >
                <div
                    style={{
                        position: "absolute",
                        left: 0,
                        top: 0,
                        bottom: 0,
                        width: `${progress}%`,
                        background: "linear-gradient(90deg, transparent, var(--accent-4))",
                        borderRight: "2px solid var(--accent-1)",
                    }}
                />

                {/* Timeline markers for terminal commands, clicks, file changes */}
                {markers.map((marker) => {
                    const markerPosition =
                        duration > 0
                            ? Math.max(
                                  0,
                                  Math.min(100, (marker.timestamp_ms / 1000 / duration) * 100)
                              )
                            : 0;
                    const color = MARKER_COLORS[marker.type];
                    const isHovered = hoveredMarker === marker.id;
                    const tooltipPlacement =
                        markerPosition < 14
                            ? "left"
                            : markerPosition > 86
                              ? "right"
                              : "center";

                    return (
                        <div
                            key={marker.id}
                            onMouseEnter={() => setHoveredMarker(marker.id)}
                            onMouseLeave={() => setHoveredMarker(null)}
                            onClick={(e) => {
                                e.stopPropagation();
                                onSeekTime(marker.timestamp_ms / 1000);
                            }}
                            style={{
                                position: "absolute",
                                left: `${markerPosition}%`,
                                top: "50%",
                                transform: "translate(-50%, -50%)",
                                cursor: "pointer",
                                zIndex: isHovered ? 10 : 1,
                            }}
                        >
                            {/* Marker dot */}
                            <div
                                style={{
                                    width: isHovered ? "10px" : "6px",
                                    height: isHovered ? "10px" : "6px",
                                    borderRadius: "50%",
                                    background: color,
                                    boxShadow: isHovered ? `0 0 8px ${color}` : "none",
                                    transition: "all 0.15s var(--ease-out)",
                                }}
                            />
                            {/* Tooltip */}
                            {isHovered && (
                                <div
                                    style={{
                                        position: "absolute",
                                        bottom: "calc(100% + 8px)",
                                        left:
                                            tooltipPlacement === "left"
                                                ? "0"
                                                : tooltipPlacement === "right"
                                                  ? "auto"
                                                  : "50%",
                                        right: tooltipPlacement === "right" ? "0" : "auto",
                                        transform:
                                            tooltipPlacement === "center"
                                                ? "translateX(-50%)"
                                                : "none",
                                        background: "var(--bg-elevated)",
                                        border: "1px solid var(--border-default)",
                                        borderRadius: "var(--radius-md)",
                                        padding: "8px 12px",
                                        width: "max-content",
                                        maxWidth: "300px",
                                        whiteSpace: "normal",
                                        wordBreak: "break-word",
                                        fontSize: "12px",
                                        color: "var(--text-primary)",
                                        boxShadow: "var(--shadow-lg)",
                                        pointerEvents: "none",
                                        zIndex: 30,
                                    }}
                                >
                                    <div
                                        style={{
                                            fontWeight: 500,
                                            marginBottom: "3px",
                                            color: "var(--text-primary)",
                                        }}
                                    >
                                        {marker.type === "command" ? "$ " : ""}
                                        {marker.label}
                                    </div>
                                    <div
                                        style={{
                                            color: "var(--text-secondary)",
                                            fontSize: "11px",
                                            fontFamily: "var(--font-mono)",
                                        }}
                                    >
                                        {formatTimestamp(marker.timestamp_ms / 1000)}
                                    </div>
                                </div>
                            )}
                        </div>
                    );
                })}

                <div
                    style={{
                        position: "absolute",
                        top: "-6px",
                        bottom: "-6px",
                        left: `${progress}%`,
                        width: "2px",
                        background: "var(--accent-1)",
                        boxShadow: "0 0 10px var(--accent-glow)",
                        zIndex: 5,
                    }}
                >
                    <div
                        style={{
                            width: "10px",
                            height: "10px",
                            borderRadius: "50%",
                            background: "var(--accent-1)",
                            border: "2px solid var(--bg-surface)",
                            position: "absolute",
                            top: "-4px",
                            left: "-4px",
                        }}
                    />
                </div>
            </div>

            <div
                style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    gap: "16px",
                }}
            >
                <div style={{ fontSize: "12px", color: "var(--text-tertiary)" }}>
                    Frame{" "}
                    <span
                        style={{
                            color: "var(--text-primary)",
                            fontFamily: "var(--font-mono)",
                            fontWeight: 500,
                            background: "var(--bg-elevated)",
                            padding: "2px 6px",
                            borderRadius: "var(--radius-sm)",
                        }}
                    >
                        {currentFrame}
                    </span>{" "}
                    / {totalFrames}
                    <span style={{ marginLeft: "8px", color: "var(--text-muted)" }}>{fps} fps</span>
                </div>
                <div style={{ display: "flex", gap: "8px" }}>
                    <form onSubmit={handleFrameJump} style={{ display: "flex", gap: "4px" }}>
                        <input
                            aria-label="Jump to frame"
                            placeholder="Frame"
                            value={frameInput}
                            onChange={(event) => setFrameInput(event.target.value)}
                            style={{
                                width: "80px",
                                padding: "6px 10px",
                                borderRadius: "var(--radius-md)",
                                border: "1px solid var(--border-default)",
                                background: "var(--bg-elevated)",
                                color: "var(--text-primary)",
                                fontSize: "12px",
                                fontFamily: "var(--font-mono)",
                            }}
                        />
                        <button
                            type="submit"
                            style={{
                                padding: "6px 12px",
                                background: "var(--bg-elevated)",
                                border: "1px solid var(--border-default)",
                                color: "var(--text-secondary)",
                                borderRadius: "var(--radius-md)",
                                cursor: "pointer",
                                fontSize: "12px",
                                fontWeight: 500,
                                transition: "all 100ms",
                            }}
                        >
                            Go
                        </button>
                    </form>
                    <form onSubmit={handleTimestampJump} style={{ display: "flex", gap: "4px" }}>
                        <input
                            aria-label="Jump to timestamp"
                            placeholder="Time (s)"
                            value={timestampInput}
                            onChange={(event) => setTimestampInput(event.target.value)}
                            style={{
                                width: "80px",
                                padding: "6px 10px",
                                borderRadius: "var(--radius-md)",
                                border: "1px solid var(--border-default)",
                                background: "var(--bg-elevated)",
                                color: "var(--text-primary)",
                                fontSize: "12px",
                                fontFamily: "var(--font-mono)",
                            }}
                        />
                        <button
                            type="submit"
                            style={{
                                padding: "6px 12px",
                                background: "var(--bg-elevated)",
                                border: "1px solid var(--border-default)",
                                color: "var(--text-secondary)",
                                borderRadius: "var(--radius-md)",
                                cursor: "pointer",
                                fontSize: "12px",
                                fontWeight: 500,
                                transition: "all 100ms",
                            }}
                        >
                            Go
                        </button>
                    </form>
                </div>
            </div>
        </footer>
    );
}

export default Timeline;
