import classnames from "classnames"
import * as React from "react"
import axios from "axios"

import * as styles from "./ContactForm.module.sass"
import { consultingCategory, position } from "@/components/contact-form/data"
import AutoComplete from "@/components/AutoComplete"
import { useRef, useState } from "react"
import { getReferer, getUtm } from "@/track"
import { IMatch } from "@/components/AutoComplete/AutoComplete"
import { useDebounceFn } from "ahooks"

interface IProps extends React.HTMLAttributes<HTMLIFrameElement> {
  isOpen: boolean
  handleOpen?: () => void
  handleClose: () => void
  location?: ILocation
  props?: IPropsInner
}

const ACCOUNT_API_URL =
  process.env.GATSBY_ACCOUNT_API_BASE_URL ?? "https://accounts-preview.pingcap.com"

export default function ContactForm(props: IProps) {
  const { isOpen, handleClose, location, props: propsInner } = props
  return isOpen ? (
    <>
      <div className={styles.mask}>
        <div className={styles.container}>
          <div className={styles.close}>
            <div className={styles.close_icon} onClick={handleClose} />
          </div>
          <div className={styles.form_wrapper}>
            <ContactFormInner handleClose={handleClose} location={location} {...propsInner} />
          </div>

          {/*<iframe*/}
          {/*  id={iframeId}*/}
          {/*  //ref={ref}*/}
          {/*  width={"100%"}*/}
          {/*  height={"100%"}*/}
          {/*  src={*/}
          {/*    "https://www.fxiaoke.com/ec/h5-landing/release/index.html?id=1f281c32d9db46d199edc2798994debb&sourceType=7"*/}
          {/*  }*/}
          {/*/>*/}
        </div>
      </div>
    </>
  ) : (
    <></>
  )
}

export interface IPropsInner {
  handleClose?: () => any
  title?: string
  description?: string
  isShowHeader?: boolean
  consult_category?: string
  location?: ILocation
}
export function ContactFormInner({
  handleClose,
  title = "与 PingCAP 联系",
  description = "留下您的联系方式，我们将在 1 个工作日内和您联系",
  isShowHeader = true,
  consult_category = undefined,
  location,
}: IPropsInner) {
  const iframeId = "contact-form-fxk"
  //useEffect(() => {
  //  if (isOpen) {
  //    window.FsYxt.creatIframeByScript({
  //      id: iframeId,
  //      src:
  //        "https://www.fxiaoke.com/ec/h5-landing/release/index.html?id=1f281c32d9db46d199edc2798994debb&sourceType=7",
  //      style: "width: 100%;height: 100%",
  //    })
  //  }
  //}, [isOpen])
  const [submitDisabled, setSubmitDisabled] = useState(false)
  const [formData, setFormData] = useState<{
    name?: string
    phone?: string
    phone_code?: string
    company?: string
    job_title?: string
    consult_category?: string
    consult_detail?: string
    checkbox?: boolean
  }>({
    name: undefined,
    phone: undefined,
    phone_code: undefined,
    company: undefined,
    job_title: undefined,
    consult_category,
    consult_detail: undefined,
    checkbox: undefined,
  })
  const [formError, setFormError] = useState<{
    name: string[]
    phone: string[]
    phone_code: string[]
    company: string[]
    job_title: string[]
    consult_category: string[]
    consult_detail: string[]
  }>({
    name: [],
    phone: [],
    phone_code: [],
    company: [],
    job_title: [],
    consult_category: [],
    consult_detail: [],
  })
  const validate = (): boolean => {
    const {
      name,
      phone,
      phone_code,
      company,
      job_title,
      consult_category,
      consult_detail,
      checkbox,
    } = formData
    //console.log("!!formData", formData)
    const name_valid = (name?.length ?? 0) > 0
    const phone_valid = (phone?.length ?? 0) > 0
    const phone_code_valid = (phone_code?.length ?? 0) > 0
    const company_valid = (company?.length ?? 0) > 0
    const job_title_valid = (job_title?.length ?? 0) > 0
    const consult_category_valid = (consult_category?.length ?? 0) > 0
    const consult_detail_valid = (consult_detail?.length ?? 0) > 0
    const checkbox_valid = checkbox === true
    return (
      name_valid &&
      phone_valid &&
      phone_code_valid &&
      company_valid &&
      job_title_valid &&
      consult_category_valid &&
      consult_detail_valid &&
      checkbox_valid
    )
  }
  const handleSubmit = async () => {
    if (!validate()) return
    setSubmitDisabled(true)
    const trackInfo = {
      utm: getUtm(),
      referer: getReferer(),
    }
    try {
      const result = await axios.post(
        `${ACCOUNT_API_URL}/api/official/contact-us`,
        {
          name: formData.name,
          phone: formData.phone,
          phone_code: formData.phone_code,
          company: formData.company,
          job_title: formData.job_title,
          consult_category: formData.consult_category,
          consult_detail: formData.consult_detail,
          utm_source: trackInfo.utm.utm_source,
          utm_medium: trackInfo.utm.utm_medium,
          utm_campaign: trackInfo.utm.utm_campaign,
          utm_term: trackInfo.utm.utm_term,
          referer: trackInfo.referer,
          referer2: location?.state?.referrer,
        },
        { withCredentials: true }
      )
      window.alert("提交成功！")
      handleClose?.()
      window.location.reload()
      //await navigate("/contact")
    } catch (e) {
      console.error("submit form error", e)
      setFormError(e.response.data.errors)
      window.alert("表单提交失败，请查看表单项下面的错误提示信息")
    } finally {
      setSubmitDisabled(false)
      sessionStorage.setItem("PhoneNumber", formData.phone ?? "")
      //sessionStorage.setItem("Email", formData.email)
    }
  }
  const smsTimer = useRef<number | undefined>()
  const [reSendRemainSecond, setReSendRemainSecond] = useState(-1)
  const showResendStatus = reSendRemainSecond >= 0
  const handleSendSMS = async () => {
    setSubmitDisabled(true)
    setReSendRemainSecond(60)
    try {
      await axios.post(`${ACCOUNT_API_URL}/api/official/contact-us/sms-code`, {
        phone: formData.phone,
      })
      smsTimer.current = window.setInterval(() => {
        setReSendRemainSecond(reSendRemainSecond => reSendRemainSecond - 1)
      }, 1000)
    } catch (e) {
      console.error("send phone code error", e)
      window.alert("验证码发送错误，请检查手机号是否正确")
      setReSendRemainSecond(-1)
      return
    } finally {
      setSubmitDisabled(false)
    }
  }
  const { run: queryCompany } = useDebounceFn(
    async (word: string): Promise<void> => {
      try {
        const response = await axios.get(
          `${ACCOUNT_API_URL}/api/search-company?word=${word}`
        )
        const data = response.data.data as { name: string }[]
        const matches: IMatch[] = data.map(value => ({
          value: value.name,
          label: value.name,
        }))
        setMatch(matches)
      } catch (e) {
        console.error("query company error", e)
        setMatch([])
      }
    },
    { wait: 250 }
  )
  const [match, setMatch] = useState<IMatch[]>([])
  return (
    <div>
      {isShowHeader && (
        <div className={styles.header}>
          <h2>{title}</h2>
          <p>{description}</p>
        </div>
      )}

      <div id={iframeId} className={styles.form}>
        <div className="field">
          <label className="label">
            <span className={styles.require_mark}>*</span> 姓名
          </label>
          <div className="control">
            <input
              className="input"
              type="text"
              placeholder="请填写姓名"
              value={formData.name}
              onChange={event =>
                setFormData(state => ({
                  ...state,
                  name: event.target.value,
                }))
              }
            />
          </div>
          {formData.name === "" && (
            <p className="help is-danger">该字段不可为空</p>
          )}
          {formError.name?.map(value => (
            <p className="help is-danger">{value}</p>
          ))}
        </div>

        <label className="label">
          <span className={styles.require_mark}>*</span> 手机号
        </label>
        <div className="field is-grouped">
          <p className="control is-expanded">
            <input
              className="input"
              type="text"
              placeholder="请填写您的手机号"
              value={formData.phone}
              onChange={event =>
                setFormData(state => ({
                  ...state,
                  phone: event.target.value.trim(),
                }))
              }
            />
          </p>
          <p className="control">
            <button
              className={classnames("button")}
              onClick={handleSendSMS}
              disabled={showResendStatus}
            >
              {showResendStatus
                ? `重新发送(${reSendRemainSecond}s)`
                : "发送验证码"}
            </button>
          </p>
        </div>
        {formError.phone?.map(value => (
          <p className="help is-danger">{value}</p>
        ))}

        <div className="field">
          <input
            className="input"
            type="text"
            placeholder="请填写您收到的验证码"
            value={formData.phone_code}
            onChange={event =>
              setFormData(state => ({
                ...state,
                phone_code: event.target.value.trim(),
              }))
            }
          />
          {formData.phone_code === "" && (
            <p className="help is-danger">该字段不可为空</p>
          )}
          {formError.phone_code?.map(value => (
            <p className="help is-danger">{value}</p>
          ))}
        </div>

        {/*<div className="field">*/}
        {/*  <label className="label">公司 Email</label>*/}
        {/*  <div className="control">*/}
        {/*    <input*/}
        {/*      className="input"*/}
        {/*      type="text"*/}
        {/*      placeholder="请填写您的工作Email"*/}
        {/*    />*/}
        {/*  </div>*/}
        {/*</div>*/}

        <div className="field">
          <label className="label">
            <span className={styles.require_mark}>*</span> 公司名称
          </label>
          <div className="control">
            <AutoComplete
              inputDOM={
                <input
                  className="input"
                  type="text"
                  placeholder="请填写公司名称"
                  value={formData.company}
                  //onBlur={() => setTimeout(() => setMatch([]), 200)}
                  onChange={event => {
                    const company = event.target.value
                    queryCompany(company)
                    setFormData(state => ({
                      ...state,
                      company,
                    }))
                  }}
                />
              }
              onClick={() => setMatch([])}
              handleSelect={value => {
                setFormData(state => ({
                  ...state,
                  company: value,
                }))
                setMatch([])
              }}
              match={match}
            />
          </div>
          {formData.company === "" && (
            <p className="help is-danger">该字段不可为空</p>
          )}
          {formError.company?.map(value => (
            <p className="help is-danger">{value}</p>
          ))}
        </div>

        <div className="field">
          <label className="label">
            <span className={styles.require_mark}>*</span> 职位
          </label>
          <div className="control">
            {/*<input className="input" type="text" placeholder="请选择职位" />*/}
            <div
              className={classnames(
                "select is-fullwidth",
                styles.select
              )}
            >
              <select
                placeholder="请选择职位"
                value={formData.job_title}
                onChange={event =>
                  setFormData(state => ({
                    ...state,
                    job_title: event.target.value,
                  }))
                }
              >
                <option value={undefined}>请选择</option>
                {position.map(value => (
                  <option key={value.value} {...value} />
                ))}
              </select>
            </div>
          </div>
          {formData.job_title === "" && (
            <p className="help is-danger">该字段不可为空</p>
          )}
          {formError.job_title?.map(value => (
            <p className="help is-danger">{value}</p>
          ))}
        </div>

        <div className="field">
          <label className="label">
            <span className={styles.require_mark}>*</span> 咨询类别
          </label>
          <div className="control">
            {/*<input*/}
            {/*  className="input"*/}
            {/*  type="text"*/}
            {/*  placeholder="请选择咨询类别"*/}
            {/*/>*/}
            <div
              className={classnames(
                "select is-fullwidth",
                styles.select
              )}
            >
              <select
                placeholder="请选择咨询类别"
                value={formData.consult_category}
                onChange={event =>
                  setFormData(state => ({
                    ...state,
                    consult_category: event.target.value,
                  }))
                }
              >
                <option value={undefined}>请选择</option>
                {consultingCategory.map(value => (
                  <option key={value.value} {...value} />
                ))}
              </select>
            </div>
          </div>
          {formData.consult_category === "" && (
            <p className="help is-danger">该字段不可为空</p>
          )}
          {formError.consult_category?.map(value => (
            <p className="help is-danger">{value}</p>
          ))}
        </div>

        <div className="field">
          <label className="label">
            <span className={styles.require_mark}>*</span> 咨询事宜
          </label>
          <div className="control">
            <textarea
              className="textarea"
              rows={3}
              placeholder="请填写咨询事宜"
              value={formData.consult_detail}
              onChange={event =>
                setFormData(state => ({
                  ...state,
                  consult_detail: event.target.value,
                }))
              }
            />
          </div>
          {formData.consult_detail === "" && (
            <p className="help is-danger">该字段不可为空</p>
          )}
          {formError.consult_detail?.map(value => (
            <p className="help is-danger">{value}</p>
          ))}
        </div>

        <div className="field">
          <div className={classnames("control", styles.checkbox)}>
            <label className="checkbox">
              <input
                type="checkbox"
                checked={formData.checkbox}
                onChange={event =>
                  setFormData(state => ({
                    ...state,
                    checkbox: event.target.checked,
                  }))
                }
              />
              请阅读并同意{" "}
              <a className={'privacy-policy-link'} href="/privacy-policy" target="_blank">
                PingCAP 隐私政策
              </a>{" "}
            </label>
          </div>
          {formData.checkbox === false && (
            <p className="help is-danger">你需要阅读并同意 PingCAP 隐私政策</p>
          )}
        </div>

        <div className="field">
          <div className={classnames("control", styles.submit)}>
            <button
              className={classnames("button", styles.submit, {
                "button is-link is-fullwidth": validate(),
              })}
              onClick={handleSubmit}
              disabled={submitDisabled || !validate()}
            >
              提交
            </button>
          </div>
          {/*<div className="control">*/}
          {/*  <button className="button is-link is-light">关闭</button>*/}
          {/*</div>*/}
        </div>
      </div>
    </div>
  )
}
