import React, { useState, useCallback, useEffect, useMemo } from 'react'
import { Paragraph, Text } from 'components/Typography'
import Card from 'antd/lib/card'
import { Button, Col, Row, Form, Input } from 'antd'
import { Icon } from 'components/Icon'
import { MediaUpload } from 'redux/Common/types'
import classNames from 'classnames'
import CoverUpload from '../CoverUpload/CoverUpload'
import './Forms.scss'
import { FormInstance } from 'antd/lib/form/Form'
import { LAYOUT } from 'constants/data-capture'
import DataCaptureLayout from '../Layout'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useWindowSize } from '../../../hooks'
import FormButtons from '../FormButtons/FormButtons'

interface IProps {
  form: FormInstance<any>
  onClose: () => void
  photoUpload: MediaUpload
  hasImage: boolean
  layout: string
  title: string
  subTitle: string
  setPhotoUpload: React.Dispatch<React.SetStateAction<MediaUpload>>
  setHasImage: React.Dispatch<React.SetStateAction<boolean>>
  setLayout: React.Dispatch<React.SetStateAction<string>>
  setTitle: React.Dispatch<React.SetStateAction<string>>
  setSubTitle: React.Dispatch<React.SetStateAction<string>>
}

const FirstStep = ({
  form,
  onClose,
  photoUpload,
  hasImage,
  layout,
  setHasImage,
  setLayout,
  setPhotoUpload,
  title,
  setTitle,
  subTitle,
  setSubTitle
}: IProps) => {
  const size = useWindowSize()
  const isMobile = useMemo(() => (size.width || 0) <= 768, [size])
  const isContactFormFlagOn = useFeatureIsOn(FLAGS.FEAT_SB_630_CONTACT_FORM)
  const [errorPhoto, setErrorPhoto] = useState(false)
  const [showReplace, setShowReplace] = useState(false)
  const handleInputChange = (event: any) => {
    const value = event.target.value
    if (value.length > 35) {
      return
    }
    setTitle(value)
    form.setFieldsValue({ title: value })
  }

  const handleChangeSubtitle = (event: any) => {
    const value = event.target.value
    if (value.length > 70) {
      return
    }
    setSubTitle(value)
    form.setFieldsValue({ subTitle: value })
  }

  useEffect(() => {
    if (!showReplace && photoUpload?.url) {
      setShowReplace(true)
    }
  }, [showReplace, photoUpload?.url])

  const uploadPhotoSuccess = (file: MediaUpload) => {
    errorPhoto && setErrorPhoto(false)
    setShowReplace(true)
    setPhotoUpload(file)
    setHasImage(true)
  }

  const removePhoto = () => {
    setPhotoUpload({})
    setShowReplace(false)
  }

  const toggleImage = useCallback(() => {
    setHasImage?.(prev => !prev)
  }, [])
  const handleSubmit = () => {
    if (!photoUpload.url && hasImage) {
      setErrorPhoto(true)
      return
    }
  }

  return (
    <DataCaptureLayout
      data={{
        title,
        subTitle,
        hasImage,
        image: photoUpload?.url || '',
        layout
      }}
      step={1}
    >
      <div className="data-capture-form-container">
        <Paragraph preset="semibold18">Module Banner</Paragraph>
        <Paragraph
          preset="regular16"
          className="m__t--4 text--default opacity--80"
        >
          You can adjust the design of the module banner and preview how it will
          appear to your audience.
        </Paragraph>
        <Card className={!isMobile ? 'm__t--24' : 'm__t--16'}>
          <Paragraph preset="semibold18">Layout</Paragraph>
          <Row className="m__t--8" gutter={16}>
            <Col>
              <Text preset="semibold14" className="text--grey4 opacity--80">
                Left
              </Text>

              <Col
                className={classNames('wrap-img', {
                  active: layout === LAYOUT.LEFT
                })}
                onClick={() => setLayout?.(LAYOUT.LEFT)}
              >
                <div className="wrap-img_item">
                  <Icon name="data-capture-layout-left" />
                </div>
              </Col>
            </Col>
            <Col>
              <Text preset="semibold14" className="text--grey4">
                Center
              </Text>

              <Col
                className={classNames('wrap-img', {
                  active: layout === LAYOUT.CENTER
                })}
                onClick={() => setLayout?.(LAYOUT.CENTER)}
              >
                <div className="wrap-img_item">
                  <Icon name="data-capture-layout-center" />
                </div>
              </Col>
            </Col>
          </Row>
        </Card>
        <Card className={!isMobile ? classNames('m__t--20') : 'm__t--10'}>
          <Row align="middle" justify="space-between">
            <Col flex={'1'}>
              <Text preset="medium18">Image</Text>
            </Col>
            <Col>
              <div onClick={toggleImage} style={{ cursor: 'pointer' }}>
                <Icon name={hasImage ? 'switch-on' : 'switch-off'}></Icon>
              </div>
            </Col>
          </Row>
          <div
            className={!isMobile ? 'm__t--24 relative' : 'm__t--12 relative'}
          >
            {photoUpload?.url && !hasImage && <div className="overlay" />}

            <CoverUpload
              photo={photoUpload}
              onUploadSuccess={uploadPhotoSuccess}
              onRemove={removePhoto}
              hideUpdate
              replace={showReplace}
            />
          </div>
          {errorPhoto && (
            <Paragraph preset="regular12" className="m__t--8 text--error">
              Please upload an image
            </Paragraph>
          )}
        </Card>
        <Card className="m__t--20">
          <Paragraph preset="semibold18">Content</Paragraph>

          <Form.Item
            name="title"
            className={'m__t--16 m__b--16'}
            label="Title"
            rules={[{ required: true, message: 'Please enter title' }]}
          >
            <Input
              className="height--52"
              placeholder="Add a title, e.g. “Sign up for my email newsletter”"
              onChange={handleInputChange}
              maxLength={35}
              value={title}
            />
            <Text
              preset="regular12"
              className={`count-message m__t--4 ${'text--default opacity--60'}`}
            >
              {`${title.length}/35 characters`}
            </Text>
          </Form.Item>
          <Form.Item
            label="Subtitle (Optional)"
            name="subTitle"
            className={'m__b--0'}
          >
            <Input
              className="height--52"
              placeholder="Add a subtitle, e.g. “Receive updates and exclusive content”"
              onChange={handleChangeSubtitle}
              maxLength={70}
              value={subTitle}
            />
            <Text
              preset="regular12"
              className="m__t--4 text--default opacity--60"
            >
              {subTitle.length | 0}/70 characters
            </Text>
          </Form.Item>
        </Card>
        {!(isContactFormFlagOn && isMobile) && (
          <div className="profile-smart-link__actions m__t--38">
            <FormButtons handleClose={onClose} />
          </div>
        )}
      </div>
    </DataCaptureLayout>
  )
}

export default FirstStep
