import React, { Component } from 'react';
import Portal from './Portal';
import Button from './Button'
import Form, { AjvError, ErrorListProps, ISubmitEvent, UiSchema, Widget } from "@rjsf/core"
import * as ModalFormStyle from './ModalForm.style'
import Modal from 'react-bootstrap/Modal'
import IfTrueThenRender from './IfTrueThenRender'
import loadEnvyFormHandler from './loadEnvyFormHandler'

class ModalForm extends Component<Props, State> {

  formName: string
  localStorageName: string
  schema: any;

  constructor(props: Props) {
    super(props)

    // hydrated later in this.componentDidMount
    this.schema = this.props.formBuilder.schema

    this.formName = props.formName
    this.localStorageName = `${this.formName}FormData`
    this.state = {
      ModalIsOpened: false,
      regions: [],
      formMeta: {
        formName: undefined,
        formCtaSource: undefined,
        ref: undefined,
      },
      formIsSent: localStorage.getItem(this.localStorageName) ? true : false,
      formJustSent: false,
      formIsSenging: false,
    }

    this.showFormHandler = this.showFormHandler.bind(this)
    this.closeModalHandler = this.closeModalHandler.bind(this)
    this.handleFormReset = this.handleFormReset.bind(this)
  }

  async componentDidMount() {
    // load https://cdn.envybox.io/widget/cbk.js?wcb_code=0df1a94d9fb1d6811a76c0a155bbd76a script
    // loadEnvyFormHandler()

    // fetch data for region field
    const regions = await fetch(`/api/form/regions`, {
      method: 'POST',
      headers: {
        "Content-Type": "application/json",
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
      },
    }).then(response => {
      try {
        return response.json()
      } catch (e) {
        console.log(response);
        console.error(e);
      }
    })
      .catch(console.error)

    // append the data to region field
    this.schema.properties.region.enum = this.schema.properties.region.enum.concat(regions)

    this.setState({ regions: [...regions] })
  }

  showFormHandler(event: any) {
    const target = event.target

    if (target.hasAttribute('data-target-modal') && target.getAttribute('data-target-modal') === this.formName) {
      // open modal
      this.setState({ ModalIsOpened: !this.state.ModalIsOpened })
      // save data about a source
      this.setState({
        formMeta: {
          formName: target.getAttribute('data-target-modal'),
          formCtaSource: target.getAttribute('data-cta-src'),
          ref: encodeURIComponent(location.href),
        }
      })
    }
  }

  closeModalHandler() {
    this.setState({ ModalIsOpened: !this.state.ModalIsOpened })
  }

  handleFormSubmit(form: formDataType) {
    const { formData } = form;
    // console.log(formData);

    // console.log("onSubmit", formData, this);
    const body = JSON.stringify({ ...formData, ...this.state.formMeta })

    this.setState({ formIsSenging: true });

    // Отправка данных минуя бекенд
    const leadRegion = formData.region
    const leadDebt = formData.debt
    const leadName = formData.name
    const leadPhone = formData.phone
    const leadEmail = '';
    const leadComment = 'заявка с pravotop.ru\n' + 'Регион (форма) : ' + leadRegion + '\n';

    // Обязательное поле sendCrmLead(id, ...):
    // envyWBK.sendCrmLead(29349, {
    // возможно не нужно
    // inbox_type_id: 846140,
    // @ts-ignore
    WBK.sendCrmLead(29349, {
      inbox_type_id: '',
      name: leadName + ' Долг ' + leadDebt,
      comment: leadComment,
      phone: leadPhone,
      email: leadEmail
    }, (response: {
      Success: boolean,
      Data: {
        lead_id: number
      }
      // когда форма отправлена в CRM успешно
    }) => {
      // console.log(response);
      if (response.Success) {
        localStorage.setItem(this.localStorageName, body)
        this.setState({ formIsSent: true, formJustSent: true })
        this.setState({ formIsSenging: false });
      } else {
        this.setState({ formIsSenging: false });
        throw new Error(`WBK.sendCrmLead не смог отправить форму`)
      }

    });

    // Отправка данных через бекенд. На данный момент неправильный API-key.
    // Вместо этого действия используется WBK.sendCrmLead
    // fetch(`/api/form/${this.formName}/store`, {
    //   method: 'POST',
    //   body,
    //   headers: {
    //     "Content-Type": "application/json",
    //     'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    //   },
    // }).then(r => {
    //   console.log(r)
    //   return r.json()
    // })
    //   // SUCCESS
    //   .then(r => {
    //     localStorage.setItem(this.localStorageName, body)
    //     this.setState({ formIsSent: true, formJustSent: true })
    //     this.setState({ formIsSenging: false });
    //   })
    //   // NEFORTANULO
    //   .catch(error => {
    //     this.setState({ formIsSenging: false });
    //     console.error(`ModalForm.handleFormSubmit throws error in ${this.formName} form`, { error })
    //   })
  }

  handleFormReset(event: any) {
    event.preventDefault()
    localStorage.removeItem(this.localStorageName)
    this.setState({ formIsSent: false })
  }


  render() {
    return (
      <div onClick={this.showFormHandler}>

        {/*********** PORTALS ************/}
        {this.props.formTriggers.map(({ condition, targetContainerId, containerClass, title, ctaScr }, key) => (
          <IfTrueThenRender key={key} condition={condition}>
            <Portal targetId={targetContainerId} containerClass={containerClass}>
              <Button title={title} target={this.formName} ctaSrc={ctaScr} />
            </Portal>
          </IfTrueThenRender>
        ))}

        {/* Basic form */}
        <Modal show={this.state.ModalIsOpened} onHide={this.closeModalHandler}>
          <Modal.Header closeButton>
            <Modal.Title>{this.props.formTitle}</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div className={ModalFormStyle.form}>
              {this.state.formIsSent ?
                <div>
                  <h5>Спасибо за обращение!</h5>
                  <p>Мы свяжемся с Вами ближайшее время или утром.</p>
                  {!this.state.formJustSent ? <>
                    <hr className="mb-5" />
                    <h5>Никто не перезвонил?</h5>
                    <p><a style={{ color: "#EEC900" }} onClick={this.handleFormReset} href="#!">Отправить форму еще раз</a></p>
                  </> : ""
                  }
                </div> :
                <Form
                  disabled={this.state.formIsSenging}
                  schema={this.schema}
                  uiSchema={this.props.formBuilder.uiSchema}
                  widgets={this.props.formBuilder.widgets}
                  transformErrors={this.props.formBuilder.transformErrors}
                  ErrorList={this.props.formBuilder.ErrorList}
                  // @ts-ignore
                  onSubmit={form => this.handleFormSubmit(form)}
                >
                  <div>
                    <button className={`btn btn-yellow btn-block`} type="submit">
                      {
                        this.state.formIsSenging ?
                          <><span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>{' '}Отправка</>
                          : <>Отправить</>
                      }

                    </button>
                  </div>
                </Form>
              }
            </div>
          </Modal.Body>
        </Modal>
      </div>
    );
  }
}

export default ModalForm;


interface ModalTriggers {
  condition: boolean,
  targetContainerId: string,
  containerClass: string,
  title: string,
  ctaScr: string,
}

interface FormBuilder {
  schema: any
  uiSchema: UiSchema
  widgets?: { [name: string]: Widget }
  transformErrors?: (errors: AjvError[]) => AjvError[]
  ErrorList?: React.StatelessComponent<ErrorListProps>
}

interface Props {
  formTriggers: ModalTriggers[],
  formName: string,
  formTitle?: string,
  formBuilder: FormBuilder
}

interface State {
  ModalIsOpened: boolean,
  regions: string[],
  formMeta: {
    formName?: string,
    formCtaSource?: string,
    ref?: string,
  },
  formIsSent: boolean,
  formJustSent: boolean,
  formIsSenging: boolean,
}

type formDataType = {
  formData: {
    apply: boolean // true
    debt: number // 2050000
    name: string // "Test"
    phone: number // xxxxxxxxxx
    region: string // "Астраханская область"
  }
}
