import {
    TacticContext,
    TacticService,
} from "../../service/MutableTacticService.ts"
import { useEffect, useState } from "react"
import "../../style/export_tactic_popup.css"

import JsonIcon from "../../assets/icon/json.svg?react"
import { loadPlainTactic } from "../../domains/TacticPersistenceDomain.ts"

export interface ExportTacticPopupProps {
    service: TacticService
    onHide: () => void
}

export default function ExportTacticPopup({
    service,
    onHide,
}: ExportTacticPopupProps) {
    const [context, setContext] = useState<TacticContext>()
    const [panicMessage, setPanicMessage] = useState<string>()

    const [exportPercentage, setExportPercentage] = useState(0)

    useEffect(() => {
        async function init() {
            const result = await service.getContext()
            if (typeof result === "string") {
                setPanicMessage("Could not retrieve tactic context")
                return
            }
            setContext(result)
        }

        if (!context) init()
    }, [context, service])

    useEffect(() => {
        function onKeyUp(e: KeyboardEvent) {
            if (e.key === "Escape") onHide()
        }

        window.addEventListener("keyup", onKeyUp)
        return () => window.removeEventListener("keyup", onKeyUp)
    }, [onHide])

    if (panicMessage) return <p>{panicMessage}</p>

    return (
        <div className="popup" onClick={onHide}>
            <div className="popup-card" onClick={(e) => e.stopPropagation()}>
                <div className="popup-header">
                    <p>Exporting {context?.name ?? "Tactic"}</p>
                </div>
                <ProgressBar percentage={exportPercentage} />
                <div className="popup-exports">
                    <div
                        className="export-card"
                        onClick={async () => {
                            await exportInJson(
                                context!,
                                service,
                                setExportPercentage,
                            )
                            setExportPercentage(0)
                        }}>
                        <p className="export-card-title">Exporter en JSON</p>
                        <JsonIcon className="json-logo" />
                    </div>
                </div>
            </div>
        </div>
    )
}

async function exportInJson(
    context: TacticContext,
    service: TacticService,
    onProgress: (p: number) => void,
) {
    const tactic = await loadPlainTactic(context, service, onProgress)

    const e = document.createElement("a")
    e.setAttribute(
        "href",
        "data:application/json;charset=utf-8," +
            encodeURIComponent(JSON.stringify(tactic, null, 2)),
    )
    e.setAttribute("download", `${context.name}.json`)
    e.style.display = "none"

    document.body.appendChild(e)

    e.click()

    document.body.removeChild(e)
}

interface ProgressBarProps {
    percentage: number
}

function ProgressBar({ percentage }: ProgressBarProps) {
    return (
        <div className={"progressbar"} style={{ display: "flex", height: 3 }}>
            <div
                style={{
                    backgroundColor: "#f5992b",
                    width: `${percentage}%`,
                }}></div>
            <div
                style={{
                    backgroundColor: "white",
                    width: `${100 - percentage}%`,
                }}></div>
        </div>
    )
}
