/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */

import { consume } from "@lit/context";
import "@material/web/progress/circular-progress";
import "@material/web/textfield/outlined-text-field";
import type { MdOutlinedTextField } from "@material/web/textfield/outlined-text-field.js";
import { MatterClient } from "@matter-server/ws-client";
import { LitElement, html, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators.js";
import { clientContext } from "../../../client/client-context.js";
import { handleAsync } from "../../../util/async-handler.js";
import { fireEvent } from "../../../util/fire_event.js";

@customElement("commission-node-wifi")
export class CommissionNodeWifi extends LitElement {
    @consume({ context: clientContext, subscribe: true })
    @property({ attribute: false })
    public client!: MatterClient;

    @state()
    private _loading: boolean = false;

    @query("md-outlined-text-field[label='SSID']")
    private _ssidField!: MdOutlinedTextField;
    @query("md-outlined-text-field[label='Password']")
    private _passwordField!: MdOutlinedTextField;
    @query("md-outlined-text-field[label='Pairing code']")
    private _pairingCodeField!: MdOutlinedTextField;

    protected override render() {
        if (!this.client.serverInfo.wifi_credentials_set) {
            return html`<md-outlined-text-field label="SSID" .disabled="${this._loading}"> </md-outlined-text-field>
                <md-outlined-text-field label="Password" type="password" .disabled="${this._loading}">
                </md-outlined-text-field>
                <br />
                <br />
                <md-outlined-button @click=${handleAsync(() => this._setWifiCredentials())} .disabled="${this._loading}"
                    >Set WiFi Credentials</md-outlined-button
                >${this._loading
                    ? html`<md-circular-progress indeterminate .visible="${this._loading}"></md-circular-progress>`
                    : nothing}`;
        }
        return html`<md-outlined-text-field label="Pairing code" .disabled="${this._loading}"> </md-outlined-text-field>
            <br />
            <br />
            <md-outlined-button @click=${handleAsync(() => this._commissionNode())} .disabled="${this._loading}"
                >Commission</md-outlined-button
            >${this._loading ? html` <md-circular-progress indeterminate></md-circular-progress> ` : nothing}`;
    }

    private async _setWifiCredentials() {
        const ssid = this._ssidField.value;
        if (!ssid) {
            alert("SSID is required");
            return;
        }
        const password = this._passwordField.value;
        if (!password) {
            alert("Password is required");
            return;
        }
        this._loading = true;
        try {
            await this.client.setWifiCredentials(ssid, password);
        } catch (err) {
            alert(`Error setting WiFi credentials: \n${(err as Error).message}`);
        } finally {
            this._loading = false;
        }
    }

    private async _commissionNode() {
        try {
            if (!this._pairingCodeField.value) {
                alert("Pairing code is required");
                return;
            }
            this._loading = true;
            const node = await this.client.commissionWithCode(this._pairingCodeField.value, false);
            fireEvent(this, "node-commissioned", node);
        } catch (err) {
            alert(`Error commissioning node: \n${(err as Error).message}`);
        } finally {
            this._loading = false;
        }
    }
}
