import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { revealInFileManager } from "../../lib/api";
import { useEditor } from "./EditorContext";

const EditorHeader = () => {
    const navigate = useNavigate();
    const [exportOpen, setExportOpen] = useState(false);
    const [includeChapterCards, setIncludeChapterCards] = useState(false);
    const {
        metadata,
        editorMode,
        setEditorMode,
        hasTerminal,
        activeTab,
        setActiveTab,
        exporting,
        exportFeedback,
        autoStepsFeedback,
        handleExportMarkdown,
        handleExportMp4,
        clearExportFeedback,
        clearAutoStepsFeedback,
        setSharing,
        isProcessing,
    } = useEditor();

    const exportKindLabel = exportFeedback?.kind === "mp4" ? "MP4" : "Markdown";
    const title = useMemo(() => {
        const explicit = metadata?.title?.trim();
        return explicit || "Untitled session";
    }, [metadata?.title]);

    const copyExportPath = async () => {
        if (!exportFeedback?.path) return;
        try {
            await navigator.clipboard.writeText(exportFeedback.path);
        } catch (err) {
            console.error("Failed to copy export path:", err);
        }
    };

    const revealExportPath = async () => {
        if (!exportFeedback?.path) return;
        try {
            await revealInFileManager(exportFeedback.path);
        } catch (err) {
            console.error("Failed to reveal export path:", err);
        }
    };

    return (
        <header
            style={{
                height: "56px",
                display: "flex",
                alignItems: "center",
                padding: "0 18px",
                justifyContent: "space-between",
                borderBottom: "1px solid var(--border-default)",
                background: "var(--bg-surface)",
                zIndex: 10,
            }}
        >
            <div style={{ display: "flex", alignItems: "center", gap: "12px", minWidth: 0 }}>
                <button
                    onClick={() => navigate("/library")}
                    title="Back to Library (⌘L)"
                    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: "13px",
                        fontWeight: 500,
                        transition: "all 150ms var(--ease-out)",
                        display: "flex",
                        alignItems: "center",
                        gap: "6px",
                    }}
                >
                    <svg
                        width="14"
                        height="14"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                    >
                        <path d="M15 18l-6-6 6-6" />
                    </svg>
                    Library
                </button>

                <div style={{ minWidth: 0 }}>
                    <div
                        style={{
                            fontSize: "14px",
                            fontWeight: 750,
                            color: "var(--text-primary)",
                            whiteSpace: "nowrap",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            maxWidth: "52vw",
                        }}
                        title={title}
                    >
                        {title}
                    </div>
                    {isProcessing && (
                        <div
                            style={{
                                marginTop: "2px",
                                display: "flex",
                                alignItems: "center",
                                gap: "8px",
                                fontSize: "12px",
                                color: "var(--status-warning)",
                                fontWeight: 600,
                            }}
                        >
                            <svg
                                width="14"
                                height="14"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                style={{
                                    animation: "spin 1s linear infinite",
                                }}
                            >
                                <path d="M21 12a9 9 0 1 1-6.219-8.56" />
                            </svg>
                            Converting video...
                        </div>
                    )}
                </div>
            </div>

            <div style={{ flex: 1, display: "flex", justifyContent: "center" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                        {(["edit", "preview"] as const).map((mode) => {
                            const active = editorMode === mode;
                            return (
                                <button
                                    key={mode}
                                    onClick={() => setEditorMode(mode)}
                                    style={{
                                        border: "none",
                                        background: "transparent",
                                        padding: "10px 6px",
                                        cursor: "pointer",
                                        color: active ? "var(--text-primary)" : "var(--text-muted)",
                                        fontSize: "13px",
                                        fontWeight: 750,
                                        letterSpacing: "-0.01em",
                                        borderBottom: active
                                            ? "2px solid var(--accent-1)"
                                            : "2px solid transparent",
                                        transition:
                                            "color 140ms var(--ease-out), border-color 140ms var(--ease-out)",
                                    }}
                                >
                                    {mode === "edit" ? "Edit" : "Preview"}
                                </button>
                            );
                        })}
                    </div>

                    {hasTerminal && (
                        <div
                            style={{
                                display: "flex",
                                gap: "2px",
                                background: "var(--bg-elevated)",
                                borderRadius: "var(--radius-md)",
                                padding: "3px",
                                border: "1px solid var(--border-subtle)",
                            }}
                        >
                            <button
                                onClick={() => setActiveTab("video")}
                                style={{
                                    padding: "5px 12px",
                                    background:
                                        activeTab === "video" ? "var(--accent-1)" : "transparent",
                                    border: "none",
                                    color: activeTab === "video" ? "#fff" : "var(--text-tertiary)",
                                    borderRadius: "var(--radius-sm)",
                                    cursor: "pointer",
                                    fontSize: "12px",
                                    fontWeight: 600,
                                    transition: "all 150ms var(--ease-out)",
                                }}
                            >
                                Screen
                            </button>
                            <button
                                onClick={() => setActiveTab("terminal")}
                                style={{
                                    padding: "5px 12px",
                                    background:
                                        activeTab === "terminal"
                                            ? "var(--accent-1)"
                                            : "transparent",
                                    border: "none",
                                    color:
                                        activeTab === "terminal" ? "#fff" : "var(--text-tertiary)",
                                    borderRadius: "var(--radius-sm)",
                                    cursor: "pointer",
                                    fontSize: "12px",
                                    fontWeight: 600,
                                    transition: "all 150ms var(--ease-out)",
                                }}
                            >
                                Terminal
                            </button>
                            <button
                                onClick={() => setActiveTab("both")}
                                style={{
                                    padding: "5px 12px",
                                    background:
                                        activeTab === "both" ? "var(--accent-1)" : "transparent",
                                    border: "none",
                                    color: activeTab === "both" ? "#fff" : "var(--text-tertiary)",
                                    borderRadius: "var(--radius-sm)",
                                    cursor: "pointer",
                                    fontSize: "12px",
                                    fontWeight: 600,
                                    transition: "all 150ms var(--ease-out)",
                                }}
                            >
                                Both
                            </button>
                        </div>
                    )}
                </div>
            </div>

            <div
                style={{ display: "flex", gap: "8px", alignItems: "center", position: "relative" }}
            >
                <div style={{ position: "relative" }}>
                    <button
                        onClick={() => setExportOpen((current) => !current)}
                        disabled={isProcessing}
                        title="Export (⌘E)"
                        style={{
                            padding: "6px 12px",
                            background: "var(--bg-elevated)",
                            border: "1px solid var(--border-default)",
                            color: "var(--text-secondary)",
                            borderRadius: "var(--radius-md)",
                            cursor: isProcessing ? "not-allowed" : "pointer",
                            fontSize: "12px",
                            fontWeight: 500,
                            opacity: isProcessing ? 0.5 : 1,
                            transition: "all 150ms var(--ease-out)",
                        }}
                    >
                        {exporting ? "Exporting..." : "Export ↓"}
                    </button>
                    {exportOpen && !isProcessing && (
                        <div
                            style={{
                                position: "absolute",
                                top: "40px",
                                right: 0,
                                minWidth: "160px",
                                borderRadius: "var(--radius-lg)",
                                border: "1px solid var(--border-default)",
                                background: "var(--bg-elevated)",
                                boxShadow: "var(--shadow-lg)",
                                overflow: "hidden",
                                zIndex: 30,
                            }}
                        >
                            <label
                                style={{
                                    display: "flex",
                                    alignItems: "center",
                                    gap: "8px",
                                    padding: "10px 14px",
                                    borderBottom: "1px solid var(--border-default)",
                                    fontSize: "12px",
                                    color: "var(--text-secondary)",
                                    background: "var(--bg-surface)",
                                    cursor: "pointer",
                                }}
                            >
                                <input
                                    type="checkbox"
                                    checked={includeChapterCards}
                                    onChange={(event) =>
                                        setIncludeChapterCards(event.target.checked)
                                    }
                                />
                                Include chapter cards (MP4)
                            </label>
                            <button
                                onClick={() => {
                                    handleExportMarkdown();
                                    setExportOpen(false);
                                }}
                                disabled={exporting}
                                style={{
                                    width: "100%",
                                    textAlign: "left",
                                    padding: "10px 14px",
                                    border: "none",
                                    background: "transparent",
                                    color: "var(--text-primary)",
                                    cursor: exporting ? "not-allowed" : "pointer",
                                    fontSize: "13px",
                                    transition: "background 100ms",
                                }}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.background = "var(--bg-hover)";
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.background = "transparent";
                                }}
                                title="Export as Markdown (⌘E)"
                            >
                                Markdown
                            </button>
                            <button
                                onClick={() => {
                                    handleExportMp4(includeChapterCards);
                                    setExportOpen(false);
                                }}
                                disabled={exporting}
                                style={{
                                    width: "100%",
                                    textAlign: "left",
                                    padding: "10px 14px",
                                    border: "none",
                                    borderTop: "1px solid var(--border-subtle)",
                                    background: "transparent",
                                    color: "var(--text-primary)",
                                    cursor: exporting ? "not-allowed" : "pointer",
                                    fontSize: "13px",
                                    transition: "background 100ms",
                                }}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.background = "var(--bg-hover)";
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.background = "transparent";
                                }}
                                title="Export MP4"
                            >
                                MP4
                            </button>
                        </div>
                    )}
                </div>

                <button
                    onClick={() => setSharing(true)}
                    disabled={isProcessing}
                    style={{
                        padding: "6px 16px",
                        background: "var(--accent-1)",
                        border: "none",
                        color: "#fff",
                        borderRadius: "var(--radius-md)",
                        cursor: isProcessing ? "not-allowed" : "pointer",
                        fontSize: "12px",
                        fontWeight: 600,
                        opacity: isProcessing ? 0.5 : 1,
                        transition: "all 150ms var(--ease-out)",
                        boxShadow: "0 1px 2px rgba(0,0,0,0.2)",
                    }}
                >
                    Share
                </button>
                <span style={{ color: "var(--text-muted)", fontSize: "11px" }}>⌘?</span>

                {exportFeedback && (
                    <div
                        style={{
                            position: "absolute",
                            top: "42px",
                            right: 0,
                            width: "min(520px, calc(100vw - 48px))",
                            borderRadius: "var(--radius-lg)",
                            border:
                                exportFeedback.status === "success"
                                    ? "1px solid var(--status-success)"
                                    : "1px solid var(--status-error)",
                            background: "var(--bg-elevated)",
                            boxShadow: "var(--shadow-lg)",
                            padding: "10px 12px",
                            zIndex: 25,
                        }}
                    >
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                gap: "10px",
                            }}
                        >
                            <div
                                style={{
                                    fontSize: "12px",
                                    fontWeight: 600,
                                    color:
                                        exportFeedback.status === "success"
                                            ? "var(--status-success)"
                                            : "var(--status-error)",
                                }}
                            >
                                {exportKindLabel} export{" "}
                                {exportFeedback.status === "success" ? "completed" : "failed"}
                            </div>
                            <button
                                onClick={clearExportFeedback}
                                title="Dismiss"
                                style={{
                                    border: "none",
                                    background: "transparent",
                                    color: "var(--text-muted)",
                                    cursor: "pointer",
                                    padding: 0,
                                    fontSize: "14px",
                                    lineHeight: 1,
                                }}
                            >
                                ×
                            </button>
                        </div>
                        <div
                            style={{
                                marginTop: "6px",
                                fontSize: "12px",
                                color: "var(--text-secondary)",
                                wordBreak: "break-all",
                            }}
                        >
                            {exportFeedback.path ?? exportFeedback.message}
                        </div>
                        <div
                            style={{
                                marginTop: "8px",
                                display: "flex",
                                gap: "8px",
                            }}
                        >
                            <button
                                onClick={copyExportPath}
                                disabled={!exportFeedback.path}
                                style={{
                                    padding: "4px 8px",
                                    borderRadius: "var(--radius-sm)",
                                    border: "1px solid var(--border-default)",
                                    background: "var(--bg-surface)",
                                    color: "var(--text-secondary)",
                                    fontSize: "11px",
                                    cursor: exportFeedback.path ? "pointer" : "not-allowed",
                                    opacity: exportFeedback.path ? 1 : 0.5,
                                }}
                            >
                                Copy path
                            </button>
                            <button
                                onClick={() => {
                                    void revealExportPath();
                                }}
                                disabled={!exportFeedback.path}
                                style={{
                                    padding: "4px 8px",
                                    borderRadius: "var(--radius-sm)",
                                    border: "1px solid var(--border-default)",
                                    background: "var(--bg-surface)",
                                    color: "var(--text-secondary)",
                                    fontSize: "11px",
                                    cursor: exportFeedback.path ? "pointer" : "not-allowed",
                                    opacity: exportFeedback.path ? 1 : 0.5,
                                }}
                            >
                                Reveal in Finder
                            </button>
                        </div>
                    </div>
                )}

                {autoStepsFeedback && (
                    <div
                        style={{
                            position: "absolute",
                            top: exportFeedback ? "162px" : "42px",
                            right: 0,
                            width: "min(520px, calc(100vw - 48px))",
                            borderRadius: "var(--radius-lg)",
                            border:
                                autoStepsFeedback.status === "success"
                                    ? "1px solid var(--status-success)"
                                    : "1px solid var(--status-error)",
                            background: "var(--bg-elevated)",
                            boxShadow: "var(--shadow-lg)",
                            padding: "10px 12px",
                            zIndex: 24,
                        }}
                    >
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                gap: "10px",
                            }}
                        >
                            <div
                                style={{
                                    fontSize: "12px",
                                    fontWeight: 600,
                                    color:
                                        autoStepsFeedback.status === "success"
                                            ? "var(--status-success)"
                                            : "var(--status-error)",
                                }}
                            >
                                Auto Steps{" "}
                                {autoStepsFeedback.status === "success" ? "completed" : "failed"}
                            </div>
                            <button
                                onClick={clearAutoStepsFeedback}
                                title="Dismiss"
                                style={{
                                    border: "none",
                                    background: "transparent",
                                    color: "var(--text-muted)",
                                    cursor: "pointer",
                                    padding: 0,
                                    fontSize: "14px",
                                    lineHeight: 1,
                                }}
                            >
                                ×
                            </button>
                        </div>
                        <div
                            style={{
                                marginTop: "6px",
                                fontSize: "12px",
                                color: "var(--text-secondary)",
                                wordBreak: "break-word",
                            }}
                        >
                            {autoStepsFeedback.message}
                        </div>
                    </div>
                )}
            </div>
        </header>
    );
};

export default EditorHeader;
