import React, { Component } from "react";
import { Form, Row, Col, Button } from "react-bootstrap";
import { withRouter } from "react-router-dom";
import { ValidatorForm } from "react-form-validator-core";
import Section from "./section";
import RowTable from "./table";
import UtilsService from "./services/shared/utils.service";
import DocumentList from "./fileuploads/DocumentList";
import SelectedDocumentList from './fileuploads/SelectedDocumentList'
import Acknowledgment from "./acknowledgment";
import { withNamespaces } from "react-i18next";
import translateLabel from "./translation";
import Tab from "react-bootstrap/Tab";
import Tabs from "react-bootstrap/Tabs";
import "bootstrap/dist/css/bootstrap.min.css";
import "react-stepzilla/src/css/main.css";
import './assets/css/moh-style.css';
import "./assets/css/icon-style.css";
import './assets/css/App.css';
import "./assets/plugin/font-awesome/css/font-awesome.min.css";
// import Tooltip from '@material-ui/core/Tooltip';

class DynamicFormBuilder extends Component {
  constructor(props) {
    super(props);
    this.tableArray = [];
    this.formArray = {};
    this.keyLoadObj = {};
    this.tabSequence = [];
    this.tabSeqCheck = [];
    this.visitedTabs = [];
    this.tabCount = 0;
    this.Popup = false;
    this.tabSaveBtn = true;
    this.loopcheck = 0;
    this.condcheck = true;
    this.previousTab = this.props.previewEditTab !== undefined && this.props.previewEditTab !== "" ? Number(this.props.previewEditTab) : "0";
    this.sectionActionBtn = this.props.hasOwnProperty("viewAction")
      ? this.props.viewAction
      : false;

    if (this.props.viewType === "form") {
      this.fetchResponseDataValue();
      const fields = this.filterFieldName();
      this.state = {
        ...fields,
        files: [],
        uploadDocumentDetails: [],
        uploadDocumentDetailsLoaded: false,
        tabEnable: true,
        Popup: false,
        SeqPopup: false,
        tabActive: this.props.previewEditTab !== undefined && this.props.previewEditTab !== "" ? Number(this.props.previewEditTab) : 0
      };
    } else if (this.props.viewType === "view") {
      this.fetchResponseDataValue();
      const fields = this.filterFieldName();
      this.state = {
        ...fields,
        files: [],
        acknowledgmentValue: false,
      };
    } else {
      this.state = {};
    }
    this.checkValue = [];
    this.actionBtn = [];
    this.handleChange = this.handleChange.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleActionBtnClick = this.handleActionBtnClick.bind(this);
    this.onAcknowledgeClick = this.onAcknowledgeClick.bind(this);
    this.handleFetchTableData = this.handleFetchTableData.bind(this);
    this.handleFormError = this.handleFormError.bind(this);
    this.callBackJsonObject = this.callBackJsonObject.bind(this);
    this.utils = new UtilsService();
    this.tabOrderSequence = this.tabOrderSequence.bind(this);
  }

  handleChange(event) {
    if (event.target.type === "checkbox") {
      if (event.target.checked || !event.target.checked) {

        this.props.element.form.forEach(function(frm) {
        
          frm.formgroup.input.forEach(function (val) {
            if (event.target.name === val.name) {
              this.checkValue[val.name] = [];
              val.options.forEach(
                function (dt) {
                  if (dt.value === event.target.value) {
                    dt.checked = event.target.checked;
                  }
                }
              );
              val.options.forEach(
                function (vl) {
                  if (vl.checked) {
                    this.checkValue[val.name].push(vl.value);
                  }
                }.bind(this)
              );
            }
          }.bind(this)
        );
      }.bind(this)
      );
      }
      this.setState({ ...this.checkValue });
    } else {
      this.setState({ [event.target.name]: event.target.value });
    }
    this.props.onAppFormChange(event);
  }

  handleKeyPress(element) {
    this.keyLoadObj[element.name] = element.value;
  }

  handleBtnClick(event) {
    //console.log("Form btn Click :"+ JSON.stringify(this.state));
    this.props.onAppBtnClick(this.state, event, this.props);
    event.preventDefault();
  }

  handleSubmit(event) {
    if (Object.keys(this.keyLoadObj).length > 0) {
      this.setState({ ...this.state, ...this.keyLoadObj });
    }
    this.props.onAppFormSubmit(this.state, this.table, event);
    event.preventDefault();
  }

  handleFormError(errorMessages) {
    if (this.tabSeqCheck.length > 0 && this.tabSequence.length > 0 && this.tabSeqCheck.length < this.tabSequence.length) {
      let dataindex = this.tabSeqCheck[this.tabSeqCheck.length - 1];
      let keyindex = this.tabSeqCheck.indexOf(dataindex);
      let data = this.tabSequence[keyindex + 1];
      this.setState({
        tabActive: data,
        Popup: true,
        SeqPopup: false
      });
      this.previousTab = data;
    }
    else if (this.tabSeqCheck.length === 0 && this.tabSequence.length > 0) {
      let data = this.tabSequence[0];
      this.setState({
        tabActive: data,
        Popup: true,
        SeqPopup: false
      });
      this.previousTab = data;
    }
  } ß

  handleActionBtnClick(val, tabIndex) {
    //window.scrollTo(0, 0);
    this.props.handleFormSection(val, tabIndex);
  }

  onAcknowledgeClick(val) {
    this.setState({ acknowledgmentValue: val });
  }

  /* static getDerivedStateFromProps(props, state) {
           return {key: props.value };
   } */

  componentDidMount() {
    //this.formResponseDataBind();
  }

  tabOrderSequence(key) {
    const formValue = this.props.element;
    let tabid = "form-tab-tab-" + key;
    document.getElementById(tabid).style = "outline : none";
    let tabvallength = this.tabSequence.length;
    let keycheck = Number(this.previousTab) + 1;
    if (this.condcheck === false) {
      this.condcheck = true;
    }
    if (key <= keycheck) {
      if (tabvallength > 0) {
        for (let i = 0; i < tabvallength; i++) {
          let formcheck = 0;
          formValue.form.map(function (frmSection, index) {
            if (index <= key && index === this.tabSequence[i]) {
              formcheck = formcheck + 1;
              let iteratecheck = 0;
              let iteratedvalue = 0;
              frmSection.formgroup.input.map(function (value) {
                if (value.type !== 'label' && value.validator !== undefined && Object.keys(value.validator).length > 0 && this.condcheck === true) {
                  iteratecheck = iteratecheck + 1;
                  let numval = document.getElementById(value.id).value;
                  if (value.type === 'select') {
                    if (numval !== "") {
                      iteratedvalue = iteratedvalue + 1;
                    }
                  } else if (value.type === 'text') {
                    if (Object.values(value.validator.rules).indexOf('isNumber') > -1) {
                      // if((Object.values(value.validator.rules).indexOf('maxStringLength:8')) > -1 && (Object.values(value.validator.rules).indexOf('minStringLength:8')>-1)) {
                      //   if(numval.length === 8) {
                      //     iteratedvalue = iteratedvalue +1;
                      //   }
                      //} 
                      let maxarrval = value.validator.rules.find(a => a.includes("maxStringLength"));
                      let minarrval = value.validator.rules.find(a => a.includes("minStringLength"));
                      let maxval = maxarrval !== undefined && maxarrval.length > 0 ? maxarrval.split(":") : [];
                      let minval = minarrval !== undefined && minarrval.length > 0 ? minarrval.split(":") : [];
                      if (maxval.length > 0 && minval.length > 0) {
                        if (numval.length <= Number(maxval[1]) && numval.length >= Number(minval[1])) {
                          iteratedvalue = iteratedvalue + 1;
                        }
                      } else if (numval !== "") {
                        iteratedvalue = iteratedvalue + 1;
                      }
                    } else if (Object.values(value.validator.rules).indexOf('required') > -1) {
                      if (numval !== "") {
                        iteratedvalue = iteratedvalue + 1;
                      }
                    }
                  } else if (value.type === "textarea") {
                    if (Object.values(value.validator.rules).indexOf('required') > -1) {
                      if (numval !== "") {
                        iteratedvalue = iteratedvalue + 1;
                      }
                    }
                  } else if (value.type === 'email') {
                    if (Object.values(value.validator.rules).indexOf('isEmail') > -1) {
                      if (numval !== "") {
                        iteratedvalue = iteratedvalue + 1;
                      }
                    }
                  } else if (value.type === 'checkbox' || value.type === "radio") {
                    if (Object.values(value.validator.rules).indexOf('required') > -1) {
                      if (document.getElementById(value.id).checked === true) {
                        iteratedvalue = iteratedvalue + 1;
                      }
                    }
                  } else if (value.type === 'datepicker' || value.type === "timepicker") {
                    if (numval !== "") {
                      iteratedvalue = iteratedvalue + 1;
                    }
                  }
                  if (iteratecheck === iteratedvalue) {
                    this.condcheck = true;
                    this.loopcheck = this.loopcheck + 1;
                    if (!this.tabSeqCheck.includes(this.tabSequence[i])) {
                      this.tabSeqCheck.push(this.tabSequence[i])
                    }
                    if (!this.visitedTabs.includes(this.previousTab)) {
                      this.visitedTabs.push(this.previousTab);
                    }
                    if (!this.visitedTabs.includes(key)) {
                      this.visitedTabs.push(key);
                    }
                    this.setState({
                      tabActive: key,
                      Popup: false,
                      SeqPopup: false
                    });
                    this.previousTab = key;
                  } else if (iteratecheck !== iteratedvalue) {
                    this.condcheck = false;
                    var index = this.visitedTabs.indexOf(key);
                    if (index !== -1) {
                      this.visitedTabs.splice(index, 1);
                    }
                    this.setState({
                      tabActive: this.tabSequence[i],
                      SeqPopup: false
                    });
                    if (Number(key) === Number(this.tabSequence[i])) {
                      this.setState({
                        Popup: false
                      });
                    } else {
                      this.setState({
                        Popup: true
                      });
                    }
                    this.previousTab = this.tabSequence[i] + "";
                  }
                }
              }.bind(this))
            }
            else if (this.condcheck && index <= key && index < this.tabSequence[i]) {
              if (!this.visitedTabs.includes(this.previousTab)) {
                this.visitedTabs.push(this.previousTab);
              }
              this.setState({
                tabActive: key,
                Popup: false,
                SeqPopup: false
              });
              this.previousTab = key;
              if (!this.visitedTabs.includes(key)) {
                this.visitedTabs.push(key);
              }
            }
          }.bind(this))
        }
      } else {
        if (!this.visitedTabs.includes(this.previousTab)) {
          this.visitedTabs.push(this.previousTab);
        }
        this.setState({
          tabActive: key,
          Popup: false,
          SeqPopup: false
        });
        this.previousTab = key;
        if (!this.visitedTabs.includes(key)) {
          this.visitedTabs.push(key);
        }
      }
    } else if (key > keycheck) {
      if (this.visitedTabs.length === 0) {
        this.setState({
          tabActive: this.previousTab,
          Popup: false,
          SeqPopup: true
        });
      }
      else if (this.tabSeqCheck.length === tabvallength && key <= this.visitedTabs.length) {
        this.setState({
          tabActive: key,
          Popup: false,
          SeqPopup: false
        });
        this.previousTab = key;
        document.getElementById(tabid).style = "outline : none";
      } else if (key > this.visitedTabs.length) {
        this.setState({
          Popup: false,
          SeqPopup: true
        });

      }
    }
  }

  handleFetchTableData(tableRow) {
    var table = [];
    var formData = this.state;
    tableRow.forEach(
      function (rowData, rowKey) {
        table[rowKey] = { id: rowKey + "tbl", type: "label" };
        for (let i = 1; i < Object.keys(rowData).length - 1; i++) {
          table[rowKey][rowData[i]["name"]] = rowData[i][rowData[i]["name"]];
        }
      }
    );
    this.setState({
      ...formData,
      gridData: [...table],
    });
  }

  filterFieldName() {
    //console.log("this.props.lang ", this.props.lang);
    const form = [];
    this.props.element.form.forEach(
      function (formGp, key) {
        formGp.formgroup.input.forEach(
          function (elem, k) {
            //form[elem.name] = elem.hasOwnProperty("keyCode") ? this.bindFormField(elem.keyCode) : "";
            if (this.props.lang === this.props.langCheckValue && elem.hasOwnProperty("keyCodeAr")) {
              form[elem.name] = elem.hasOwnProperty("keyCodeAr")
                ? this.bindFormField(elem.keyCodeAr)
                : "";
            } else {
              form[elem.name] = elem.hasOwnProperty("keyCode")
                ? this.bindFormField(elem.keyCode)
                : "";
            }
          }.bind(this)
        );
      }.bind(this)
    );
    return form;
  }

  generateActionBtn(formElement) {
    if (formElement.button && Object.keys(formElement.button).length) {
      this.actionBtn = [];
      formElement.button.forEach(
        function (btn, index) {
          if (btn.type === "submit" || btn.type === "button") {
            var button;
            if (btn.type === "button") {
              button = (
                <Button
                  className = "formbtn-primary"
                  variant="formbtn-primary"
                  type={btn.type}
                  name={btn.name}
                  style={{ display: "flex" }}
                  onClick={this.handleBtnClick}
                >
                  {" "}
                  {translateLabel(btn.value)}
                </Button>
              );
            } else {
              if (
                this.state.acknowledgmentValue === true &&
                this.props.isAcknowldege === true
              ) {
                button = (
                  <Button className = "formbtn-primary"
                  variant="formbtn-primary" style={this.props.lang === this.props.langCheckValue ? { float: "left" } : { float: "right" }} type={btn.type}>
                    {translateLabel(btn.value)}
                  </Button>
                );
              } else if (this.props.isAcknowldege === true) {
                button = (
                  <Button
                    style={{ display: "none" }}
                    className = "formbtn-primary"
                    variant="formbtn-primary"
                    type={btn.type}
                  >
                    {translateLabel(btn.value)}
                  </Button>
                );
              } else {
                button = (
                  <Button className = "formbtn-primary"
                  variant="formbtn-primary" type={btn.type} style={this.props.lang === this.props.langCheckValue ? { float: "left" } : { float: "right" }}>
                    {this.props.onButtonLable === true ? translateLabel("Proceed to preview") : translateLabel(btn.value)}
                  </Button>
                );
              }
            }
            this.actionBtn.push(
              <div key={index+1}  className={"col-6 " + btn.class}>
                <Form.Group controlId={btn.id}>{button}</Form.Group>
              </div>
            );
          }
        }.bind(this)
      );
    }
  }

  bindFormField(code) {
    var res;
    // console.log("formArray", this.formArray);
    if (Object.keys(this.formArray).length) {
      res = this.formArray[code];
    } else {
      res = "";
    }
    return res;
  }

  fetchResponseDataValue() {
    if (this.props.hasOwnProperty("responseData")) {
      var response = this.props.responseData;
      if (Object.keys(response).length) {
        Object.keys(response).forEach(function (key) {
          if (typeof response[key] === "object") {
            //if object
            this.callBackJsonObject(response[key]);
          } else {
            this.formArray[key] = response[key];
          }
        }, this);
      }
    }
    //this.props.tableViewData(this.tableArray);
  }

  callBackJsonObject(response) {
    Object.keys(response).forEach(function (key) {
      if (typeof response[key] === "object" && response[key] !== null) {
        // isobject
        if (Array.isArray(response[key])) {
          //isArray
          this.tableArray.push({ [key]: { ...response[key] } });
        } else {
          this.callBackJsonObject(response[key]);
        }
      } else {
        //parent keys
        this.formArray[key] = response[key];
      }
    }, this);
  }

  render() {
    const formElement = this.props.element;
    let random =  Math.random();
    let documentGrid;
    if (this.props.documentList !== undefined) {
      documentGrid = (
        <div className="container">
          <div className="row">
            <div class="header-align-left col-lg-12 col-md-6">
              <h4>Uploaded Documents</h4>
            </div>
            <div className={"col col-lg-12 col-md-12 panel-theme-bg"}>
              <div className={"col col-lg-12 sectionContainer"}>
                {this.props.documentList}
              </div>
            </div>
          </div>
        </div>
      );
    }
    //var isAgree;
    // Option area
    // if(formElement.notes && formElement.notes !=="") {
    //     var isAgree =  <div className="col col-lg-12 mt20"> <Form.Group controlId="isAgree-container">
    //     <div className="col-lg-1"><Form.Label><span className='asterisk'>*</span></Form.Label></div>
    //         <div key="div-isAgree" className="col-lg-11">
    //             <Form.Check
    //                 type="checkbox"
    //                 name="isAgree"
    //                 label={formElement.notes}
    //                 value="test"
    //                 checked="false"
    //                 id="isAgreeKey"
    //                 onChange={this.handleChange}
    //             />
    //         </div>
    //         </Form.Group></div>
    // }
    this.generateActionBtn(formElement);
    var showAddRowGrid = "";
    if (!this.props.hasOwnProperty("tabView") && formElement.form.length === 1 && formElement.hasOwnProperty("table") && Object.keys("table").length) {
      showAddRowGrid = formElement.table.map(
        function (table, index) {
          if (Object.keys(this.props.responseData).length) {
            return (
              <RowTable
                lang={this.props.i18n.language}
                ServiceSubID={this.props.ServiceSubID}
                key={index+random +1 }
                id={index+random +1}
                tabKey={index}
                inputTable={table}
                addTable={table}
                tabTitle={table.title}
                viewType={this.props.viewType}
                onCallBack={this.handleFetchTableData}
                stateVal={this.state}
                responseData={this.props.responseData}
                misMatchTableData={this.props.misMatchTableData}
                tableResponseData={this.tableArray}
              />
            );
          }
        }.bind(this)
      );
    }
    if (this.props.viewType === "form") {
      // form
      // form-list - col-lg-12
      return (
        <div className="col-lg-12 zero-padding">
          <Row className="justify-content-md-center dyna-cmp">
            {formElement.pagetitle !== "" ? (
              <Col className="dynaFrmTitle zero-padding" lg="12" md="12">
                <h4
                  key={formElement.pagetitle + "-hd"}
                  dir={this.props.labelDirectionStyle}
                  className="wizard-form-title rem15FontSize"
                >
                  {translateLabel(formElement.pagetitle)}
                </h4>
              </Col>
            ) : (
                ""
              )}
            {/* <hr /> */}
            <ValidatorForm ref="form" onSubmit={this.handleSubmit} onError={this.handleFormError}>
              {this.state.Popup ?
                <div className="alert dpflex" role="alert">
                  <span className='asterisk'>{translateLabel("PLS_FILL_REQ_VAL_TO_PROCEED")}</span>
                </div>
                : this.state.SeqPopup ? <div className="alert dpflex" role="alert">
                  <span className='asterisk'>{translateLabel("Please View the tab one by one")}</span>
                </div> : ""}
              {(formElement.form.length > 1 || (this.props.hasOwnProperty("tabView") && this.props.tabView === "true")) ? (
                <Tabs defaultActiveKey={0} activeKey={this.state.tabActive} id="form-tab" onSelect={this.tabOrderSequence}>
                  {formElement.form.map((frmSection, index) => {
                    frmSection.formgroup.input.forEach((value, key) => {
                      if (value.type !== 'label' && value.validator !== undefined && Object.keys(value.validator).length > 0) {
                        if (!this.tabSequence.includes(index)) {
                          this.tabSequence.push(index)
                        }
                      }
                    })
                    return (
                      // <Tooltip title="Add" aria-label="add">
                      <Tab
                        className="formTabClass"
                        key={index+1}
                        eventKey={index}
                        aria-labelledby={translateLabel(frmSection.formgroup.title)}
                        title={translateLabel(frmSection.formgroup.title)}
                      >

                        <Section
                          key={index}
                          lang={this.props.lang}
                          langCheckValue={this.props.langCheckValue}
                          config={this.props.labelDiretionStylesList}
                          inputElement={frmSection}
                          frmTitle={translateLabel(frmSection.title)}
                          stateVal={this.state}
                          onChange={this.handleChange}
                          onKeyLoad={this.handleKeyPress}
                        />
                      </Tab>
                      // </Tooltip>
                    );
                  })}
                  {formElement.hasOwnProperty("table") &&
                    Object.keys("table").length
                    ? formElement.table.map(
                      function (table, index) {
                        if (Object.keys(this.props.responseData).length) {
                          return (
                            <Tab
                              className="formTabClass"
                              key={formElement.form.length + index}
                              eventKey={formElement.form.length + index}
                              title={translateLabel(table.tablelist.title)}
                            >
                              <RowTable
                                lang={this.props.i18n.language}
                                ServiceSubID={this.props.ServiceSubID}
                                key={formElement.form.length + index + "-tb"}
                                tabKey={index}
                                inputTable={table}
                                addTable={table}
                                tabTitle={table.title}
                                viewType={this.props.viewType}
                                onCallBack={this.handleFetchTableData}
                                stateVal={this.state}
                                responseData={this.props.responseData}
                                misMatchTableData={
                                  this.props.misMatchTableData
                                }
                                tableResponseData={this.tableArray}
                              />
                            </Tab>
                          );
                        }
                      }.bind(this)
                    )
                    : ""}
                  {this.props.externalComponent !== undefined && this.props.externalComponent !== "" ?
                    this.props.externalComponent.map(function (element, index) {
                      return (
                        <Tab
                          className="formTabClass"
                          // key={formElement.form.length + formElement.table.length + index}
                          // eventKey={formElement.form.length + formElement.table.length + index}
                          key={formElement.hasOwnProperty("table") ? formElement.form.length + formElement.table.length + index : formElement.form.length + index}
                          eventKey={formElement.hasOwnProperty("table") ? formElement.form.length + formElement.table.length + index : formElement.form.length + index}
                          title={translateLabel(element.title)}
                        >
                          {element.externalComponent}
                        </Tab>
                      )
                    })
                    : ("")}
                </Tabs>
              ) : (
                  // <h4>{translateLabel(frmSection.formgroup.title)}</h4>
                  formElement.form.map((frmSection, index) => {
                    return (
                      <div key={index + "-title"}>
                        {frmSection.formgroup.title !== "" ? (
                          <div className={this.props.lang === this.props.langCheckValue ? "zero-rpad col-lg-12 col-md-12" : "zero-padding col-lg-12 col-md-12"}>
                            <h4
                              dir={this.props.labelDirectionStyle}
                              className="wizard-form-title"
                            >
                              {translateLabel(frmSection.formgroup.title)}
                            </h4>
                          </div>
                        ) : (
                            ""
                          )}
                        <Section
                          key={index}
                          lang={this.props.lang}
                          langCheckValue={this.props.langCheckValue}
                          config={this.props.labelDiretionStylesList}
                          inputElement={frmSection}
                          frmTitle={translateLabel(frmSection.title)}
                          stateVal={this.state}
                          onChange={this.handleChange}
                        />
                      </div>
                    );
                  })
                )}
              {showAddRowGrid}
              {/* {isAgree} */}
              {documentGrid}
              <div className={this.props.payeePopUp ? "col col-lg-12 zero-lpad btnstyle" : "col col-lg-12 zero-lpad"}>
                <div className="justify-content-md-center row">
                  {this.actionBtn}
                </div>
              </div>
            </ValidatorForm>
          </Row>
        </div>
      );
    } else if (this.props.viewType === "view") {
      //form-list
      return (
        <div className="container nopaddingContainer dyna-cmp">
          <Row className="justify-content-md-center">
            {/* <Spinner animation="border" /> */}
            {formElement.pagetitle !== "" ? (
              <Col  className="dynaFrmTitle zero-padding" lg="12" md="12">
                <h4
                  dir={this.props.labelDirectionStyle}
                  key={formElement.pagetitle + "-hd"}
                  className="wizard-form-title"
                >
                  {translateLabel(formElement.pagetitle)}
                </h4>
              </Col>
            ) : (
                ""
              )}
            {/* <div className="dynaFrmContent"> */}
            <form ref="form" onSubmit={this.handleSubmit}>
            
          
                  {formElement.form.length > 1 ? (
                    <Tabs defaultActiveKey={0} id="form-tab">
                      {formElement.form.map((frmSection, index) => {
                        return (
                          <Tab
                            className="formTabClass"
                            eventKey={index}
                            key={index + 1}
                            title={translateLabel(frmSection.formgroup.title)}
                          >
                            <Section
                              key={index}
                              lang={this.props.lang}
                              langCheckValue={this.props.langCheckValue}
                              config={this.props.labelDiretionStylesList}
                              inputElement={frmSection}
                              matchElement={this.props.misMatchData}
                              frmTitle={translateLabel(frmSection.title)}
                              stateVal={this.state}
                              onSectionActionClick={this.handleActionBtnClick}
                              sectionButton={this.sectionActionBtn}
                              onChange={this.handleChange}
                            />
                          </Tab>
                        );
                       })
                      }
                      {formElement.hasOwnProperty("table") &&
                        Object.keys("table").length
                        ? formElement.table.map(
                          function (table, index) {
                            if (Object.keys(this.props.responseData).length) {
                              return (
                                <Tab
                                  className="formTabClass"
                                  key={formElement.form.length + index}
                                  eventKey={formElement.form.length + index}
                                  title={translateLabel(table.tablelist.title)}
                                >
                                  <RowTable
                                    lang={this.props.i18n.language}
                                    ServiceSubID={this.props.ServiceSubID}
                                    key={formElement.form.length + index + "-tb"}
                                    tabKey={index}
                                    inputTable={table}
                                    addTable={table}
                                    tabTitle={table.title}
                                    viewType={this.props.viewType}
                                    onCallBack={this.handleFetchTableData}
                                    stateVal={this.state}
                                    responseData={this.props.responseData}
                                    misMatchTableData={
                                      this.props.misMatchTableData
                                    }
                                    tableResponseData={this.tableArray}
                                    onSectionActionClick={this.handleActionBtnClick}
                                    tablewizardStep={this.props.tablewizardStep !== undefined ? this.props.tablewizardStep : table.tablelist.editTabIndex}
                                    isEditTable={this.props.isEditTable}
                                  />
                                </Tab>
                              );
                            }
                          }.bind(this)
                        )
                        : ""
                      }
                      {this.props.externalComponent !== undefined && this.props.externalComponent !== "" ?
                        this.props.externalComponent.map(function (element, index) {
                          return (
                            <Tab
                              className="formTabClass"
                              key={formElement.hasOwnProperty("table") ? formElement.form.length + formElement.table.length + index : formElement.form.length + index}
                              eventKey={formElement.hasOwnProperty("table") ? formElement.form.length + formElement.table.length + index : formElement.form.length + index}
                              title={translateLabel(element.title)}
                            >
                              {element.externalComponent}
                            </Tab>
                          )
                        })
                        : ("")
                      }
                    </Tabs>
                  ) : (
                      formElement.form.map((frmSection, index) => {
                        return (
                          <div key={index + "-title"}>
                            {frmSection.formgroup.title !== "" ? (
                              <div className="col-lg-12 col-md-12">
                                <h4
                                  dir={this.props.labelDirectionStyle}
                                  className={this.props.lang === this.props.langCheckValue ? "wizard-form-title" : "zero-padding wizard-form-title"}>
                                  {translateLabel(frmSection.formgroup.title)}
                                </h4>
                              </div>
                            ) : (
                                ""
                              )}
                            <Section
                              key={index+1}
                              lang={this.props.lang}
                              langCheckValue={this.props.langCheckValue}
                              config={this.props.labelDiretionStylesList}
                              inputElement={frmSection}
                              matchElement={this.props.misMatchData}
                              frmTitle={translateLabel(frmSection.title)}
                              stateVal={this.state}
                              onSectionActionClick={this.handleActionBtnClick}
                              sectionButton={this.sectionActionBtn}
                              onChange={this.handleChange}
                            />
                          </div>
                        );
                      })


                    )
                 }
                 {showAddRowGrid}
                 {formElement.form.length < 1 && this.props.externalComponent !== undefined && this.props.externalComponent !== "" ?
                    this.props.externalComponent.map(function (element, index) {
                      return (
                        <div key={index+1}>
                          <h4 dir={this.props.labelDirectionStyle}>{element.title}</h4>
                          {element.externalComponent}
                        </div>
                      )
                    }.bind(this))
                    : ("")
                 }
                 {(() => {
                    if (
                      this.props.isUploadPresent &&
                      documentGrid === undefined
                    ) {
                      return (
                        <DocumentList
                          lang={this.props.lang}
                          storeData={this.props.storeData}
                          onSectionActionClick={this.handleActionBtnClick}
                        />
                      );
                    } else {
                      return documentGrid;
                    }
                  })()
                 }
                 {(() => {
                      if (
                        this.props.isSelectedDocumentPresent &&
                        documentGrid === undefined
                      ) {
                        return (
                          <SelectedDocumentList
                            storeData={this.props.storeData}
                            onSectionActionClick={this.handleActionBtnClick}
                          />
                        );
                      } else {
                        return documentGrid;
                      }
                   })()
                 }
                  {(() => {
                      if (this.props.isAcknowldege) {
                        return (
                          <div className="container">
                            <Acknowledgment
                              onAcknowledgeClick={this.onAcknowledgeClick}
                            />
                          </div>
                        );
                      }
                    })()
                  }
                  <div className="col-12 col-lg-12">
                      <div className="justify-content-md-center row">
                        {this.actionBtn}
                      </div>
                  </div>
            </form>
            {/* </div> */}
          </Row>
        </div>
      );
    }
  }
}
export default withNamespaces()(withRouter(DynamicFormBuilder));