import { html } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { GlElement } from '../element.js';
import { checkboxBaseStyles } from './checkbox.css.js';

import '../code-icon.js';

export const tagName = 'gl-checkbox';

@customElement(tagName)
export class Checkbox extends GlElement {
	static override shadowRootOptions: ShadowRootInit = {
		...GlElement.shadowRootOptions,
		delegatesFocus: true,
	};

	static override readonly styles = [checkboxBaseStyles];

	@property({ type: Boolean, reflect: true })
	disabled: boolean = false;

	@property({ type: String })
	value: string = '';

	_defaultChecked: boolean = false;
	@property({ type: Boolean })
	get defaultChecked(): boolean {
		return this._defaultChecked;
	}

	@property({ type: Boolean, reflect: true })
	checked: boolean = false;

	@property({ type: Boolean, reflect: true })
	indeterminate: boolean = false;

	constructor() {
		super();
		this._defaultChecked = this.checked;
	}

	private handleChange(e: Event) {
		this.checked = (e.target as HTMLInputElement).checked;
		this.indeterminate = false;
		const event = new CustomEvent('gl-change-value');
		this.dispatchEvent(event);
	}

	private renderCheck() {
		if (this.indeterminate) {
			return html`<code-icon icon="dash"></code-icon>`;
		}

		return html`<code-icon icon="check" style="visibility: ${this.checked ? 'visible' : 'hidden'}"></code-icon>`;
	}

	override render(): unknown {
		return html`<label ?aria-disabled=${this.disabled}
			><input
				class="input"
				.disabled=${this.disabled}
				type="checkbox"
				.checked=${this.checked}
				@change=${this.handleChange}
			/>
			<div class="control">${this.renderCheck()}</div>
			<slot class="label-text" part="label"></slot>
		</label>`;
	}
}

declare global {
	interface HTMLElementTagNameMap {
		[tagName]: Checkbox;
	}
}
