import React from "react";
import { Root, createRoot } from "react-dom/client";
import styles from "./styles/onboarding.index.css?inline";
import { ColorTheme, SignInPageApi, ThemeType } from "./types/shared-types";
import { App } from "./app";
import { WithApiContext } from "./context";
import { WithOnboardingStateContext } from "./context/onboarding-state";

export class KiroSignInPage extends HTMLElement {
	private root: Root | null = null;

	private api: SignInPageApi | undefined;
	private themes: ColorTheme[] = [];
	private currentThemeId: string = "";
	private portalUrl: string | undefined;

	// Define the observed attributes
	static get observedAttributes(): string[] {
		return ["requiredsteps", "themetype"];
	}

	constructor() {
		super();
		this.attachShadow({ mode: "open" });
		this.root = this.root
			? this.root
			: createRoot(this.shadowRoot as ShadowRoot);
		const styleEl = document.createElement("style");
		styleEl.textContent = styles;
		this.shadowRoot?.appendChild(styleEl);
	}

	// Handle attribute changes
	attributeChangedCallback(name: string) {
		if (name === "requiredsteps" || name === "themetype") {
			this.render();
		}
	}

	public setThemes(themes: ColorTheme[], currentThemeId: string): void {
		this.themes = themes;
		this.currentThemeId = currentThemeId;
		this.render();
	}

	public setApi(api: SignInPageApi): void {
		this.api = api;
		this.render();
	}

	public setPortalUrl(url: string): void {
		this.portalUrl = url;
		this.render();
	}

	private render() {
		if (!this.api) {
			return null;
		}
		const themeType = this.getAttribute("themetype") as ThemeType;
		this.root?.render(
			<React.StrictMode>
				<WithApiContext api={this.api}>
					<WithOnboardingStateContext>
						<App
							themes={this.themes}
							currentThemeId={this.currentThemeId}
							portalUrl={this.portalUrl}
						/>
					</WithOnboardingStateContext>
				</WithApiContext>
			</React.StrictMode>
		);
	}

	connectedCallback() {
		this.render();
	}
}

//export default KiroSignInPage;

// Register the custom element
customElements.define("kiro-sign-in-page", KiroSignInPage);
