import React, { Component } from 'react';
import { Form, Col, Table } from 'react-bootstrap';
import Config from '../config/appConstants';
import { withNamespaces } from 'react-i18next';
import UtilsService from '../services/shared/utils.service';
import translateLabel from "../translation";
import { setLN1A_App } from '../redux';
import { connect } from 'react-redux';
import BlockRoundedIcon from '@material-ui/icons/BlockRounded';
import DeleteForeverRoundedIcon from '@material-ui/icons/DeleteForeverRounded';

class RowTable extends Component {

  constructor(props) {
    super(props);

    this.defaultTableData = [];
    this.formData = this.props.stateVal;
    this.state = {
       rows: [],
       tableData: [],
       newRow:[]
       };
    this.utils = new UtilsService();
    this.checkValue = [];
    //this.handleChange      = this.handleChange.bind(this);
    this.updateStatusValue            = this.updateStatusValue.bind(this);
    this.handleSubmit                 = this.handleSubmit.bind(this);
    this.updateResidentialStatusValue = this.updateResidentialStatusValue.bind(this);
    this.updateCommercialStatusValue  = this.updateCommercialStatusValue.bind(this);
    this.handleRowTableData           = this.handleRowTableData.bind(this);
    this.handleSectionEditClick       = this.handleSectionEditClick.bind(this);
    this.updateStatusValue();
  }

  updateStatusValue() {
    switch (this.props.ServiceSubID) {
      case "LN1A":
        this.updateResidentialStatusValue();
        break;
      case "LN1B":
        this.updateResidentialStatusValue();
        // this.updateCommercialStatusValue();
        break;
      default:
    }
  }

  handleRowTableData(rowData) {
    // this.props.
  }

  updateResidentialStatusValue() {
    if (this.props.viewType === "form" && this.props.responseData.hasOwnProperty("IndividualDetails") && this.props.responseData.IndividualDetails.hasOwnProperty("RelationshipDetails")) {
      var tableDataValue;
      var newRows = this.props.inputTable.tablelist.tabData;
      tableDataValue = this.getSpouseToDataTable(this.props.inputTable.tablelist.tabData);
      // this.state = { rows: [...tableDataValue], tableData: [], newRow:[...newRows] };
      this.setState({ rows: [...tableDataValue], tableData: [], newRow:[...newRows] });
      //this.state = { rows: [{ ...this.props.inputTable.tablelist.tabData }], tableData: [] };
    } else {
      if (this.props.viewType === "form") {
        if (typeof this.formData === "object" && this.formData.gender !== "") {
          this.props.inputTable.tablelist.tabData[3].relationShip = Config.RELATIONSHIP_LIST[this.formData.gender];
        }
      }
      // this.state = { rows: [{ ...this.props.inputTable.tablelist.tabData }], tableData: [] };
      this.setState({ rows: [{ ...this.props.inputTable.tablelist.tabData }], tableData: [] });
    }
  }

  updateCommercialStatusValue() {
    if (this.props.viewType === "form" && this.props.responseData.hasOwnProperty("CompanyDetails") && this.props.responseData.CompanyDetails.hasOwnProperty("CompanyPartner")) {
      var tableDataValue;
      tableDataValue = this.getPartnerToDataTable();
      // this.state = { rows: [...tableDataValue], tableData: [] };
      this.setState({ rows: [...tableDataValue], tableData: [] });
    } else {
      if (this.props.viewType === "form") {
        if (typeof this.formData === "object" && this.formData.gender !== "") {
          this.props.inputTable.tablelist.tabData[3].relationShip = Config.RELATIONSHIP_LIST[this.formData.gender];
        }
      }
      // this.state = { rows: [{ ...this.props.inputTable.tablelist.tabData }], tableData: [] };
      this.setState({ rows: [{ ...this.props.inputTable.tablelist.tabData }], tableData: [] });
    }
    //this.state = {rows: [{...this.props.inputTable.tablelist.tabData}], tableData:[]};
  }

  handleChange(event, rowId, elemId) {
    const { name, value } = event.target;
    const rows = [...this.state.rows];
    rows[rowId][elemId] = {
      ...rows[rowId][elemId],
      [name]: value
    };
    this.props.onCallBack(this.state.rows);
  }

  handleAddRow(rowData) {
    let newRow = [];
    rowData.forEach(function(rData, key) {
     if(key !== 2) {
        rData[rData["name"]] = "";
        rData["readOnly"] = false;
        rData["disabled"] = false;
      }
      newRow.push(rData);
    })
    if (Object.keys(this.state.rows).length < 4) {
      const item = { ...rowData };
      this.setState({
        rows: [...this.state.rows, item]
      });
      this.addRowBtn = false;
    } else {
      alert("Maximum entries reached")
    }
  }

  handleRemoveRow() {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
    this.addRowBtn = true;
  }

  handleDeleteRow(idx) {
    const rows = [...this.state.rows]
    rows.splice(idx, 1)
    this.setState({ rows });
    this.addRowBtn = true;
  }

  handleSubmit(event) {
    const request = JSON.stringify(this.state);
    this.props.onAppFormSubmit(request, event);
    event.preventDefault();
  }

  handleSectionEditClick() {
    this.props.onSectionActionClick(this.props.tablewizardStep,this.props.inputTable.tablelist.editTabIndex);
  }

  getSpouseToDataTable(tabRowData) {
    var rowData = [];
    var addRowData = [];
    var fieldName;
    //var rowLength = this.props.responseData.IndividualDetails.SpousesDetails.length;
    var ObjLength = Object.keys(tabRowData).length;
    var tabRowJson;
    addRowData = [...tabRowData];
    for (var rowId = 0; rowId < this.props.responseData.IndividualDetails.RelationshipDetails.length; rowId++) {
      rowData[rowId] = {};
      for (var tData = 0; tData < ObjLength; tData++) {
        if (tData !== ObjLength - 1) {
          // fieldName = this.props.inputTable.tablelist.tabData[tData]["name"];
          fieldName = addRowData[tData]["name"];
          var keyCodeData = this.props.lang === Config.LANG.AR && addRowData[tData].hasOwnProperty("keyCodeAr") ? addRowData[tData]['keyCodeAr'].split(".") : addRowData[tData]['keyCode'].split(".");
          if (keyCodeData.length === 2 && this.props.responseData.IndividualDetails.RelationshipDetails[rowId].hasOwnProperty(keyCodeData[0])) {
            addRowData[tData][fieldName] = this.props.responseData.IndividualDetails.RelationshipDetails[rowId][keyCodeData[0]][keyCodeData[1]];
          } else {
            if(this.props.lang === Config.LANG.AR && tabRowData[tData].hasOwnProperty('keyCodeAr')) {
              addRowData[tData][fieldName] = this.props.responseData.IndividualDetails.RelationshipDetails[rowId][tabRowData[tData]['keyCodeAr']];
            } else {
              addRowData[tData][fieldName] = this.props.responseData.IndividualDetails.RelationshipDetails[rowId][tabRowData[tData]['keyCode']];
            }
          }
          addRowData[tData]["type"] = "text";
          addRowData[tData]["readOnly"] = true;
        }
        addRowData[ObjLength - 1]["disabled"] = true;
        tabRowJson = { "0": { ...addRowData[0] }, "1": { ...addRowData[1] }, "2": { ...addRowData[2] }, "3": { ...addRowData[3] }, "4": { ...addRowData[4] } };
        rowData[rowId] = { ...tabRowJson }
      }
    }
    this.props.onCallBack(rowData);
    return rowData;
  }

  getPartnerToDataTable() {
    var rowData = [];
    var fieldName;
    var rowLength = this.props.responseData.CompanyDetails.CompanyPartner.length;
    var ObjLength = Object.keys(this.props.inputTable.tablelist.tabData).length;
    var tabRowJson;
    for (var rowId = 0; rowId < rowLength; rowId++) {
      rowData[rowId] = {};
      for (var tData = 0; tData < ObjLength; tData++) {
        if (tData !== 0 && tData !== ObjLength - 1) {
          fieldName = this.props.inputTable.tablelist.tabData[tData]["name"];
          this.props.inputTable.tablelist.tabData[tData][fieldName] = this.props.responseData.CompanyDetails.CompanyPartner[rowId][this.props.inputTable.tablelist.tabData[tData]['keyCode']];
          this.props.inputTable.tablelist.tabData[tData]["type"] = "text";
          this.props.inputTable.tablelist.tabData[tData]["readOnly"] = true;
        }
        this.props.inputTable.tablelist.tabData[ObjLength - 1]["disabled"] = true;
        tabRowJson = { "0": { ...this.props.inputTable.tablelist.tabData[0] }, "1": { ...this.props.inputTable.tablelist.tabData[1] }, "2": { ...this.props.inputTable.tablelist.tabData[2] }, "3": { ...this.props.inputTable.tablelist.tabData[3] }, "4": { ...this.props.inputTable.tablelist.tabData[4] } };
        rowData[rowId] = { ...tabRowJson }
      }
    }
    this.props.onCallBack(rowData);
    return rowData;
  }
  // filterFieldName() {
  //   const form = [];
  //     this.props.element.form.map((formGp, key) => {
  //         formGp.formgroup.input.map((elem, k) => {
  //               if(elem.type !="label") {
  //                   form[elem.name] = "";
  //               }
  //         });
  //     });
  //   return form;
  // }

  componentDidMount() {
  }

  render() {
    var title, editButtonAction = " ";
    if (this.props.tabTitle !== "") {
      title = <Col lg="12" md="6" className="header-align-left" key={"tl-" + this.props.tabTitle}><h4 className="rem15FontSize" key={this.props.tabTitle}>{translateLabel(this.props.tabTitle)}</h4></Col>;
    }
    if(this.props.inputTable.tablelist.title !== "Address" && this.props.isEditTable){
      if (this.props.hasOwnProperty('tablewizardStep') && this.props.tablewizardStep !== "" && this.props.tablewizardStep !== undefined) {
        editButtonAction = <div className="col col-lg-12 col-md-12" style={{ margin: "10px" }}>
          <div className="col-lg-12 col-md-12 col-sm-12 col-12">
            
            <div style={ this.props.lang === Config.LANG.AR ? { width: '100%', textAlign: 'left' } : { width: '100%', textAlign: 'right' }}>
              <button  onClick={() => { this.handleSectionEditClick() }} className="btn-primary"> {translateLabel("EDITBTN")}</button>
            </div>
          </div>
        </div>
      }
    }
    if (this.props.inputTable.viewType === "addRowGrid") { // load Add Row Table View
      if (this.props.viewType === "form" && this.formData.Gender !== "" && this.formData.Gender === "Male") {
        // addRowActionbtn = <div className="col col-lg-12 col-md-12" style={{ marginTop: "10px" }}>
        //   <button onClick={() => this.handleAddRow(this.props.addTable.tablelist.tabData)} type="button" className="btn btn-primary float-right">
        //     {translateLabel('ADDROW')}
        //   </button>
        // </div>
      }
      // if(this.props.tableResponseData[this.props.tabKey].hasOwnProperty(this.props.inputTable.keyCode)) {
      return (
        <div className="container">
          {/* <div className="row table-tab-view" style={{ "padding": "0px" }}>
            <div className={"col col-lg-8"} style={{ "paddingLeft": "0px" }}>
              {title}
            </div>
            <div className={"col col-lg-4"} style={{ "marginBottom": "10px" }}>
              {addRowActionbtn}
            </div>
          </div> */}
          <div> {/*justify-content-md-center*/}
            <div className={"col-lg-12 col-md-12 zero-padding " + this.props.inputTable.panelClass}>{/*  + this.props.inputTable.panelClass} */}
              {/* responsive="lg,md,sm,xs" */}
              <div className="table-responsive table-hover addRowTableStyle dyna-frm-table-view">
                <Table>
                  <thead>
                    <tr>
                      {this.contructRowTableHeader(this.props.inputTable.tablelist.tabHeader)}
                    </tr>
                  </thead>
                  <tbody>
                    {/* <tr> */}
                    {/* {this.contructRowTableData(this.props.inputTable.tablelist.tabData, this)} */}
                    {/* {this.contructRowTableData()} */}
                    {/* </tr> */}
                    {this.constructTableBody()}
                  </tbody>
                </Table>
                <hr style={{marginTop: "-15px"}}></hr>
              </div>
              {/* {this.props.inputTable.tablelist.tabData} */}
            </div>
          </div>
        </div>
      );
      // } else {
      //   return("");
      // }
    } else if (this.props.inputTable.viewType === "defaultGrid") { // load readonly table view
       return (
        // <div>
        <div className="container zero-rpad">
          <div> {/*justify-content-md-center*/}
            {title}
            {editButtonAction}
            <div className={"col col-lg-12 col-md-12 zero-padding " + this.props.inputTable.panelClass}>{/* + this.props.inputTable.panelClass */}
              {/* {this.formData.gender != "" && this.formData.gender == "Male" ?  addRowActionbtn : "" } */}
              <div className="table-responsive table-hover dyna-frm-table-view">
                <Table>
                  <thead>
                    <tr>
                      {this.contructRowTableHeader(this.props.inputTable.tablelist.tabHeader)}
                    </tr>
                  </thead>
                  <tbody>
                    {this.constructDefaultTableBody(this.props.inputTable.tablelist.tabData)}
                  </tbody>
                </Table>
                <hr style={{marginTop: "-15px"}}></hr>
              </div>
            </div>
          </div>
        </div>
      );
    }
  }

  contructRowTableHeader(col) {
    var headerRow = [];
    col.forEach(th => {
      headerRow.push(<th className={(th.class !== "col-md-3") ? th.class : ""} key={th.id}>{translateLabel(th.labelName)}</th>);
    });
    return headerRow;
  }

  constructTableBody() {
    var row;
    var tableRow = [];
    var loadTable;
    var td;
    row = this.state.rows;
    if (this.props.viewType === "view") {
      if (this.props.tableResponseData.hasOwnProperty(this.props.tabKey) && this.props.tableResponseData[this.props.tabKey].hasOwnProperty(this.props.inputTable.keyCode)) {
        loadTable = this.props.tableResponseData[this.props.tabKey][this.props.inputTable.keyCode];
        for (var j = 0; j < Object.keys(loadTable).length; j++) {
          // console.log("row", loadTable[j].SpouseID);
          td = this.readOnlyTableData(loadTable[j], j, this.addRowData);
          tableRow.push(<tr key={"tr_" + j}>{td}</tr>);
        }
      } else {
        td = <td colspan={Object.keys(this.props.inputTable.tablelist.tabHeader).length} align="center">No Records</td>;
        tableRow.push(<tr key={"tr_0"}>{td}</tr>);
      }
    } else {
      // only for default row display create operation
      row.forEach((template, index) => {
        td = this.contructRowTableData(template, index);
        tableRow.push(<tr key={"tr_" + index}>{td}</tr>);
      })
    }
    return tableRow;
  }

  constructDefaultTableBody(rowDtls) {
    var row;
    // var tableRow = [];
    var td;
    var rowLength;
    this.defaultTableData = [];
    let tableRow = this.props.tableResponseData.find((element) => Object.keys(element)[0] === this.props.inputTable.keyCode);
    //constructDefaultTableBody
    // if (this.props.tableResponseData.hasOwnProperty(this.props.tabKey) && this.props.tableResponseData[this.props.tabKey].hasOwnProperty(this.props.inputTable.keyCode)) {
    if (tableRow!== undefined) {
      row =tableRow[this.props.inputTable.keyCode];
      // row = this.props.tableResponseData[this.props.tabKey][this.props.inputTable.keyCode];
      rowLength = Object.keys(row).length;
      if (rowLength) {
        for (let i = 0; i < rowLength; i++) {
          td = this.contructDefaultTableData(i, row[i], rowDtls, this.props.inputTable.keyCode);
          //this.defaultTableData.push(<tr key={i}><td key={i+"-sno"}>{i+1}</td><td key={i+"-s1"}>{row[i][rowDtls["1"]["keyCode"]]}</td><td key={i+"s3"}>{row[i][rowDtls["2"]["keyCode"]]}</td><td key={i+"s4"}>{row[i][rowDtls["3"]["keyCode"]]}</td><td key={i+"s5"}>{row[i][rowDtls["4"]["keyCode"]]}</td><td key={i+"s6"}>{row[i][rowDtls["5"]["keyCode"]]}</td></tr>);
          this.defaultTableData.push(<tr key={i}>{td}</tr>);
        }
        return (this.defaultTableData);
      }
    }
  }

  contructDefaultTableData(rowId, rowData, rowKeyCode, tableKeyCode) {
    var td = [];
    //td.push(<td key={rowId+"-sno"}>{rowId+1}</td>);
    for (let i = 0; i < Object.keys(rowKeyCode).length; i++) {
      // if(rowKeyCode[i]["type"] !== "button") {
          if (this.props.misMatchTableData !== undefined && this.props.misMatchTableData.hasOwnProperty(tableKeyCode) && this.props.misMatchTableData[tableKeyCode] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId].hasOwnProperty(rowKeyCode[i]["keyCode"])) {
            td.push(<td key={rowId + "-" + rowKeyCode[i]["keyCode"]}><label className="rop-highlight form-label">{rowData[rowKeyCode[i]["keyCode"]]}</label></td>)
          } else {
            // let ar = this.props.lang === Config.LANG.AR ? "Ar" : "";
            var keyCodeData = this.props.lang === Config.LANG.AR && rowKeyCode[i].hasOwnProperty("keyCodeAr") ? rowKeyCode[i]["keyCodeAr"].split(".") : rowKeyCode[i]["keyCode"].split(".");
            if (keyCodeData.length === 2 && rowData.hasOwnProperty(keyCodeData[0])) {
              td.push(<td className={(rowKeyCode[i]["class"] !== "col-md-3") ? rowKeyCode[i]["class"] : ""} key={rowId + "-" + rowKeyCode[i]["keyCode"]}>{rowData[[keyCodeData[0]]][keyCodeData[1]]}</td>)
            } else if(keyCodeData.length === 3 && rowData.hasOwnProperty(keyCodeData[0])) {
              td.push(<td className={(rowKeyCode[i]["class"] !== "col-md-3") ? rowKeyCode[i]["class"] : ""} key={rowId+"-"+rowKeyCode[i]["keyCode"]}>{rowData[[keyCodeData[0]]][keyCodeData[1]][keyCodeData[2]]}</td>)
            } else {
              td.push(<td className={(rowKeyCode[i]["class"] !== "col-md-3") ? rowKeyCode[i]["class"] : ""} key={rowId + "-" + rowKeyCode[i]["keyCode"]}>{this.props.lang === Config.LANG.AR && rowKeyCode[i].hasOwnProperty("keyCodeAr") ? rowData[rowKeyCode[i]["keyCodeAr"]] : rowData[rowKeyCode[i]["keyCode"]]}</td>)
            }
          }
    // } else { 
    //   td.push(<td><button onClick={() => this.handleRowTableData(rowData)} type="button" className="btn btn-primary float-right">
    //   {translateLabel(rowKeyCode[i]["value"])}
    // </button></td>)
    // }
    }
    return td;
  }

  readOnlyTableData(row, kcode, tableData) {
    var responseRow = [];
    var tableKeyCode = "SpousesDetails";
    var rowId = kcode;
    if (this.props.misMatchTableData !== undefined && this.props.misMatchTableData.hasOwnProperty(tableKeyCode) && this.props.misMatchTableData[tableKeyCode] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId].hasOwnProperty("FirstName")) {
      responseRow.push(<td key={kcode + "---" + row.FirstName}><label className="rop-highlight form-label">{row["FirstName"]}</label></td>);
    } else {
      responseRow.push(<td key={kcode + "---" + row.FirstName}>{row["FirstName"]}</td>);
    }
    if (this.props.misMatchTableData !== undefined && this.props.misMatchTableData.hasOwnProperty(tableKeyCode) && this.props.misMatchTableData[tableKeyCode] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId].hasOwnProperty("SpouseID")) {
      responseRow.push(<td key={kcode + "---" + row.SpouseID}><label className="rop-highlight form-label">{row["SpouseID"]}</label></td>);
    } else {
      responseRow.push(<td key={kcode + "---" + row.SpouseID}>{row["SpouseID"]}</td>);
    }
    if (this.props.misMatchTableData !== undefined && this.props.misMatchTableData.hasOwnProperty(tableKeyCode) && this.props.misMatchTableData[tableKeyCode] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId] !== undefined && this.props.misMatchTableData[tableKeyCode][rowId].hasOwnProperty("GenderNameEnglish")) {
      responseRow.push(<td key={kcode + "---" + row.GenderNameEnglish}><label className="rop-highlight form-label">{row["GenderNameEnglish"]}</label></td>);
    } else {
      responseRow.push(<td key={kcode + "---" + row.GenderNameEnglish}>{row["GenderNameEnglish"]}</td>);
    }
    return responseRow;
  }

  contructRowTableData(template, index) {
    var element;
    var responseRow = [];
    for (var i = 0; i < Object.keys(template).length; i++) {
      element = this.contructRowTable(index, template[i], i);
      responseRow.push(element);
    }
    // }
    return responseRow;
  }

  bindDynamicTableData(rowId, template) {
    var element;
    var td = [];
    for (var i = 0; i < Object.keys(template).length; i++) {
      element = this.contructRowTable(rowId, template[i], i);
      td.push(element);
    }
    return td;
  }

  contructRowTable(rowId, template, key) {
    if (template.type === "text" || template.type === "password" || template.type === "email" || template.type === "number") {
      return (
        <td key={template.id + '-td' + rowId}>
          <Form.Control
            id={template.id}
            name={template.name}
            type={template.type}
            placeholder={translateLabel(template.placeholder)}
            min="0"
            readOnly={template.readOnly}
            value={this.state.rows[rowId][key][template.name] ? this.state.rows[rowId][key][template.name] : this.state.rows[rowId].name}
            required={template.required}
            onChange={(e) => this.handleChange(e, rowId, key)}
          />
        </td>
      );
    }

    if (template.type === "select") {
      return (
        <td key={template.id + '-td' + rowId}>
          <select name={template.name} id={template.id} value={this.state.rows[rowId].name} onChange={(e) => this.handleChange(e, rowId, key)} className="form-control">
            <option key='0' value=''> Select any {template.label}</option>
            {template.options.map((data, index) => (
              <option key={index + 1} value={data.value}>{data.text}</option>
            ))}
          </select>
        </td>
      );
    }

    if (template.type === "label") {
      var sn = rowId + 1
      return (<td key={template.id + '-td' + rowId}>
        <Form.Group controlId={template.id}>
          <Form.Label>{sn}</Form.Label>
        </Form.Group>
      </td>
      );
    }
    if (template.type === "submit" || template.type === "button") {
      var dblBtn;
      if (template.disabled) {
        dblBtn = rowId === 0 ? "disabled" : template.disabled;
      } else {
        dblBtn = rowId === 0 ? "disabled" : "";
      }
      return (
        <td key={template.id + '-td' + rowId} style={{ textAlign: "center" }}>
          {/* <Form.Group controlId={template.id}> */}
          {dblBtn ? <BlockRoundedIcon className="db-delete-icon" /> : <DeleteForeverRoundedIcon className="delete-icon handCursor" onClick={() => this.handleDeleteRow(rowId)} />}
          {/* <Button variant="danger" type={template.type} disabled={dblBtn}  onClick={() => this.handleDeleteRow(rowId)}>{translateLabel(template.value)}</Button> */}
          {/* </Form.Group> */}
        </td>
      );
    }
  }
}

const mapStateToProps = state => ({
  ln1A_app_details: state.ln1A_app_details,
});

const mapDispatchToProps = {
  setLN1A_App
};

export default withNamespaces()(connect(mapStateToProps, mapDispatchToProps)(RowTable));
