import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useState } from "react";
import { useSelectedVetraCloudEnvironmentDocument, actions, } from "@powerhousedao/vetra-cloud-package/document-models/vetra-cloud-environment/v1";
import { StatusBadge } from "./components/StatusBadge.js";
import { ServicesList } from "./components/ServicesList.js";
import { PackagesList } from "./components/PackagesList.js";
import { SectionCard } from "./components/SectionCard.js";
import { DnsRecordsTable } from "./components/DnsRecordsTable.js";
import { vetraThemeCSS } from "./components/vetra-theme.js";
import { DocumentToolbar } from "@powerhousedao/design-system/connect/components/document-toolbar/document-toolbar";
const READONLY_STATUSES = new Set([
    "TERMINATING",
    "DESTROYED",
    "ARCHIVED",
]);
export default function Editor() {
    const [document, dispatch] = useSelectedVetraCloudEnvironmentDocument();
    const state = document.state.global;
    const isDraft = state.status === "DRAFT";
    const isReadonly = READONLY_STATUSES.has(state.status);
    const [initSubdomain, setInitSubdomain] = useState("");
    const [initBaseDomain, setInitBaseDomain] = useState("");
    const [initRegistry, setInitRegistry] = useState("");
    const handleInitialize = useCallback(() => {
        if (!initSubdomain.trim() || !initBaseDomain.trim())
            return;
        dispatch(actions.initialize({
            genericSubdomain: initSubdomain.trim(),
            genericBaseDomain: initBaseDomain.trim(),
            defaultPackageRegistry: initRegistry.trim() || undefined,
        }));
    }, [dispatch, initSubdomain, initBaseDomain, initRegistry]);
    const handleSetLabel = useCallback((value) => {
        if (value.trim() && value.trim() !== state.label) {
            dispatch(actions.setLabel({ label: value.trim() }));
        }
    }, [dispatch, state.label]);
    const handleSetSubdomain = useCallback((value) => {
        if (value.trim() && value.trim() !== state.genericSubdomain) {
            dispatch(actions.setGenericSubdomain({ genericSubdomain: value.trim() }));
        }
    }, [dispatch, state.genericSubdomain]);
    const handleToggleCustomDomain = useCallback((enabled) => {
        dispatch(actions.setCustomDomain({
            enabled,
            domain: enabled ? state.customDomain?.domain : undefined,
        }));
    }, [dispatch, state.customDomain?.domain]);
    const handleSetCustomDomainValue = useCallback((domain) => {
        dispatch(actions.setCustomDomain({
            enabled: state.customDomain?.enabled ?? false,
            domain: domain.trim() || undefined,
        }));
    }, [dispatch, state.customDomain?.enabled]);
    const handleApproveChanges = useCallback(() => {
        dispatch(actions.approveChanges({}));
    }, [dispatch]);
    const handleTerminate = useCallback(() => {
        dispatch(actions.terminateEnvironment({}));
    }, [dispatch]);
    const genericDomain = [state.genericSubdomain, state.genericBaseDomain]
        .filter(Boolean)
        .join(".");
    // ========== DRAFT VIEW ==========
    if (isDraft) {
        return (_jsxs("div", { className: "vetra-editor", style: containerStyle, children: [_jsx("style", { children: vetraThemeCSS }), _jsx(DocumentToolbar, {}), _jsxs("div", { style: headerStyle, children: [_jsxs("div", { children: [_jsx("h1", { style: { fontSize: 28, fontWeight: 700, lineHeight: 1.2, color: "var(--v-fg)" }, children: "New Environment" }), _jsx("p", { style: { fontSize: 14, color: "var(--v-muted-fg)", marginTop: 4 }, children: "Initialize your Vetra Cloud environment to get started." })] }), _jsx(StatusBadge, { status: state.status })] }), _jsx(SectionCard, { title: "Initialize Environment", children: _jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 16 }, children: [_jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Subdomain *" }), _jsx("input", { type: "text", value: initSubdomain, onChange: (e) => setInitSubdomain(e.target.value), placeholder: "my-environment", style: inputStyle }), _jsx("span", { style: hintStyle, children: "Will be used as the generic subdomain for your environment" })] }), _jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Base Domain *" }), _jsx("input", { type: "text", value: initBaseDomain, onChange: (e) => setInitBaseDomain(e.target.value), placeholder: "vetra.io", style: inputStyle }), _jsx("span", { style: hintStyle, children: "The base domain for all service URLs (e.g. vetra.io)" })] }), _jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Default Package Registry" }), _jsx("input", { type: "text", value: initRegistry, onChange: (e) => setInitRegistry(e.target.value), placeholder: "https://registry.example.com", style: inputStyle }), _jsx("span", { style: hintStyle, children: "Optional. Default registry for packages added to this environment." })] }), _jsx("button", { onClick: handleInitialize, disabled: !initSubdomain.trim() || !initBaseDomain.trim(), style: {
                                    ...btnPrimaryStyle,
                                    alignSelf: "flex-start",
                                    opacity: initSubdomain.trim() && initBaseDomain.trim() ? 1 : 0.5,
                                }, children: "Initialize Environment" })] }) })] }));
    }
    // ========== MAIN VIEW ==========
    return (_jsxs("div", { className: "vetra-editor", style: containerStyle, children: [_jsx("style", { children: vetraThemeCSS }), _jsx(DocumentToolbar, {}), _jsx(SectionCard, { title: "Environment", children: _jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 16 }, children: [_jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Name" }), _jsx("input", { type: "text", defaultValue: state.label ?? "", placeholder: "Environment name", onBlur: (e) => handleSetLabel(e.target.value), onKeyDown: (e) => {
                                        if (e.key === "Enter")
                                            e.currentTarget.blur();
                                    }, disabled: isReadonly, style: inputStyle })] }), _jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Status" }), _jsx("div", { style: { paddingTop: 2 }, children: _jsx(StatusBadge, { status: state.status }) })] }), _jsxs("div", { style: { display: "flex", gap: 10 }, children: [state.status === "CHANGES_PENDING" && (_jsx("button", { onClick: handleApproveChanges, style: btnPrimaryStyle, children: "Approve Changes" })), !READONLY_STATUSES.has(state.status) &&
                                    state.status !== "DEPLOYING" && (_jsx("button", { onClick: handleTerminate, style: btnDestructiveStyle, children: "Terminate" }))] })] }) }), _jsx(SectionCard, { title: "Domain Configuration", children: _jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 16 }, children: [_jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Generic Domain" }), _jsx("div", { style: {
                                        ...inputStyle,
                                        background: "var(--v-accent)",
                                        opacity: 0.85,
                                        fontFamily: "monospace",
                                    }, children: genericDomain || "—" }), _jsx("span", { style: hintStyle, children: "Subdomain is auto-generated. Service URLs are derived from this domain." })] }), _jsxs("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }, children: [_jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Subdomain" }), _jsx("input", { type: "text", defaultValue: state.genericSubdomain ?? "", placeholder: "subdomain", onBlur: (e) => handleSetSubdomain(e.target.value), onKeyDown: (e) => {
                                                if (e.key === "Enter")
                                                    e.currentTarget.blur();
                                            }, disabled: isReadonly, style: inputStyle })] }), _jsxs("div", { style: fieldStyle, children: [_jsx("label", { style: labelStyle, children: "Base Domain" }), _jsx("input", { type: "text", value: state.genericBaseDomain ?? "", readOnly: true, style: { ...inputStyle, opacity: 0.6 } })] })] }), _jsxs("div", { style: {
                                borderTop: "1px solid var(--v-border)",
                                paddingTop: 16,
                                display: "flex",
                                flexDirection: "column",
                                gap: 12,
                            }, children: [_jsxs("label", { style: {
                                        display: "flex",
                                        alignItems: "center",
                                        gap: 10,
                                        cursor: isReadonly ? "default" : "pointer",
                                    }, children: [_jsx("input", { type: "checkbox", checked: state.customDomain?.enabled ?? false, onChange: (e) => handleToggleCustomDomain(e.target.checked), disabled: isReadonly, style: { width: 18, height: 18, accentColor: "var(--v-primary)" } }), _jsx("span", { style: { fontSize: 14, fontWeight: 600, color: "var(--v-fg)" }, children: "Custom Domain" })] }), state.customDomain?.enabled && (_jsx("div", { style: fieldStyle, children: _jsx("input", { type: "text", defaultValue: state.customDomain?.domain ?? "", placeholder: "project.acme.net", onBlur: (e) => handleSetCustomDomainValue(e.target.value), onKeyDown: (e) => {
                                            if (e.key === "Enter")
                                                e.currentTarget.blur();
                                        }, disabled: isReadonly, style: inputStyle }) })), state.customDomain?.dnsRecords &&
                                    state.customDomain.dnsRecords.length > 0 && (_jsx(DnsRecordsTable, { records: state.customDomain.dnsRecords }))] })] }) }), _jsx(SectionCard, { title: "Reactor Modules", children: _jsx(PackagesList, { packages: state.packages, defaultRegistry: state.defaultPackageRegistry, dispatch: dispatch, disabled: isReadonly }) }), _jsx(SectionCard, { title: "Services", children: _jsx(ServicesList, { services: state.services, genericDomain: genericDomain, dispatch: dispatch, disabled: isReadonly }) }), _jsxs("div", { style: {
                    display: "grid",
                    gridTemplateColumns: "1fr 1fr 1fr",
                    gap: 16,
                    padding: "16px 0",
                    borderTop: "1px solid var(--v-border)",
                    fontSize: 12,
                    color: "var(--v-muted-fg)",
                }, children: [_jsxs("div", { children: [_jsx("span", { style: metaLabelStyle, children: "ID" }), _jsx("br", {}), _jsx("span", { style: { fontFamily: "monospace", fontSize: 11 }, children: document.header.id })] }), _jsxs("div", { children: [_jsx("span", { style: metaLabelStyle, children: "Created" }), _jsx("br", {}), new Date(document.header.createdAtUtcIso).toLocaleString()] }), _jsxs("div", { children: [_jsx("span", { style: metaLabelStyle, children: "Modified" }), _jsx("br", {}), new Date(document.header.lastModifiedAtUtcIso).toLocaleString()] })] })] }));
}
// ========== SHARED STYLES ==========
const containerStyle = {
    maxWidth: 960,
    margin: "0 auto",
    padding: 32,
    display: "flex",
    flexDirection: "column",
    gap: 20,
};
const headerStyle = {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "flex-start",
    paddingBottom: 20,
    borderBottom: "1px solid var(--v-border)",
};
const fieldStyle = {
    display: "flex",
    flexDirection: "column",
    gap: 4,
};
const inputStyle = {
    padding: "10px 14px",
    borderRadius: 8,
    border: "1px solid var(--v-border)",
    background: "var(--v-input)",
    color: "var(--v-fg)",
    fontFamily: "inherit",
    fontSize: 14,
};
const labelStyle = {
    fontSize: 13,
    fontWeight: 600,
    color: "var(--v-fg)",
};
const hintStyle = {
    fontSize: 12,
    color: "var(--v-muted-fg)",
};
const metaLabelStyle = {
    fontWeight: 600,
    textTransform: "uppercase",
    letterSpacing: 1,
};
const btnPrimaryStyle = {
    background: "var(--v-primary)",
    color: "var(--v-primary-fg)",
    border: "none",
    borderRadius: 8,
    padding: "10px 24px",
    fontSize: 14,
    fontWeight: 600,
    cursor: "pointer",
};
const btnDestructiveStyle = {
    background: "var(--v-destructive)",
    color: "var(--v-destructive-fg)",
    border: "none",
    borderRadius: 8,
    padding: "10px 24px",
    fontSize: 14,
    fontWeight: 600,
    cursor: "pointer",
};
