'use client'

import * as React from "react"
import {useRef, useState, useEffect} from "react"
import axios from "axios"
import {useDebounceFn} from "ahooks"
import {AutoComplete, Button, Checkbox, Form, Input, Modal, Row, Select, Space} from "antd";

import {getReferer, getUtm} from "@/hooks/track"

import {consultingCategory, position} from "./data"
import styles from "./ContactForm.module.sass"
import {ACCOUNT_API_URL} from "@/constant";

export interface IMatch {
  value: string
  label: string
}

export function useContactForm() {
  const [open, setOpen] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const handleOpen = () => setOpen(true)
  const handleOk = () => setOpen(false)
  const handleCancel = () => setOpen(false)
  const node = (
    <Modal
      // title="Title"
      open={open}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      onCancel={handleCancel}
      maskClosable={false}
      keyboard={false}
      footer={null}
    >
      <ContactFormInner handleClose={() => setOpen(false)} />
    </Modal>
  )
  return {node, handleOpen}
}

export interface IPropsInner {
  handleClose?: () => any
  title?: string
  description?: string
  isShowHeader?: boolean
  consult_category?: string
  // location?: ILocation
}
export function ContactFormInner(props: IPropsInner) {
  const {
    handleClose,
    title = "与平凯星辰联系",
    description = "留下您的联系方式，我们将在 1 个工作日内和您联系",
    isShowHeader = true,
    consult_category = undefined,
    // location,
  } = props
  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 [captchaResponse, setCaptchaResponse] = useState('');
  const [captchaKey, setCaptchaKey] = useState('');
  const [captchaImageUrl, setCaptchaImageUrl] = useState<string | undefined>(undefined)
  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)
    try {
      const trackInfo = {
        utm: getUtm(),
        referer: getReferer(),
      }
      const result = await axios.post(
        `/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: window.document.referrer,
        },
        { withCredentials: true }
      )
      window.alert("提交成功！")
      handleClose?.()
      window.location.reload()
      //await navigate("/contact")
    } catch (e) {
      console.error("submit form error", e)
      // @ts-ignore
      setFormError(e.response.data.errors)
      window.alert("表单提交失败，请查看表单项下面的错误提示信息")
    } finally {
      setSubmitDisabled(false)
      sessionStorage.setItem("PhoneNumber", formData.phone ?? "")
      //sessionStorage.setItem("Email", formData.email)
    }
  }
  const smsTimer = useRef<number | null>(null)
  const [reSendRemainSecond, setReSendRemainSecond] = useState(60)
  const [sendBtnDisabled, setSendBtnDisabled] = useState(false)
  const [showResendStatus, setShowResendStatus] = useState(false)

  const clearSmsTimer = () => {
    if (smsTimer.current) {
      clearInterval(smsTimer.current)
      smsTimer.current = null
    }
  }
  const startCountdown = () => {
    clearSmsTimer()
    setSendBtnDisabled(true)
    setShowResendStatus(true)
    setReSendRemainSecond(60)

    smsTimer.current = window.setInterval(() => {
      setReSendRemainSecond((prev) => {
        if (prev <= 1) {
          clearSmsTimer()
          setSendBtnDisabled(false)
          setShowResendStatus(false)
          return 0
        }
        return prev - 1
      })
    }, 1000)
  }
  const handleSendSMS = async () => {
    setSubmitDisabled(true)

    const params: Record<string, any> = {
      phone: formData.phone,
      ...(captchaKey && captchaResponse
        ? { captcha_key: captchaKey, captcha_response: captchaResponse }
        : {}),
    };

    try {
      await axios.post(`/api/official/contact-us/sms-code`, params)
      startCountdown();
    } catch (e: any) {
      const errors = e?.response?.data?.errors;
      const data = e?.response?.data?.data;

      if (errors) {
        const firstError = Object.values(errors)[0] as string[];
        window.alert(firstError?.[0] || '验证码发送错误，请检查手机号是否正确');
      }

      if (data?.image_url && data?.key) {
        setCaptchaImageUrl(data.image_url);
        setCaptchaKey(data.key);
        setSendBtnDisabled(true);
        return;
      }

      startCountdown();

    } finally {
      setSubmitDisabled(false)
    }
  }
  const handleRefreshCaptcha = async () => {
    try {
      const res = await axios.post(`/api/captcha/refresh`)
      const imageUrl = res?.data?.image_url as string | undefined
      const key = res?.data?.key as string | undefined
      if (imageUrl) setCaptchaImageUrl(imageUrl)
      if (key) setCaptchaKey(key)
      setCaptchaResponse('')
    } catch (e) {
      console.error('refresh captcha error', e)
    }
  }
  const handleCaptchaInput = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value.trim();
    setCaptchaResponse(value)

    if (value && !showResendStatus) {
      setSendBtnDisabled(false)
    } else {
      setSendBtnDisabled(true)
    }
  }
  const { run: queryCompany } = useDebounceFn(
    async (word: string): Promise<void> => {
      if (word === '') return
      try {
        const response = await axios.get(
          `/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[]>([])

  useEffect(() => {
    return () => clearSmsTimer()
  }, [])

  return (
    <div>
      {isShowHeader && (
        <div className={styles.header}>
          <h2>{title}</h2>
          <p>{description}</p>
        </div>
      )}

      <div id={iframeId}>
        <Form
          layout={'vertical'}
          requiredMark={true}
        >
          <Form.Item required label="姓名">
            <Input
              placeholder="请填写姓名"
              value={formData.name}
              onChange={event =>
                setFormData(state => ({
                  ...state,
                  name: event.target.value,
                }))
              }
            />
            {formData.name === "" && (
              <p className={styles.error}>该字段不可为空</p>
            )}
            {formError.name?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item required label="手机号">
              <Input
                style={{width: 'calc(100%-144px)', marginRight: 16}}
                placeholder="请填写您的手机号"
                value={formData.phone}
                onChange={event =>
                  setFormData(state => ({
                    ...state,
                    phone: event.target.value.trim(),
                  }))
                }
              />
            {formError.phone?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item required label="验证码">
            {captchaImageUrl && (
              <div style={{display: 'flex', alignItems: 'center', gap: 16, marginBottom: 12}}>
                <Input
                  style={{flex: 1}}
                  placeholder="请输入图形验证码"
                  value={captchaResponse}
                  onChange={handleCaptchaInput}
                />
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={captchaImageUrl} alt="captcha" width={102} height={40} style={{cursor: 'pointer'}} onClick={handleRefreshCaptcha} />
              </div>
            )}
            <div style={{display: 'flex', gap: 16}}>
              <Input
                placeholder="请填写您收到的验证码"
                value={formData.phone_code}
                onChange={event =>
                  setFormData(state => ({
                    ...state,
                    phone_code: event.target.value.trim(),
                  }))
                }
              />
              <Button
                onClick={handleSendSMS}
                disabled={sendBtnDisabled}
              >
                {showResendStatus
                  ? `重新发送(${reSendRemainSecond}s)`
                  : "发送验证码"}
              </Button>
            </div>
            {formData.phone_code === "" && (
              <p className={styles.error}>该字段不可为空</p>
            )}
            {formError.phone_code?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item required label="公司名称">
            <AutoComplete
              placeholder="请填写您的公司名称"
              value={formData.company}
              onChange={value =>
                setFormData(state => ({
                  ...state,
                  company: value.trim(),
                }))
              }
              onSearch={queryCompany}
              options={match}
            />
            {formData.company === "" && (
              <p className={styles.error}>该字段不可为空</p>
            )}
            {formError.company?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item required label="职位">
            {/*TODO: auto complete*/}
            <Select
              placeholder="请选择职位"
              value={formData.job_title}
              onChange={value =>
                setFormData(state => ({
                  ...state,
                  job_title: value,
                }))
              }
            >
              <Select.Option value={undefined}>请选择</Select.Option>
              {position.map(value => (
                <Select.Option key={value.value} {...value} />
              ))}
            </Select>
            {formData.job_title === "" && (
              <p className={styles.error}>该字段不可为空</p>
            )}
            {formError.job_title?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item required label="咨询类别">
            {/*TODO: auto complete*/}
            <Select
              placeholder="请选择咨询类别"
              value={formData.consult_category}
              onChange={value =>
                setFormData(state => ({
                  ...state,
                  consult_category: value,
                }))
              }
            >
              <Select.Option value={undefined}>请选择</Select.Option>
              {consultingCategory.map(value => (
                <Select.Option key={value.value} {...value} />
              ))}
            </Select>
            {formData.consult_category === "" && (
              <p className={styles.error}>该字段不可为空</p>
            )}
            {formError.consult_category?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item required label="咨询类别">
            <Input.TextArea
              rows={3}
              placeholder="请填写咨询事宜"
              value={formData.consult_detail}
              onChange={event =>
                setFormData(state => ({
                  ...state,
                  consult_detail: event.target.value,
                }))
              }
            />
            {formData.consult_detail === "" && (
              <p className={styles.error}>该字段不可为空</p>
            )}
            {formError.consult_detail?.map(value => (
              <p key={value} className={styles.error}>{value}</p>
            ))}
          </Form.Item>
          <Form.Item>
            <Checkbox
              checked={formData.checkbox}
              onChange={event =>
                setFormData(state => ({
                  ...state,
                  checkbox: event.target.checked,
                }))
              }
            >
              请阅读并同意{" "}
              <a className={styles.checkbox_link} href="/privacy-policy" target="_blank">
               平凯星辰隐私政策
              </a>
            </Checkbox>
            {formData.checkbox === false && (
              <p className={styles.error}>你需要阅读并同意平凯星辰隐私政策</p>
            )}
          </Form.Item>
          <Form.Item>
            <Button
              type={'primary'}
              block
              onClick={handleSubmit}
              disabled={!validate()}
              loading={submitDisabled}
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
