import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc, HeightSym } from '../../../../fields/Doc';
import { ChartJSOrUndefined } from 'react-chartjs-2/dist/types';
import { action, computed, observable } from 'mobx';
import { Cast, NumCast, StrCast } from '../../../../fields/Types';
import { CategoricalChartState } from 'recharts/types/chart/generateCategoricalChart';
import { LineChart } from './LineChart';

export interface ChartBoxProps {
    rootDoc: Doc;
    dataDoc: Doc;
    pairs: { x: number; y: number }[];
    setChartBox: (chartBox: ChartBox) => void;
    getAnchor: () => Doc;
}

const primaryColor = 'rgba(53, 162, 235, 0.5)';
const selectedColor = 'rgba(255, 99, 132, 0.5)';

export interface RechartData {
    name: string | number;
    y: number;
}

export interface DataPoint {
    x: number;
    y: number;
}

export interface ChartData {
    xLabel: string;
    yLabel: string;
    data: DataPoint[];
    tooltipContent: (data: DataPoint) => string;
}

@observer
export class ChartBox extends React.Component<ChartBoxProps> {
    @observable private _chartData: ChartData | undefined = undefined;
    @observable private currChart: LineChart | undefined;

    @computed get currView() {
        if (this.props.rootDoc._dataVizView) {
            return StrCast(this.props.rootDoc._currChartView);
        } else {
            return 'table';
        }
    }

    constructor(props: any) {
        super(props);
        if (!this.props.rootDoc._currChartView) {
            this.props.rootDoc._currChartView = 'bar';
        }
    }

    setCurrChart(chart: LineChart | undefined) {
        // this.currChart = chart;
    }

    @action
    generateChartData() {
        if (this.props.rootDoc._chartData) {
            this._chartData = JSON.parse(StrCast(this.props.rootDoc._chartData));
            return;
        }

        const data: ChartData = {
            xLabel: '',
            yLabel: '',
            data: [],
            tooltipContent: (data: DataPoint) => {
                return `<b>x: ${data.x} y: ${data.y}</b>`;
            },
        };

        if (this.props.pairs && this.props.pairs.length > 0) {
            data.xLabel = 'x';
            data.yLabel = 'y';
            this.props.pairs.forEach(pair => {
                data.data.push({ x: pair.x, y: pair.y });
            });
        }

        this._chartData = data;
        this.props.rootDoc._chartData = JSON.stringify(data);
    }

    // @action
    // generateChartJsData() {
    //     if (this.props.rootDoc._chartData) {
    //         // parse the string into a json object
    //         this._chartJsData = JSON.parse(StrCast(this.props.rootDoc._chartData));
    //         this._prevColor = StrCast(this.props.rootDoc._prevColor);
    //         this._prevIndex = JSON.parse(StrCast(this.props.rootDoc._prevIndex));
    //         return;
    //     }
    //     const labels = this.props.pairs.map(p => p.x);
    //     const dataset = {
    //         label: 'Dataset 1',
    //         data: this.props.pairs.map(p => p.y),
    //         backgroundColor: this.props.pairs.map(p => primaryColor),
    //     };
    //     const data = {
    //         labels,
    //         datasets: [dataset],
    //     };
    //     this._chartJsData = data;
    // }

    componentDidMount() {
        // this.generateChartJsData();
        this.generateChartData();
        // setting timeout to allow rerender cycle of the actual chart tof inish
        setTimeout(() => {
            this.props.setChartBox(this);
        });
        // this.props.setChartBox(this);
    }

    @action
    onClickChangeChart = (e: React.MouseEvent<HTMLButtonElement>) => {
        e.preventDefault();
        e.stopPropagation();
        console.log(e.currentTarget.value);
        this.props.rootDoc._currChartView = e.currentTarget.value.toLowerCase();
    };

    onMouseMove = (e: CategoricalChartState) => {
        console.log(e);

        // pops up at 526 when it should be at 263
        // at 100%scale it pops up at 526 but mouse shows 263 at 50% scale
        if (e.chartX && e.chartY) {
            e.chartX += 263;
            e.chartY += 263;
        }
        // if (e.chartX && e.chartY) {
        //     e.chartX -= 200;
        //     e.chartY -= 200;
        // }
    };

    scrollFocus(doc: Doc, smooth: boolean) {}

    handleDotClick = (e: any) => {
        console.log(e);
    };

    _getAnchor() {
        return this.currChart?._getAnchor();
    }

    // handleTextClick = (e: any) => {
    //     console.log(e);
    // }

    // @computed get reLineChart() {
    //     return (
    //         // <ResponsiveContainer width="80%" height="80%">
    //         <LineChart
    //             width={500}
    //             height={300}
    //             data={this._chartData}
    //             margin={{
    //                 top: 5,
    //                 right: 30,
    //                 left: 20,
    //                 bottom: 5,
    //             }}
    //             onMouseDown={e => console.log(e)}
    //             onMouseMove={e => this.onMouseMove(e)}>
    //             <CartesianGrid strokeDasharray="3 3" />
    //             <XAxis dataKey="name" onMouseDown={e => console.log(e)} />
    //             <YAxis />
    //             <Tooltip />
    //             <Legend />
    //             <Line type="monotone" dataKey="y" stroke="#8884d8" activeDot={{ r: 8, onClick: this.handleDotClick }} />
    //             {/* <Line type="monotone" dataKey="uv" stroke="#82ca9d" /> */}
    //         </LineChart>
    //         // </ResponsiveContainer>
    //     );
    // }

    render() {
        if (this.props.pairs && this._chartData) {
            let width = NumCast(this.props.rootDoc._width);
            width = width * 0.7;
            let height = NumCast(this.props.rootDoc._height);
            height = height * 0.7;
            console.log(width, height);
            return (
                <div>
                    <div>
                        {/*{this.props.rootDoc._currChartView == 'line' ? (
                            <Line ref={this._chartRef} options={this.options} data={this._chartJsData} onClick={e => this.onClick(e)} />
                        ) : (
                            <Bar ref={this._chartRef} options={this.options} data={this._chartJsData} onClick={e => this.onClick(e)} />
                        )} */}
                        {/* {this.reLineChart} */}
                        <LineChart width={width} height={height} data={this._chartData} setCurrChart={this.setCurrChart} dataDoc={this.props.dataDoc} fieldKey={'data'} getAnchor={this.props.getAnchor} />
                    </div>
                    <button onClick={e => this.onClickChangeChart(e)} value="line">
                        Line
                    </button>
                    <button onClick={e => this.onClickChangeChart(e)} value="bar">
                        Bar
                    </button>
                </div>
            );
        } else {
            return <div></div>;
        }
    }
}
