import React, { useState, useCallback, useEffect } from 'react'
import Modal from 'components/Modal'
import { Button, Form } from 'antd'
import { Row, Col } from 'antd/lib/grid'
import { Icon } from 'components/Icon'
import { Paragraph } from 'components/Typography'
import { useForm } from 'antd/lib/form/Form'
import FirstStep from './Forms/FirstStep'
import SecondStep from './Forms/SecondStep'
import { useDispatch } from 'react-redux'
import { updateTalentProfileActions } from 'redux/User/actions'
import { selectLocalizations } from 'redux/User/selector'
import { useTypedSelector } from 'redux/rootReducer'
import { LocalizationItem } from 'redux/User/types'
import './Forms/Forms.scss'
import { useAutoSave } from 'hooks/useAutoSave'
interface IProps {
  show: boolean
  onClose?: (value: boolean) => void
  edit?: boolean
  formData: LocalizationItem
  onChangeForm: (values: LocalizationItem) => void
  onChangePage?: (item: LocalizationItem) => void
  onShowInfo?: () => void
  onEdit?: () => void
}

const CreateModal = ({
  show,
  onClose,
  edit,
  formData,
  onChangeForm,
  onChangePage,
  onShowInfo,
  onEdit
}: IProps) => {
  const dispatch = useDispatch()
  const [form] = useForm()
  const [isCreate, setIsCreate] = useState<boolean>(false)
  const [step, setStep] = useState<number>(1)
  const localizations = useTypedSelector(selectLocalizations)
  const { onForceSave } = useAutoSave()
  useEffect(() => {
    if (show) {
      !edit
        ? form.resetFields()
        : form.setFieldsValue({
            name: formData.name,
            currency: formData.currency,
            countries: formData.countries
          })
    }
  }, [form, edit, show])

  const nextStep = useCallback(() => {
    setStep(prev => prev + 1)
  }, [])

  const prevStep = useCallback(() => {
    setStep(prev => prev - 1)
  }, [])

  const handleCloseModal = useCallback(() => {
    onClose?.(false)
    setStep(1)
  }, [onClose])

  const handleChangeCurrency = useCallback(
    (value: string) => {
      onChangeForm({ ...formData, currency: value })
    },
    [onChangeForm, formData]
  )

  const handleChangePageCopy = useCallback(
    (value: string) => {
      onChangeForm({ ...formData, copyFrom: value })
    },
    [onChangeForm, formData]
  )

  const handleSubmit = () => {
    if (step === 1) {
      if (edit) {
        onEdit?.()
      } else {
        nextStep()
        return
      }
    }
    if (step === 2) {
      const handleCreatePage = () => {
        //If not in a creating action
        if (!isCreate) {
          //Lock it so clicking the button again would have no effect (prevent multiple page created)
          setIsCreate(true)
          dispatch(
            updateTalentProfileActions.REQUEST({
              localizations: localizations?.length
                ? [...localizations, { ...formData, id: null }]
                : [{ ...formData, id: null }],
              onSuccess: (res: any) => {
                const newLocalization: LocalizationItem = res?.talentProfile
                  ?.localizations.length
                  ? //Under new backend, the order of the localizations might be changed
                    //It is also more robust to search by the matching countries
                    //rather than getting it from the last element of array
                    // ? res?.talentProfile?.localizations[
                    //   res?.talentProfile?.localizations.length - 1
                    // ]
                    res?.talentProfile?.localizations.find(
                      (loc: LocalizationItem) => {
                        return (
                          loc.countries.length == formData.countries.length &&
                          loc.countries.every(function (element, index) {
                            return element === formData.countries[index]
                          })
                        )
                      }
                    )
                  : null
                newLocalization && onChangePage?.(newLocalization)
                onClose?.(false)
                //Workaround for resetting the modal
                handleCloseModal()
                onShowInfo?.()
                //Unlock the button
                setIsCreate(false)
              }
            })
          )
        }
      }
      onForceSave(handleCreatePage)
    }
  }

  const handlePageNameChange = useCallback(
    (name: string) => {
      onChangeForm({ ...formData, name })
    },
    [onChangeForm, formData]
  )

  const handleChangeContries = useCallback(
    (countries: string[]) => {
      onChangeForm({ ...formData, countries })
    },
    [onChangeForm, formData]
  )

  const renderStep = () => {
    switch (step) {
      case 1:
        return (
          <FirstStep
            form={form}
            name={formData?.name}
            countries={formData.countries}
            currency={formData.currency}
            edit={edit}
            onChangeCurrency={handleChangeCurrency}
            onPageNameChange={handlePageNameChange}
            onChangeCountries={handleChangeContries}
          />
        )
      case 2:
        return (
          <SecondStep
            onChangePageCopy={handleChangePageCopy}
            pageCopy={formData.copyFrom || null}
          />
        )

      default:
        return <></>
    }
  }
  return (
    <>
      <Modal
        width={664}
        closable
        centered
        className="localization-create-modal"
        visible={show}
        onCancel={handleCloseModal}
        destroyOnClose
        maskClosable={false}
        title={
          <div>
            {!edit && (
              <Paragraph
                preset="semibold14"
                className="text--mineShaft opacity--60"
              >
                STEP {step}/2
              </Paragraph>
            )}
            <Row align="middle" className="m__t--8">
              {step > 1 && !edit && (
                <Col
                  onClick={prevStep}
                  className="m__r--8 d--flex cursor-pointer"
                >
                  <Icon name="back" />
                </Col>
              )}
              <Col>
                <Paragraph preset="semibold18">
                  {edit
                    ? 'Edit Localized Page Settings'
                    : 'Add a New Localized Page'}
                </Paragraph>
              </Col>
            </Row>
          </div>
        }
      >
        <Form
          labelCol={{
            span: 24
          }}
          wrapperCol={{
            span: 24
          }}
          form={form}
          onFinish={handleSubmit}
          hideRequiredMark
        >
          {renderStep()}
          <div className="localization-create-modal__actions m__t--38">
            <Button
              className="ant-btn-xl ant-btn-uppercase"
              onClick={handleCloseModal}
            >
              Cancel
            </Button>
            <Button
              className="ant-btn-xl ant-btn-uppercase"
              size="large"
              type="primary"
              htmlType="submit"
            >
              {edit ? 'Save' : step === 1 ? 'Next' : 'Done'}
            </Button>
          </div>
        </Form>
      </Modal>
    </>
  )
}

export default CreateModal
