/**
 * Copyright Aquera Inc 2023
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {
  LitElement,
  html,
  CSSResultArray,
  TemplateResult,
} from 'lit';
import { customElement, query, property } from 'lit/decorators.js';
import { styles } from './nile-circular-progressbar.css';
import NileElement from '../internal/nile-element';
import logInfo from '../nile-icon/icons/svg/log-info';

@customElement('nile-circular-progressbar')
export class NileCircularProgressbar extends NileElement {
  public static get styles(): CSSResultArray {
    return [styles];
  }

  @query('.progress') progressCircle!: SVGCircleElement;
  
  @property({ type: Number, reflect: true }) value = 0;
  // Add a flag to track if the value is invalid
  private isInvalidValue = false;

  @property({ type: String, reflect: true }) content?: string;
  @property({ type: Number, reflect: true }) size = 40;

  private get circleSize() {
    const radius = this.size / 2 - 4;
    return {
      radius,
      viewBox: this.size,
      fontSize: `${this.size * 0.25}px`,
    };
  }

  connectedCallback() {
    super.connectedCallback();
    this.updateComplete.then(() => {
      this.value = Math.max(0, Math.min(100, this.value));
      this.setProgress(this.value);
    });
  }

  private setProgress(percent: number) {
    if (this.progressCircle) {
      const circleRadius = this.progressCircle.r.baseVal.value;
      const circumference = circleRadius * 2 * Math.PI;

      this.progressCircle.style.transition = 'stroke-dashoffset 0.8s ease-in-out';
      this.progressCircle.style.strokeDasharray = `${circumference}`;
      this.progressCircle.style.strokeDashoffset = `${circumference - (percent / 100) * circumference}`;
    }
  }

  private validateValue() {
    if (isNaN(this.value) || this.value < 0 || this.value > 100) {
      console.error(`[NileCircularProgressBar]: Invalid value (${this.value}) detected. Value must be between 0 to 100.`);
      this.value = 0;
      this.isInvalidValue = true; 
    } else {
      this.isInvalidValue = false;  
    }
  }

  override updated(changedProperties: Map<string, any>) {
    if (changedProperties.has('value')) {
      this.validateValue();
      this.setProgress(this.value);

      if (this.value === 100) {
        this.emit('nile-complete', { message: 'Nile Circular Progress reached 100%' });
      }
    }
  }

  public render(): TemplateResult {
    const { radius, viewBox, fontSize } = this.circleSize;
    // Modified innerText logic
    const innerText = this.isInvalidValue 
      ? ' ' 
      : (this.content ?? `${Math.round(this.value)}%`); // Show "Null" for invalid, otherwise keep original behavior

    return html`
      <svg width="${viewBox}" height="${viewBox}" viewBox="0 0 ${viewBox} ${viewBox}">
        <circle r="${radius}" cx="${viewBox / 2}" cy="${viewBox / 2}" class="track"></circle>
        <circle r="${radius}" cx="${viewBox / 2}" cy="${viewBox / 2}" class="progress"></circle>
        
        <text
          x="50%"
          y="53%"
          text-anchor="middle"
          alignment-baseline="middle"
          class="circle__text"
          style="font-size: ${fontSize};"
        >
          ${innerText}
        </text>
      </svg>
    `;
  }
}

export default NileCircularProgressbar;

declare global {
  interface HTMLElementTagNameMap {
    'nile-circular-progressbar': NileCircularProgressbar;
  }
}