import { useState } from "react";
import type { Hotspot, HotspotAction } from "../types/annotations";

interface HotspotEditorProps {
    hotspots: Hotspot[];
    selectedHotspotId: string | null;
    placingMode: boolean;
    currentFrame: number;
    totalFrames: number;
    onSelectHotspot: (id: string) => void;
    onDeleteHotspot: (id: string) => void;
    onTogglePlacingMode: () => void;
    onUpdateHotspot: (id: string, updater: (hotspot: Hotspot) => Hotspot) => void;
}

const buildDefaultAction = (type: HotspotAction["type"]): HotspotAction => {
    if (type === "tooltip") return { type: "tooltip", text: "" };
    if (type === "seek") return { type: "seek", targetFrame: 0 };
    return { type: "url", href: "", newTab: true };
};

// Linear-style numeric stepper
const Stepper = ({
    value,
    onChange,
    min = 0,
    max = 100,
    suffix = "",
}: {
    value: number;
    onChange: (v: number) => void;
    min?: number;
    max?: number;
    suffix?: string;
}) => (
    <div
        style={{
            display: "flex",
            alignItems: "center",
            gap: "2px",
            background: "var(--bg-elevated)",
            borderRadius: "var(--radius-md)",
            padding: "2px",
            border: "1px solid var(--border-subtle)",
        }}
    >
        <button
            onClick={() => onChange(Math.max(min, value - 1))}
            style={{
                width: "24px",
                height: "24px",
                border: "none",
                background: "transparent",
                color: "var(--text-muted)",
                cursor: "pointer",
                borderRadius: "var(--radius-sm)",
                fontSize: "14px",
                lineHeight: 1,
                transition: "color 100ms",
            }}
            onMouseEnter={(e) => {
                e.currentTarget.style.color = "var(--text-secondary)";
            }}
            onMouseLeave={(e) => {
                e.currentTarget.style.color = "var(--text-muted)";
            }}
        >
            −
        </button>
        <span
            style={{
                minWidth: "36px",
                textAlign: "center",
                fontSize: "12px",
                fontFamily: "var(--font-mono)",
                fontVariantNumeric: "tabular-nums",
                color: "var(--text-primary)",
            }}
        >
            {Math.round(value)}
            {suffix}
        </span>
        <button
            onClick={() => onChange(Math.min(max, value + 1))}
            style={{
                width: "24px",
                height: "24px",
                border: "none",
                background: "transparent",
                color: "var(--text-muted)",
                cursor: "pointer",
                borderRadius: "var(--radius-sm)",
                fontSize: "14px",
                lineHeight: 1,
                transition: "color 100ms",
            }}
            onMouseEnter={(e) => {
                e.currentTarget.style.color = "var(--text-secondary)";
            }}
            onMouseLeave={(e) => {
                e.currentTarget.style.color = "var(--text-muted)";
            }}
        >
            +
        </button>
    </div>
);

// Linear-style property row
const PropertyRow = ({ label, children }: { label: string; children: React.ReactNode }) => (
    <div
        style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "8px 0",
        }}
    >
        <span style={{ fontSize: "13px", color: "var(--text-tertiary)" }}>{label}</span>
        {children}
    </div>
);

function HotspotEditor({
    hotspots,
    selectedHotspotId,
    placingMode,
    currentFrame,
    totalFrames,
    onDeleteHotspot,
    onSelectHotspot,
    onTogglePlacingMode,
    onUpdateHotspot,
}: HotspotEditorProps) {
    const selectedHotspot = hotspots.find((h) => h.id === selectedHotspotId) ?? null;
    const [showAdvanced, setShowAdvanced] = useState(false);

    const update = (field: keyof Hotspot, value: number | string) => {
        if (!selectedHotspot) return;
        onUpdateHotspot(selectedHotspot.id, (c) => ({ ...c, [field]: value }));
    };

    // List view - Linear style
    if (!selectedHotspot) {
        return (
            <div style={{ padding: "4px 0" }}>
                {/* Add button */}
                <button
                    onClick={onTogglePlacingMode}
                    style={{
                        width: "100%",
                        padding: "12px 16px",
                        borderRadius: "var(--radius-md)",
                        border: placingMode
                            ? "1px solid var(--accent-1)"
                            : "1px solid var(--border-default)",
                        background: placingMode ? "var(--accent-4)" : "var(--bg-elevated)",
                        color: placingMode ? "var(--accent-1)" : "var(--text-secondary)",
                        cursor: "pointer",
                        fontSize: "13px",
                        fontWeight: 500,
                        textAlign: "left",
                        transition: "all 150ms var(--ease-out)",
                    }}
                >
                    {placingMode ? "Click on video to place..." : "+ Add hotspot"}
                </button>

                {/* Hotspot list */}
                {hotspots.length > 0 && (
                    <div style={{ marginTop: "16px" }}>
                        {hotspots.map((hotspot, idx) => (
                            <button
                                key={hotspot.id}
                                onClick={() => onSelectHotspot(hotspot.id)}
                                style={{
                                    width: "100%",
                                    display: "flex",
                                    alignItems: "center",
                                    gap: "12px",
                                    padding: "10px 12px",
                                    marginBottom: "4px",
                                    borderRadius: "var(--radius-md)",
                                    border: "none",
                                    background: "transparent",
                                    cursor: "pointer",
                                    textAlign: "left",
                                    transition: "background 100ms var(--ease-out)",
                                }}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.background = "var(--bg-hover)";
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.background = "transparent";
                                }}
                            >
                                <div
                                    style={{
                                        width: "24px",
                                        height: "24px",
                                        borderRadius: "var(--radius-sm)",
                                        background: "var(--accent-4)",
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: "center",
                                        fontSize: "11px",
                                        fontFamily: "var(--font-mono)",
                                        fontWeight: 600,
                                        color: "var(--accent-1)",
                                    }}
                                >
                                    {idx + 1}
                                </div>
                                <div style={{ flex: 1, minWidth: 0 }}>
                                    <div
                                        style={{
                                            fontSize: "13px",
                                            fontWeight: 500,
                                            color: "var(--text-primary)",
                                            textTransform: "capitalize",
                                        }}
                                    >
                                        {hotspot.action.type}
                                    </div>
                                    <div
                                        style={{
                                            fontSize: "11px",
                                            fontFamily: "var(--font-mono)",
                                            color: "var(--text-muted)",
                                            marginTop: "2px",
                                        }}
                                    >
                                        {(hotspot.frameStart / 30).toFixed(1)}s –{" "}
                                        {(hotspot.frameEnd / 30).toFixed(1)}s
                                    </div>
                                </div>
                                <svg
                                    width="16"
                                    height="16"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="var(--text-muted)"
                                    strokeWidth="2"
                                >
                                    <path d="M9 18l6-6-6-6" />
                                </svg>
                            </button>
                        ))}
                    </div>
                )}

                {hotspots.length === 0 && !placingMode && (
                    <p
                        style={{
                            padding: "32px 16px",
                            textAlign: "center",
                            fontSize: "13px",
                            color: "var(--text-muted)",
                            lineHeight: 1.5,
                        }}
                    >
                        Add interactive hotspots to highlight important areas.
                    </p>
                )}
            </div>
        );
    }

    // Editor view - Linear style
    return (
        <div style={{ padding: "4px 0" }}>
            {/* Back header */}
            <button
                onClick={() => onSelectHotspot("")}
                style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "6px",
                    padding: "8px 0",
                    marginBottom: "8px",
                    border: "none",
                    background: "transparent",
                    color: "var(--text-tertiary)",
                    cursor: "pointer",
                    fontSize: "13px",
                    transition: "color 100ms",
                }}
                onMouseEnter={(e) => {
                    e.currentTarget.style.color = "var(--text-primary)";
                }}
                onMouseLeave={(e) => {
                    e.currentTarget.style.color = "var(--text-tertiary)";
                }}
            >
                <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                >
                    <path d="M15 18l-6-6 6-6" />
                </svg>
                Back
            </button>

            {/* Action type */}
            <div
                style={{
                    display: "flex",
                    gap: "4px",
                    padding: "4px",
                    background: "var(--bg-elevated)",
                    borderRadius: "var(--radius-md)",
                    marginBottom: "20px",
                    border: "1px solid var(--border-subtle)",
                }}
            >
                {(["tooltip", "url", "seek"] as const).map((type) => (
                    <button
                        key={type}
                        onClick={() =>
                            onUpdateHotspot(selectedHotspot.id, (c) => ({
                                ...c,
                                action: buildDefaultAction(type),
                            }))
                        }
                        style={{
                            flex: 1,
                            padding: "8px 12px",
                            borderRadius: "var(--radius-sm)",
                            border: "none",
                            background:
                                selectedHotspot.action.type === type
                                    ? "var(--accent-1)"
                                    : "transparent",
                            color:
                                selectedHotspot.action.type === type
                                    ? "#fff"
                                    : "var(--text-tertiary)",
                            fontSize: "12px",
                            fontWeight: 500,
                            cursor: "pointer",
                            textTransform: "capitalize",
                            transition: "all 100ms var(--ease-out)",
                        }}
                    >
                        {type}
                    </button>
                ))}
            </div>

            {/* Style */}
            <div
                style={{
                    display: "flex",
                    gap: "4px",
                    padding: "4px",
                    background: "var(--bg-elevated)",
                    borderRadius: "var(--radius-md)",
                    marginBottom: "20px",
                    border: "1px solid var(--border-subtle)",
                }}
            >
                {(
                    [
                        { style: "pulse" as const, label: "Hotspot" },
                        { style: "circle" as const, label: "Pin" },
                        { style: "rectangle" as const, label: "Area" },
                    ] as const
                ).map(({ style, label }) => (
                    <button
                        key={style}
                        onClick={() =>
                            onUpdateHotspot(selectedHotspot.id, (c) => ({ ...c, style }))
                        }
                        style={{
                            flex: 1,
                            padding: "8px 12px",
                            borderRadius: "var(--radius-sm)",
                            border: "none",
                            background:
                                selectedHotspot.style === style ? "var(--accent-1)" : "transparent",
                            color:
                                selectedHotspot.style === style ? "#fff" : "var(--text-tertiary)",
                            fontSize: "12px",
                            fontWeight: 500,
                            cursor: "pointer",
                            transition: "all 100ms var(--ease-out)",
                        }}
                        title={label}
                    >
                        {label}
                    </button>
                ))}
            </div>

            {/* Action content - Linear style */}
            {selectedHotspot.action.type === "tooltip" && (
                <div style={{ marginBottom: "20px" }}>
                    <textarea
                        value={selectedHotspot.action.text}
                        onChange={(e) =>
                            onUpdateHotspot(selectedHotspot.id, (c) => ({
                                ...c,
                                action: { type: "tooltip", text: e.target.value },
                            }))
                        }
                        placeholder="Enter message..."
                        style={{
                            width: "100%",
                            padding: "12px",
                            borderRadius: "var(--radius-md)",
                            border: "1px solid var(--border-default)",
                            background: "var(--bg-elevated)",
                            color: "var(--text-primary)",
                            fontSize: "13px",
                            fontFamily: "inherit",
                            minHeight: "80px",
                            resize: "vertical",
                            outline: "none",
                            transition: "border-color 150ms",
                        }}
                        onFocus={(e) => {
                            e.currentTarget.style.borderColor = "var(--accent-1)";
                        }}
                        onBlur={(e) => {
                            e.currentTarget.style.borderColor = "var(--border-default)";
                        }}
                    />
                </div>
            )}

            {selectedHotspot.action.type === "url" && (
                <div style={{ marginBottom: "20px" }}>
                    <input
                        value={selectedHotspot.action.href}
                        onChange={(e) =>
                            onUpdateHotspot(selectedHotspot.id, (c) => ({
                                ...c,
                                action: { ...c.action, href: e.target.value },
                            }))
                        }
                        placeholder="https://..."
                        style={{
                            width: "100%",
                            padding: "10px 12px",
                            borderRadius: "var(--radius-md)",
                            border: "1px solid var(--border-default)",
                            background: "var(--bg-elevated)",
                            color: "var(--text-primary)",
                            fontSize: "13px",
                            fontFamily: "var(--font-mono)",
                            outline: "none",
                            marginBottom: "10px",
                            transition: "border-color 150ms",
                        }}
                        onFocus={(e) => {
                            e.currentTarget.style.borderColor = "var(--accent-1)";
                        }}
                        onBlur={(e) => {
                            e.currentTarget.style.borderColor = "var(--border-default)";
                        }}
                    />
                    <label
                        style={{
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                            fontSize: "12px",
                            color: "var(--text-tertiary)",
                            cursor: "pointer",
                        }}
                    >
                        <input
                            type="checkbox"
                            checked={selectedHotspot.action.newTab}
                            onChange={(e) =>
                                onUpdateHotspot(selectedHotspot.id, (c) => ({
                                    ...c,
                                    action: { ...c.action, newTab: e.target.checked },
                                }))
                            }
                            style={{ accentColor: "var(--accent-1)" }}
                        />
                        Open in new tab
                    </label>
                </div>
            )}

            {selectedHotspot.action.type === "seek" && (
                <div style={{ marginBottom: "20px" }}>
                    <PropertyRow label="Jump to frame">
                        <Stepper
                            value={selectedHotspot.action.targetFrame}
                            onChange={(v) =>
                                onUpdateHotspot(selectedHotspot.id, (c) => ({
                                    ...c,
                                    action: { type: "seek", targetFrame: v },
                                }))
                            }
                            max={totalFrames}
                        />
                    </PropertyRow>
                </div>
            )}

            {/* Timing - Linear style */}
            <div
                style={{
                    padding: "12px 0",
                    borderTop: "1px solid var(--border-subtle)",
                }}
            >
                <PropertyRow label="Visible from">
                    <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                        <Stepper
                            value={selectedHotspot.frameStart}
                            onChange={(v) => update("frameStart", v)}
                            max={totalFrames}
                        />
                        <button
                            onClick={() => {
                                update("frameStart", currentFrame);
                                update("frameEnd", Math.min(totalFrames, currentFrame + 90));
                            }}
                            title="Set to current frame"
                            style={{
                                width: "28px",
                                height: "28px",
                                borderRadius: "var(--radius-md)",
                                border: "1px solid var(--border-default)",
                                background: "var(--bg-elevated)",
                                color: "var(--text-muted)",
                                cursor: "pointer",
                                fontSize: "12px",
                                transition: "all 150ms",
                            }}
                        >
                            ⏱
                        </button>
                    </div>
                </PropertyRow>
                <PropertyRow label="Until">
                    <Stepper
                        value={selectedHotspot.frameEnd}
                        onChange={(v) => update("frameEnd", v)}
                        max={totalFrames}
                    />
                </PropertyRow>
            </div>

            {/* Advanced toggle - Linear style */}
            <button
                onClick={() => setShowAdvanced(!showAdvanced)}
                style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    width: "100%",
                    padding: "12px 0",
                    border: "none",
                    borderTop: "1px solid var(--border-subtle)",
                    background: "transparent",
                    color: "var(--text-tertiary)",
                    fontSize: "12px",
                    cursor: "pointer",
                    transition: "color 100ms",
                }}
                onMouseEnter={(e) => {
                    e.currentTarget.style.color = "var(--text-primary)";
                }}
                onMouseLeave={(e) => {
                    e.currentTarget.style.color = "var(--text-tertiary)";
                }}
            >
                Position & Size
                <svg
                    width="12"
                    height="12"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    style={{
                        transform: showAdvanced ? "rotate(180deg)" : "rotate(0deg)",
                        transition: "transform 150ms var(--ease-out)",
                    }}
                >
                    <path d="M6 9l6 6 6-6" />
                </svg>
            </button>

            {showAdvanced && (
                <div style={{ paddingBottom: "12px" }}>
                    <PropertyRow label="X">
                        <Stepper
                            value={selectedHotspot.x}
                            onChange={(v) => update("x", v)}
                            suffix="%"
                        />
                    </PropertyRow>
                    <PropertyRow label="Y">
                        <Stepper
                            value={selectedHotspot.y}
                            onChange={(v) => update("y", v)}
                            suffix="%"
                        />
                    </PropertyRow>
                    <PropertyRow label="Width">
                        <Stepper
                            value={selectedHotspot.width}
                            onChange={(v) => update("width", v)}
                            suffix="%"
                        />
                    </PropertyRow>
                    <PropertyRow label="Height">
                        <Stepper
                            value={selectedHotspot.height}
                            onChange={(v) => update("height", v)}
                            suffix="%"
                        />
                    </PropertyRow>
                </div>
            )}

            {/* Delete - Linear style */}
            <div style={{ paddingTop: "16px", borderTop: "1px solid var(--border-subtle)" }}>
                <button
                    onClick={() => onDeleteHotspot(selectedHotspot.id)}
                    style={{
                        width: "100%",
                        padding: "10px",
                        borderRadius: "var(--radius-md)",
                        border: "1px solid transparent",
                        background: "transparent",
                        color: "var(--text-muted)",
                        fontSize: "12px",
                        cursor: "pointer",
                        transition: "all 100ms var(--ease-out)",
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.color = "var(--status-error)";
                        e.currentTarget.style.background = "var(--status-error-muted)";
                        e.currentTarget.style.borderColor = "var(--status-error)";
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.color = "var(--text-muted)";
                        e.currentTarget.style.background = "transparent";
                        e.currentTarget.style.borderColor = "transparent";
                    }}
                >
                    Delete hotspot
                </button>
            </div>
        </div>
    );
}

export default HotspotEditor;
