import React, { useState } from 'react'
import { DatePicker, Form, Input } from 'antd'
import { FormInstance } from 'antd/es/form/Form'

import { Paragraph } from 'components/Typography'
import { MultistageFormStage } from 'components/MultistageForm'

import { MusicItem } from 'models/talent/talent-profile-module.model'

import { addingHttpsPrefix } from 'utils/string'

import { ReactComponent as DateIcon } from 'icons/date.svg'
import moment, { Moment } from 'moment'

interface CustomItemReleaseFormProps {
  isEdit: boolean
  music?: MusicItem
  isDisabledDate: (date: any) => boolean
}

export const CustomItemReleaseForm: React.FC<CustomItemReleaseFormProps> = ({
  isEdit,
  music,
  isDisabledDate,
  ...props
}) => {
  const [date, setDate] = useState<Moment>()
  const [form, setForm] = useState<FormInstance>()

  const initialValues = React.useMemo(() => {
    const releaseDate = isEdit ? moment(music?.releaseDate) : moment(Date.now())
    const customLink = isEdit ? music?.links[0].url : ''

    setTimeout(() => setDate(releaseDate))

    return {
      releaseDate,
      customLink
    }
  }, [isEdit, music])

  const handleChangeLink: React.ChangeEventHandler<
    HTMLInputElement
  > = event => {
    const { value } = event.currentTarget
    const normalizedValue = addingHttpsPrefix(value)

    form?.setFieldsValue({ customLink: normalizedValue })
  }

  return (
    <MultistageFormStage
      initialValues={initialValues}
      setForm={setForm}
      requiredMark="optional"
      validateTrigger="onSubmit"
      {...props}
    >
      <Paragraph className="m__b--5" preset="semibold18">
        How it works
      </Paragraph>
      <Paragraph className="opacity--80 m__b--16" preset="regular16">
        Enter the release date and your pre-release landing page link
      </Paragraph>

      <Form.Item
        className={'m__b--16'}
        colon={false}
        label="Release date"
        labelAlign="left"
        name="releaseDate"
        rules={[{ required: true, message: 'Please enter this field' }]}
      >
        <DatePicker
          value={date}
          onSelect={value => {
            form?.setFieldsValue({
              releaseDate: value
            })
          }}
          disabledDate={isDisabledDate}
          placeholder="Date"
          format="DD MMMM, YYYY"
          allowClear={false}
          suffixIcon={<DateIcon />}
        />
      </Form.Item>

      <Form.Item
        className="m__b--120"
        label="Link"
        labelAlign="left"
        name="customLink"
        colon={false}
        rules={[
          { required: true, message: 'Please enter this field' },
          { type: 'url', message: 'This field must be a valid url.' }
        ]}
      >
        <Input onChange={handleChangeLink} placeholder="https://" />
      </Form.Item>
    </MultistageFormStage>
  )
}
