import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import Modal from 'components/Modal'
import { Button, ConfigProvider, Form } from 'antd'
import { Row, Col } from 'antd/lib/grid'
import { Paragraph } from 'components/Typography'
import FirstStep from './Forms/FirstStep'
import SecondStep from './Forms/SecondStep'
import ThirdStep from './Forms/ThirdStep'
import { Icon } from 'components/Icon'
import {
  DataCaptureFieldItem,
  DataCaptureFormItem
} from 'models/talent/talent-profile-module.model'
import { useForm } from 'antd/lib/form/Form'
import { DEFAULT_FIELDS, LAYOUT } from 'constants/data-capture'
import { MediaUpload } from 'redux/Common/types'
import omit from 'lodash/omit'
import './index.scss'
import { useTypedSelector } from 'redux/rootReducer'
import { selectUserData } from 'redux/User/selector'
import { LIGHT_THEME } from 'constants/profile-theme'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import classNames from 'classnames'
import FormButtons from './FormButtons/FormButtons'
import { useWindowSize } from '../../hooks'
import {
  DataCaptureFieldType,
  DataCaptureFormType
} from '@komi-app/shared-types'
interface IProps {
  item?: DataCaptureFormItem
  show: boolean
  toggleModal(show: boolean): void
  onFinish?: (values: any) => void
  isContactForm?: boolean
  isNew?: boolean
}

const initialValues = {
  title: '',
  subTitle: '',
  contentTitle: '',
  contentSubTitle: ''
}

const DataCaptureModal = ({
  show,
  toggleModal,
  item,
  onFinish,
  isContactForm = false,
  isNew = false
}: IProps) => {
  const user = useTypedSelector(selectUserData)

  const [photoUpload, setPhotoUpload] = useState<MediaUpload>({})
  const [hasImage, setHasImage] = useState<boolean>(false)
  const [layout, setLayout] = useState<string>(LAYOUT.LEFT)
  const [step, setStep] = useState<number>(1)
  const [fields, setFields] = useState<DataCaptureFieldItem[]>(DEFAULT_FIELDS)
  const [title, setTitle] = useState<string>('')
  const [subTitle, setSubTitle] = useState<string>('')
  const [formTitle, setFormTitle] = useState<string>('')
  const [formSubTitle, setFormSubTitle] = useState<string>('')
  const [form] = useForm()
  const [formData, setFormData] = useState<any>({})
  const [showClosePopup, setShowClosePopup] = useState(false)
  const modalRef = useRef<any>(null)
  const nextStep = useCallback(() => {
    setStep(prev => prev + 1)
    modalRef?.current?.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
  }, [modalRef])
  const isContactFormEnabled = useFeatureIsOn(FLAGS.FEAT_SB_630_CONTACT_FORM)
  const size = useWindowSize()
  const isMobile = useMemo(() => (size.width || 0) <= 768, [size])
  const isContactFormFlagOn = useFeatureIsOn(FLAGS.FEAT_SB_630_CONTACT_FORM)

  const prevStep = useCallback(() => {
    setStep(prev => prev - 1)
    modalRef?.current?.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
  }, [modalRef])

  useEffect(() => {
    if (show) {
      if (!item) {
        const fields = DEFAULT_FIELDS.reduce((value, item) => {
          return { ...value, [item.name]: item.label }
        }, {})
        form.setFieldsValue({
          ...initialValues,
          ...fields
        })
        return
      }
      setPhotoUpload({ url: item.image })
      setHasImage(item?.enableImage || false)
      setLayout(item.layout || LAYOUT.LEFT)
      const fields = item.form.fields.reduce((value, item) => {
        return { ...value, [item.name]: item.label }
      }, {})
      setFields(item.form.fields)

      setTitle(item.title)
      setSubTitle(item.subTitle || '')
      setFormTitle(item.form.title || '')
      setFormSubTitle(item.form.subTitle || '')

      form.setFieldsValue({
        ...fields,
        title: item.title,
        subTitle: item.subTitle || '',
        headerTitle: item.form.title || '',
        headerSubTitle: item.form.subTitle || '',
        formName: item.form.name
      })
    }
  }, [show, item])
  const handleClose = useCallback(() => {
    isNew ? onDisCardChanges() : setShowClosePopup(true)
  }, [])

  const onDisCardChanges = useCallback(() => {
    toggleModal(false)

    setTimeout(() => {
      form.resetFields()
      setFormData({})
      setFields(DEFAULT_FIELDS)
      setPhotoUpload({})
      setHasImage(false)
      setLayout(LAYOUT.LEFT)
      setStep(1)
      setTitle('')
      setSubTitle('')
      setFormTitle('')
      setFormSubTitle('')
      setShowClosePopup(false)
    }, 200)
  }, [
    form,
    setFormData,
    setFields,
    setPhotoUpload,
    setHasImage,
    setStep,
    toggleModal,
    setTitle,
    setSubTitle,
    setFormTitle,
    setFormSubTitle
  ])
  const renderStep = () => {
    switch (step) {
      case 1:
        return (
          <div>
            <FirstStep
              form={form}
              onClose={handleClose}
              photoUpload={photoUpload}
              hasImage={hasImage}
              layout={layout}
              setPhotoUpload={setPhotoUpload}
              setHasImage={setHasImage}
              setLayout={setLayout}
              title={title}
              setTitle={setTitle}
              subTitle={subTitle}
              setSubTitle={setSubTitle}
            />
            {isContactFormFlagOn && isMobile && (
              <FormButtons handleClose={handleClose} />
            )}
          </div>
        )
      case 2:
        return (
          <div>
            <SecondStep
              fields={fields}
              setFields={setFields}
              form={form}
              nextStep={nextStep}
              onClose={handleClose}
              title={formTitle}
              setTitle={setFormTitle}
              subTitle={formSubTitle}
              setSubTitle={setFormSubTitle}
            />
            {isContactFormFlagOn && isMobile && (
              <FormButtons
                handleClose={handleClose}
                nextStepDisabled={!fields.length}
              />
            )}
          </div>
        )
      case 3:
        return (
          <ThirdStep
            isEdit={!!item}
            onSubmit={() => {}}
            onClose={handleClose}
          />
        )

      default:
        break
    }
  }

  const handleSubmit = (values: any) => {
    if (!photoUpload.url && hasImage) {
      return
    }
    if (step === 1) {
      const data = {
        layout,
        enableImage: hasImage,
        image: photoUpload.url,
        title: values.title,
        subTitle: values.subTitle
      }
      setFormData((value: any) => ({ ...value, ...data }))
      nextStep()
      return
    }
    if (
      !fields.length ||
      fields.some(
        field =>
          ([
            DataCaptureFieldType.SELECT_MULTIPLE,
            DataCaptureFieldType.SELECT_SINGLE
          ].includes(field.type) &&
            !field.options?.length) ||
          (field.type === DataCaptureFieldType.LEGALS &&
            !field.options?.length &&
            !field.text)
      )
    ) {
      return
    }
    if (step === 2) {
      const formFields = fields.map(item => {
        let options = item.options
        if (item.options?.length) {
          options = item.options.map(el => omit(el, 'edit'))
        }
        return omit({ ...item, options }, ['edit'])
      })
      const data = {
        form: {
          title: values.headerTitle,
          subTitle: values.headerSubTitle,
          fields: formFields
        }
      }
      setFormData((value: any) => ({ ...value, ...data }))
      nextStep()
      return
    }
    const newForm = { ...formData.form, name: values.formName }
    const data = { ...formData, form: newForm, order: 0 }

    if (isContactForm) {
      data.formType = DataCaptureFormType.CONTACT_FORM
      data.emailNotifications = true
    }

    onFinish?.(data)
    onDisCardChanges()
  }
  const widthModal = useMemo(() => {
    if (showClosePopup) {
      return 522
    }
    if (step === 3) {
      return 644
    }
    return 960
  }, [step, showClosePopup])

  const isDarken = useMemo(
    () =>
      user?.talentProfile?.themeColor?.overlayColor ===
      LIGHT_THEME.overlayColor,
    [user?.talentProfile?.themeColor?.overlayColor]
  )

  useEffect(() => {
    if (user) {
      const themeColor = user?.talentProfile?.themeColor

      ConfigProvider.config({
        theme: {
          primaryColor: themeColor?.backgroundColor, // backgroundColor
          infoColor: themeColor?.typographyColor, // textColor
          successColor: isDarken
            ? 'rgba(18, 18, 18, 0.1)'
            : 'rgba(255, 255, 255, 0.1)' // overlayColor
        }
      })
    } else {
      ConfigProvider.config({
        theme: {
          primaryColor: '#121212', // backgroundColor
          infoColor: '#ffffff', // textColor
          successColor: 'rgba(255, 255, 255, 0.1)' // overlayColor
        }
      })
    }
  }, [isDarken, user])

  return (
    <ConfigProvider>
      <Modal
        width={widthModal}
        closable
        centered
        className={classNames(
          showClosePopup ? 'data-capture-cancel' : 'data-capture-modal',
          {
            'data-capture-modal-mobile-fix': isContactFormEnabled
          }
        )}
        visible={show}
        onCancel={handleClose}
        destroyOnClose
        maskClosable={false}
        title={
          !showClosePopup ? (
            <div>
              <Paragraph
                preset="semibold14"
                className="text--mineShaft opacity--60"
              >
                Step {step}/3
              </Paragraph>
              <Row align="middle" className="m__t--8">
                {step > 1 && (
                  <Col
                    onClick={prevStep}
                    className="m__r--8 d--flex cursor-pointer"
                  >
                    <Icon name="back" />
                  </Col>
                )}
                <Col>
                  <Paragraph preset="semibold18">
                    {isContactForm
                      ? 'Create a Contact Form'
                      : 'Create a Data Capture Form'}
                  </Paragraph>
                </Col>
              </Row>
            </div>
          ) : null
        }
      >
        {showClosePopup ? (
          <div className="flex flex-col">
            <Paragraph preset="semibold18">
              Are you sure you want to discard your changes?
            </Paragraph>
            <Paragraph className="opacity--80 m__t--8" preset="regular16">
              {`The updates you’ve made to this ${isContactForm ? 'contact form' : 'data capture form'} will be
              discarded and you can’t undo this action.`}
            </Paragraph>
            <Row
              className="m__t--24"
              gutter={16}
              align="middle"
              justify="space-between"
            >
              <Col flex={'1'}>
                <Button
                  className="ant-btn-xl ant-btn-uppercase full-width"
                  onClick={() => setShowClosePopup(false)}
                  size="large"
                  type="primary"
                >
                  No Thanks!
                </Button>
              </Col>
              <Col flex={'1'}>
                <Button
                  onClick={onDisCardChanges}
                  className="ant-btn-xl ant-btn-uppercase full-width"
                >
                  Discard Changes
                </Button>
              </Col>
            </Row>
          </div>
        ) : (
          <div className="data-capture-modal--content" ref={modalRef}>
            <Form
              labelCol={{
                span: 24
              }}
              wrapperCol={{
                span: 24
              }}
              form={form}
              onFinish={handleSubmit}
              hideRequiredMark
            >
              {renderStep()}
            </Form>
          </div>
        )}
      </Modal>
    </ConfigProvider>
  )
}

export default DataCaptureModal
