import React from "react";
import { InputText } from "primereact/inputtext";
import { Dropdown, DropdownChangeParams } from "primereact/dropdown";
import "./NewWidget.scss";

import { Button } from "primereact/button";
import axios from "axios";
import { DataService } from "../services/DataService";
import { ApiQueryFilters } from "../data-contracts/ApiQueryFilter";
import { Widget } from "../types/widget";
import ReactApexChart from "react-apexcharts";
import { ChartComponentState } from "../types/ChartComponentState";

const calcTypes = 
[{Name: "Sum", Disabled: false},
 {Name: "Min", Disabled: true},
 {Name: "Max", Disabled: false},
 {Name: "Count", Disabled: false},
 {Name: "Average", Disabled: true}]
;
interface NewWidgetProps {
  onOkButton(data: Widget);
  onCancelButton();

}

interface NewWidgetState { 
  Widget: Widget;
  objectTables: any[]; 
  objectFields: any[];
}

const chartState:ChartComponentState = {
  series: [
    {
      data: [10,20,30],
    },
  ],
  options: {
    chart: {
      toolbar:{show: false},
      
    },
    colors: ["#22D792"],
    plotOptions: {
      bar: {
        borderRadius: 4,
        horizontal: true,
      }
    },
    dataLabels: {
      enabled: false,
    },
    xaxis: {
      categories: ['A','B','C'],
    },
  },
};

const ChartTypes = [{ Name: "Column", Disabled: true },{ Name: "Area", Disabled: false }, { Name: "Bar", Disabled: false }, { Name: "Pie", Disabled: true }, { Name: "Donut", Disabled: true }];
class NewWidget extends React.Component<NewWidgetProps, NewWidgetState> {
  constructor(props) {
    super(props);
    const defaultWidget: Widget = {
      WidgetName: 'New Widget',
      WidgetType: "Bar",
      CalcType: null,
      ValueFieldName: null,
      ValueFieldId: null,
      EntityName: null,
      EntityId: null,
      Group: null
    };
    this.state = {
      Widget: defaultWidget,
      objectTables: [],
      objectFields: [], 
    }; 
    this.getData();
  }
  getData() {
    this.getObjectTables();
  }
  getObjectTables() {
    let service = new DataService();
    const filters = new ApiQueryFilters();
    filters.addAdditionalFilter(
      "ObjectTableId",
      this.state.Widget.EntityName,
      null,
      null,
      "Equals",
      false,
      false,
      false,
      "string"
    );
    filters.addAdditionalFilter(
      "Name",
      'GLAccount,ARPayment,ARInvoice',
      null,
      null,
      "InListExact",
      false,
      false,
      false,
      "string"
    );
    service.getObjectTables(filters).then((response: any) => {
      console.log("getObjectTables", response);
      this.setState({ objectTables: response.data.Result });
    },(error)=>{
      alert("Something wrong happen, " + error);
    });
  }
  getObjectFields() {
    let service = new DataService();
    const filters = new ApiQueryFilters();
    filters.SortBy = 'FieldName';
    filters.addAdditionalFilter(
      "ObjectTableId",
      this.state.Widget.EntityId,
      null,
      null,
      "Equals",
      false,
      false,
      false,
      "string"
    );
    service.getObjectFields(filters).then((response: any) => {
      console.log("getByfilters", response);
      this.setState({ objectFields: response.data.Result });
    },(error)=>{
      alert("Something wrong happen, " + error);
    });
  }
selectedTable;
  onEntityChanged = (e: DropdownChangeParams) => {
    const selectedTable = e.target.value;
    this.selectedTable = selectedTable; 
    // const selectedTable = e.value;
    console.log("onEntityChanged",selectedTable);
    
    this.state.Widget.EntityName = selectedTable?.Name;
    this.state.Widget.EntityId = selectedTable?.Id;
    this.setState({ Widget: {...this.state.Widget} }, () => {
      if (selectedTable) {
        this.getObjectFields();
      } else {
            this.state.Widget.Group = null;
            this.state.Widget.ValueFieldId = null;
            this.state.Widget.ValueFieldName = null;
            this.setState({ Widget: {...this.state.Widget},
            objectFields: [] });
        }
    });
  }
  onGroupChanged = (e: DropdownChangeParams) => {
    this.state.Widget.Group = e.value;
    this.setState({ Widget: {...this.state.Widget} });
  }
  selectedValueField;
  onValueChanged = (e: DropdownChangeParams) => {
    this.selectedValueField = e.value;
    this.state.Widget.ValueFieldId = this.selectedValueField.Id;
    this.state.Widget.ValueFieldName = this.selectedValueField.FieldName;
    this.setState({ Widget: {...this.state.Widget} });
  };
  onCalcTypeChanged = (e: DropdownChangeParams) => {
    this.state.Widget.CalcType = e.value;
    this.setState({ Widget: {...this.state.Widget} });
  }
  render() {
    return (
      <div className="dialog-wrapper">
        <div className="dialog-content container">
          <div style={{ width: "250px", padding: '0 40px 0 0', textAlign: 'center' }}>
            <Dropdown
              style={{ width: "160px" }}
              value={this.state.Widget.WidgetType}
              options={ChartTypes}
              placeholder="Chart Type"
              optionLabel="Name"
              optionValue="Name"
              optionDisabled={(option) => option?.Disabled}
              onChange={(e) => {
                this.state.Widget.WidgetType = e.value;
                this.setState({ Widget: { ...this.state.Widget } });
              }}
            />
            <br />
            <br />
            <div>
              {this.state.Widget.WidgetType === 'Bar' && <ReactApexChart options={chartState.options} series={chartState.series} type="bar" height={"100%"} />}
              {this.state.Widget.WidgetType === 'Area' && <ReactApexChart options={chartState.options} series={chartState.series} type="area" height={"100%"} />}
            </div>
          </div>

          <div>
            <form id="frm" name="frm">
              {/* <input type="submit" opacity /> */}
              <div className="form">
                {/* Name */}
                <div className="form-field">
                  <label htmlFor="widget-name">Name</label>
                  <InputText
                    id="widget-name"
                    className="p-inputtext-sm"
                    value={this.state.Widget.WidgetName || undefined}
                    required
                    onChange={(e) => {
                      this.state.Widget.WidgetName = e.target.value;
                      this.setState({ Widget: { ...this.state.Widget } });
                    }}
                  />
                </div>

                {/* Entity */}
                <div className="form-field">
                  <label htmlFor="widget-Entity">Entity</label>
                  <Dropdown
                    value={this.selectedTable}
                    options={this.state.objectTables}
                    onChange={this.onEntityChanged}
                    optionLabel="Name"
                    // optionValue="Id"
                    filter
                    showClear
                    filterBy="Name"
                    placeholder="Select an entity"
                    // valueTemplate={selectedCountryTemplate}
                    // itemTemplate={countryOptionTemplate}
                  />
                </div>

                {/* Group  */}
                <div className="form-field">
                  <label htmlFor="widget-Entity">Group</label>
                  <Dropdown
                    value={this.state.Widget.Group}
                    options={this.state.objectFields}
                    virtualScrollerOptions={{ itemSize: 50 }}
                    onChange={this.onGroupChanged}
                    optionLabel="FieldName"
                    optionValue="FieldName"
                    filter
                    showClear
                    filterBy="FieldName"
                    placeholder="Select group"
                  />
                </div>

                {/*       CalcType  */}
                <div className="form-field">
                  <label htmlFor="widget-Entity">Calc. Type</label>
                  <Dropdown
                    value={this.state.Widget.CalcType}
                    options={calcTypes}
                    optionLabel="Name"
                    optionValue="Name"
                    optionDisabled={(option) => option?.Disabled}
                    onChange={this.onCalcTypeChanged}
                    showClear
                    required
                    placeholder="Select type"
                  />
                </div>

                {/* Value  */}
                <div className="form-field">
                  <label htmlFor="widget-Entity">Value</label>
                  <Dropdown
                    value={this.selectedValueField}
                    options={this.state.objectFields}
                    virtualScrollerOptions={{ itemSize: 50 }}
                    onChange={this.onValueChanged}
                    optionLabel="FieldName"
                    // optionValue="Id"
                    filter
                    showClear
                    filterBy="FieldName"
                    placeholder="Select value"
                  />
                </div>
              </div>
            </form>
          </div>
        </div>

        <div className="dialog-footer">
          <Button
            label="Cancel"
            className="p-button-text"
            onClick={this.props.onCancelButton.bind(this)}
          />
          <Button
            label="Ok"
            form="frm"
            // icon="pi pi-check"
            onClick={this.props.onOkButton.bind(this, { ...this.state.Widget })}
            autoFocus
          />
        </div>
      </div>
    );
  }
}

export default NewWidget;
