"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState, } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { useOrganization } from "./useOrganization";
import { useUpdateOrganization } from "./useUpdateOrganization";
import { useIdentityProviderList } from "../identity-provider/useIdentityProviderList";
import { useResourceAvailable, ApiResourceKind } from "../deployment-mode";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const DESCRIPTION_MAX_LEN = 500;
const LOGO_URL_MAX_LEN = 2048;
/**
 * Self-contained profile editor for an {@link Organization} resource.
 *
 * Fetches the organization by ID, displays editable fields (name,
 * description, logo URL) and read-only identifiers (slug, ID).
 * On save, calls `organization.update()` and fires `onUpdated`.
 *
 * All visual properties flow through `--stgm-*` design tokens. The
 * component has zero dependencies on Console routing, auth context,
 * or layout — platform builders can embed it directly:
 *
 * @example
 * ```tsx
 * <OrgProfilePanel
 *   orgId="org-id-123"
 *   onUpdated={(org) => console.log("Saved:", org.metadata?.name)}
 * />
 * ```
 */
export function OrgProfilePanel({ orgId, onUpdated, className, }) {
    const { organization, isLoading: isFetching, error: fetchError, refetch, } = useOrganization(orgId || null);
    const { update, isUpdating, error: updateError, clearError, } = useUpdateOrganization();
    // Form state — synchronized from server data when it loads/changes.
    const [name, setName] = useState("");
    const [description, setDescription] = useState("");
    const [logoUrl, setLogoUrl] = useState("");
    // Track the server snapshot so we can detect changes and reset.
    const serverName = organization?.metadata?.name ?? "";
    const serverDescription = organization?.spec?.description ?? "";
    const serverLogoUrl = organization?.spec?.logoUrl ?? "";
    const serverSlug = organization?.metadata?.slug ?? "";
    const serverOrgId = organization?.metadata?.id ?? "";
    const isPersonal = organization?.spec?.isPersonal ?? false;
    // Sync form fields when server data changes.
    useEffect(() => {
        if (!organization)
            return;
        setName(organization.metadata?.name ?? "");
        setDescription(organization.spec?.description ?? "");
        setLogoUrl(organization.spec?.logoUrl ?? "");
    }, [organization]);
    const hasChanges = useMemo(() => name.trim() !== serverName ||
        description.trim() !== serverDescription ||
        logoUrl.trim() !== serverLogoUrl, [name, description, logoUrl, serverName, serverDescription, serverLogoUrl]);
    const canSubmit = name.trim().length > 0 && !isUpdating && hasChanges;
    const handleDiscard = useCallback(() => {
        setName(serverName);
        setDescription(serverDescription);
        setLogoUrl(serverLogoUrl);
        clearError();
    }, [serverName, serverDescription, serverLogoUrl, clearError]);
    const handleSubmit = useCallback(async (e) => {
        e.preventDefault();
        if (!canSubmit || !organization)
            return;
        clearError();
        try {
            const updated = await update({
                name: name.trim(),
                slug: serverSlug,
                org: serverSlug,
                description: description.trim() || undefined,
                logoUrl: logoUrl.trim() || undefined,
            });
            refetch();
            onUpdated?.(updated);
        }
        catch {
            // error state is managed by useUpdateOrganization
        }
    }, [
        canSubmit,
        organization,
        name,
        description,
        logoUrl,
        serverSlug,
        update,
        clearError,
        refetch,
        onUpdated,
    ]);
    // -----------------------------------------------------------------------
    // Loading state
    // -----------------------------------------------------------------------
    if (isFetching && !organization) {
        return (_jsx("div", { className: cn("space-y-4", className), "aria-busy": "true", "aria-label": "Loading organization profile", children: Array.from({ length: 4 }, (_, i) => (_jsx("div", { className: "bg-muted-subtle h-10 animate-pulse rounded", style: { width: `${90 - i * 12}%` } }, i))) }));
    }
    // -----------------------------------------------------------------------
    // Fetch error
    // -----------------------------------------------------------------------
    if (fetchError) {
        return (_jsxs("div", { className: cn("space-y-3", className), role: "alert", children: [_jsx("p", { className: "text-destructive text-sm", children: getUserMessage(fetchError) }), _jsx("button", { type: "button", onClick: refetch, className: cn("rounded-md px-3 py-1.5 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover"), children: "Retry" })] }));
    }
    if (!organization)
        return null;
    // -----------------------------------------------------------------------
    // Render
    // -----------------------------------------------------------------------
    return (_jsxs("form", { onSubmit: handleSubmit, className: cn("space-y-6", className), children: [_jsxs("div", { className: "space-y-3", children: [_jsx(ReadOnlyField, { label: "Slug", value: serverSlug, mono: true }), _jsx(ReadOnlyField, { label: "Organization ID", value: serverOrgId }), isPersonal && (_jsx("div", { children: _jsx("span", { className: "bg-primary-subtle text-primary rounded-full px-2 py-0.5 text-[0.6rem] font-medium uppercase tracking-wider", children: "Personal" }) }))] }), _jsx("hr", { className: "border-border" }), _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("label", { htmlFor: "stgm-org-profile-name", className: "text-xs font-medium text-foreground", children: "Name" }), _jsx("input", { id: "stgm-org-profile-name", type: "text", value: name, onChange: (e) => setName(e.target.value), disabled: isUpdating, required: true, className: cn("w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50") }), _jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: "The display name shown in the sidebar and across the platform." })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("label", { htmlFor: "stgm-org-profile-desc", className: "text-xs font-medium text-foreground", children: "Description" }), _jsx("textarea", { id: "stgm-org-profile-desc", value: description, onChange: (e) => setDescription(e.target.value), maxLength: DESCRIPTION_MAX_LEN, rows: 3, disabled: isUpdating, placeholder: "What is this organization for?", className: cn("w-full resize-y rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50") }), _jsxs("p", { className: "text-[0.65rem] text-muted-foreground", children: [description.length, "/", DESCRIPTION_MAX_LEN, " characters"] })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("label", { htmlFor: "stgm-org-profile-logo", className: "text-xs font-medium text-foreground", children: "Logo URL" }), _jsx("input", { id: "stgm-org-profile-logo", type: "url", value: logoUrl, onChange: (e) => setLogoUrl(e.target.value), maxLength: LOGO_URL_MAX_LEN, disabled: isUpdating, placeholder: "https://example.com/logo.png", className: cn("w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50") }), _jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: "A public URL to your organization's logo image." }), _jsx(LogoPreview, { url: logoUrl.trim() })] })] }), updateError && (_jsx("p", { className: "text-destructive text-[0.65rem]", role: "alert", children: getUserMessage(updateError) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("button", { type: "submit", disabled: !canSubmit, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-40"), children: [isUpdating && _jsx(SpinnerIcon, {}), "Save changes"] }), hasChanges && !isUpdating && (_jsx("button", { type: "button", onClick: handleDiscard, className: cn("rounded-md px-3 py-1.5 text-xs", "text-muted-foreground hover:text-foreground hover:bg-accent-hover"), children: "Discard" }))] }), _jsx(IdentityProvidersSummary, { orgSlug: serverSlug })] }));
}
// ---------------------------------------------------------------------------
// IdentityProvidersSummary — shows linked IDPs on the org profile
// ---------------------------------------------------------------------------
function IdentityProvidersSummary({ orgSlug }) {
    const idpAvailable = useResourceAvailable(ApiResourceKind.identity_provider);
    const { identityProviders, isLoading } = useIdentityProviderList(idpAvailable && orgSlug ? orgSlug : null);
    if (!idpAvailable || !orgSlug)
        return null;
    return (_jsxs(_Fragment, { children: [_jsx("hr", { className: "border-border" }), _jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-[0.65rem] font-medium text-muted-foreground uppercase tracking-wider", children: "Identity Providers" }), isLoading ? (_jsx("div", { className: "bg-muted-subtle h-8 animate-pulse rounded" })) : identityProviders.length === 0 ? (_jsxs("p", { className: "text-xs text-muted-foreground", children: ["No identity providers configured.", " ", _jsx("a", { href: "/settings/identity-providers", className: "text-primary hover:text-primary-hover underline underline-offset-2", children: "Set up federated authentication" })] })) : (_jsxs("div", { className: "space-y-1.5", children: [identityProviders.map((idp) => {
                                const spec = idp.spec;
                                const displayName = spec?.displayName || idp.metadata?.name || "Unnamed";
                                const isSso = spec?.isSsoProvider;
                                const isJit = !isSso && spec?.autoProvisionAccounts;
                                return (_jsxs("div", { className: "flex items-center gap-2 text-xs", children: [_jsx(ShieldSmallIcon, {}), _jsx("span", { className: "text-foreground truncate", children: displayName }), isSso && (_jsx("span", { className: "rounded-full border border-primary/30 bg-primary-subtle px-1.5 py-px text-[0.6rem] font-medium text-primary", children: "SSO" })), isJit && (_jsx("span", { className: "rounded-full border border-primary/30 bg-primary-subtle px-1.5 py-px text-[0.6rem] font-medium text-primary", children: "JIT" }))] }, idp.metadata?.id));
                            }), _jsx("a", { href: "/settings/identity-providers", className: "inline-block text-[0.65rem] text-primary hover:text-primary-hover underline underline-offset-2", children: "Manage" })] }))] })] }));
}
function ShieldSmallIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: "shrink-0 text-muted-foreground", children: _jsx("path", { d: "M8 1.5L2 4v4c0 3.5 2.5 5.5 6 7 3.5-1.5 6-3.5 6-7V4L8 1.5z" }) }));
}
// ---------------------------------------------------------------------------
// ReadOnlyField — copiable label/value pair
// ---------------------------------------------------------------------------
function ReadOnlyField({ label, value, mono, }) {
    const [copied, setCopied] = useState(false);
    const handleCopy = useCallback(() => {
        navigator.clipboard.writeText(value).then(() => {
            setCopied(true);
            setTimeout(() => setCopied(false), 1500);
        });
    }, [value]);
    if (!value)
        return null;
    return (_jsxs("div", { className: "space-y-0.5", children: [_jsx("p", { className: "text-[0.65rem] font-medium text-muted-foreground uppercase tracking-wider", children: label }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: cn("text-xs text-foreground select-all", mono && "font-mono"), children: value }), _jsx("button", { type: "button", onClick: handleCopy, className: cn("rounded px-1.5 py-0.5 text-[0.6rem]", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "transition-colors"), "aria-label": `Copy ${label}`, children: copied ? "Copied" : "Copy" })] })] }));
}
// ---------------------------------------------------------------------------
// LogoPreview — shows a small preview when the URL looks like an image
// ---------------------------------------------------------------------------
function LogoPreview({ url }) {
    const [status, setStatus] = useState("idle");
    useEffect(() => {
        setStatus("idle");
    }, [url]);
    if (!url || status === "error")
        return null;
    return (_jsx("div", { className: "mt-2", children: _jsx("img", { src: url, alt: "Organization logo preview", onLoad: () => setStatus("loaded"), onError: () => setStatus("error"), className: cn("h-10 w-10 rounded-md border border-border object-contain bg-background", status === "idle" && "opacity-0", status === "loaded" && "opacity-100") }) }));
}
// ---------------------------------------------------------------------------
// SpinnerIcon
// ---------------------------------------------------------------------------
function SpinnerIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=OrgProfilePanel.js.map