import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import ApexCharts from 'apexcharts';

@customElement('apex-chart')
export class ApexChart extends LitElement {
    private chart?: ApexCharts;

    protected createRenderRoot() {
        return this;
    }

    render() {
        return html`<div id="container" style="width:100%;height:100%"></div>`;
    }

    async renderChart(optionsJson: string) {
        await this.updateComplete;
        const options = JSON.parse(optionsJson);

        options.chart = {
            ...options.chart,
            events: {
                dataPointSelection: (_e: unknown, _ctx: unknown, cfg: any) => {
                    (this as any).$server.onPointClick(cfg.seriesIndex, cfg.dataPointIndex);
                },
            },
        };

        const container = this.querySelector('#container') as HTMLElement;
        if (this.chart) {
            await this.chart.updateOptions(options);
        } else {
            this.chart = new ApexCharts(container, options);
            await this.chart.render();
        }
    }

    disconnectedCallback() {
        super.disconnectedCallback();
        this.chart?.destroy();
    }
}