import { makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { ViewBoxAnnotatableComponent, ViewBoxInterface } from '../DocComponent';
import { StyleProp } from '../StyleProvider';
import './DiagramBox.scss';
import { FieldView, FieldViewProps } from './FieldView';
import { PinProps, PresBox } from './trails';
import mermaid from 'mermaid';
import { Doc, DocListCast } from '../../../fields/Doc';
import { List } from '../../../fields/List';

interface MermaidProps {
    chart: String;
}

class Mermaid extends React.Component<MermaidProps> {
    componentDidMount() {
        mermaid.contentLoaded();
    }
    render() {
        return <pre className="mermaid">{this.props.chart}</pre>;
    }
}

@observer
export class DiagramBox extends ViewBoxAnnotatableComponent<FieldViewProps>() implements ViewBoxInterface {
    @observable chartContent: string = '';

    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(DiagramBox, fieldKey);
    }
    constructor(props: FieldViewProps) {
        super(props);
        makeObservable(this);
        //this.createMermaidCode();
        this.chartContent = 'flowchart LR;A-->B:::wide;B-->C:::wide; B-->D[hello];';
    }

    componentDidMount() {
        this._props.setContentViewBox?.(this);
        // (window as any)["callb"] = (x: any) => {
        //     alert(x);
        // };
        mermaid.initialize({
            securityLevel: "loose",
            startOnLoad: true,
            flowchart: { useMaxWidth: true, htmlLabels: true, curve: 'cardinal' },
        });

        const renderMermaid = async (str: string) => {
            try {
                const { svg, bindFunctions } = await mermaid2(str);
                return { svg, bindFunctions };
            } catch (error) {
                console.error("Error rendering mermaid diagram:", error);
                return { svg: "", bindFunctions: undefined };
            }
        };
        const mermaid2 = async (str: string) => {
            return await mermaid.render("graph" + Date.now(), str);
        };
        renderMermaid(this.chartContent).then(({ svg, bindFunctions }) => {
            const dashDiv = document.getElementById('dashDiv');
            if (dashDiv) {
                dashDiv.innerHTML = svg;
                if (bindFunctions) {
                    bindFunctions(dashDiv);
                }
            }
        });
    }
    createMermaidCode = (): void => {
        if (this.Document.data instanceof List) {
            let docArray: Doc[] = DocListCast(this.Document.data);
            let mermaidCode = 'graph LR;';
            docArray.map(doc => {
                if (doc.title == 'rectangle') {
                    DocListCast(this.Document.data).map(lineDoc => {
                        if (
                            (lineDoc.title == 'stroke' || lineDoc.title == 'line') &&
                            typeof lineDoc.x === 'number' &&
                            typeof doc.x === 'number' &&
                            typeof doc.width === 'number' &&
                            typeof doc.height === 'number' &&
                            typeof doc.y === 'number' &&
                            typeof lineDoc.y === 'number'
                        ) {
                            if (lineDoc.x < doc.x + doc.width + (doc.width + doc.x) * 0.1 && lineDoc.x > doc.x && lineDoc.y > doc.y && lineDoc.y < doc.y + doc.height) {
                                DocListCast(this.Document.data).map(doc2 => {
                                    if (
                                        doc2.title == 'rectangle' &&
                                        typeof lineDoc.x === 'number' &&
                                        typeof lineDoc.width === 'number' &&
                                        typeof doc2.x === 'number' &&
                                        typeof doc2.width === 'number' &&
                                        typeof doc2.y === 'number' &&
                                        typeof doc2.height === 'number' &&
                                        typeof lineDoc.y === 'number'
                                    ) {
                                        if (
                                            lineDoc.x + lineDoc.width > doc2.x - (doc2.x - doc2.width) * 0.1 &&
                                            lineDoc.x + lineDoc.width < doc2.x + doc2.width &&
                                            lineDoc.y > doc2.y &&
                                            lineDoc.y < doc2.y + doc2.height &&
                                            typeof doc.x === 'number' &&
                                            typeof doc.width === 'number'
                                        ) {
                                            mermaidCode += doc.title + Math.floor(doc.x).toString() + '-->' + doc2.title + Math.floor(doc2.x).toString() + ';';
                                            const indexToRemove = docArray.findIndex(doc => doc === lineDoc);
                                            if (indexToRemove !== -1) {
                                                docArray.splice(indexToRemove, 1);
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    });
                }
                this.chartContent = mermaidCode;
            });
        }
    };
    render() {
        console.log(this.ScreenToLocalBoxXf().Scale);
        return (
            <div id="dashDiv"></div>
        );
    }
}
