import * as React from 'react'
import { useCallback, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import { Col, Form, Input as AntdInput, Row, Switch } from 'antd'
import { FormInstance, Rule } from 'antd/lib/form'

import DragDropButton from 'components/Button/DragDropButton'
import { Paragraph, Text } from 'components/Typography'
import { Icon } from 'components/Icon'
import { MusicProfileLinkItem } from 'components/PreReleaseModal'

import { PreReleaseLinkArtist } from '../PreReleaseLinkArtist/PreReleaseLinkArtist'

import classNames from 'classnames'
import './PreReleaseLinkItem.scss'

interface PreReleaseLinkItemProps {
  form?: FormInstance
  item: MusicProfileLinkItem
  className?: string
  dragHandleProps?: DraggableProvidedDragHandleProps
  setItem: (link: MusicProfileLinkItem) => void
}

const PreReleaseLinkItem = ({
  className,
  dragHandleProps,
  form,
  item,
  setItem
}: PreReleaseLinkItemProps) => {
  const { artistsToFollow, icon, isVisible, isTemporary, key, name, url } = item

  const artists = React.useMemo(
    () => artistsToFollow || [{ name: '', url: '' }],
    []
  )

  useEffect(() => {
    setItem({ ...item, url })
  }, [url])

  const handleLinkChange: React.ChangeEventHandler<
    HTMLInputElement
  > = event => {
    const link = event.target.value
    setItem({ ...item, url: link })

    if (!form) {
      return
    }

    const musicLinks = form.getFieldValue('musicLinks')
    musicLinks[key]['isVisible'] = Boolean(link)

    form?.setFieldsValue({ musicLinks })
  }

  const linkInputRules: Rule[] = [
    { type: 'url', message: 'This field must be a valid url.' }
  ]

  const buildFormItemName = useCallback(
    itemName => ['musicLinks', key, itemName],
    [item.key]
  )

  return (
    <div className={classNames('music-item', className)}>
      <Row className="prerelease--item-head" align="middle" wrap={false}>
        <Col className="prerelease--item-head-left">
          <Icon name={icon || 'apple-music'} />
          <Text ellipsis={true} preset="semibold16">
            {name}
          </Text>
        </Col>

        <Text>Visible</Text>
        <Form.Item
          className="prerelease--item-head-visible"
          name={buildFormItemName('isVisible')}
          valuePropName="checked"
          initialValue={isVisible}
        >
          <Switch />
        </Form.Item>

        <DragDropButton
          className="prerelease--item-head-drag"
          dragType="vertical"
          dragHandleProps={dragHandleProps}
          onClick={event => event.stopPropagation()}
        />
      </Row>

      <Paragraph className="prerelease--item-learn-more">
        Want to know how {name} pre-saves work? <Link to="#">Learn more</Link>
      </Paragraph>

      <Form.Item
        label="Pre-Release Link"
        labelAlign="left"
        colon={false}
        requiredMark={false}
        className={classNames('m__t--24 m__b--24')}
        rules={linkInputRules}
        initialValue={item.url}
        name={buildFormItemName('url')}
      >
        <AntdInput onChange={handleLinkChange} placeholder="https://" />
      </Form.Item>

      <Row className="prerelease--item-temporary-link">
        <Form.Item
          name={buildFormItemName('isTemporary')}
          className="prerelease--item-temporary-link-switch"
          valuePropName="checked"
          initialValue={isTemporary}
        >
          <Switch />
        </Form.Item>

        <Paragraph className="prerelease--item-temporary-link-label">
          You don’t have a link yet? Use a temporary link and be reminded 7 days
          ahead of the release date
        </Paragraph>
      </Row>

      {key === 'SPOTIFY' && (
        <Form.List
          initialValue={artists}
          name={buildFormItemName('artistsToFollow')}
        >
          {(fields, { add, remove }) => (
            <div className="prerelease--item-artists">
              <Text
                className="prerelease--item-artists-label"
                preset="semibold14"
              >
                Artist(s) to follow (optional)
              </Text>

              {fields.map((item, index) => (
                <PreReleaseLinkArtist
                  key={item.key}
                  initialArtistValue={artists[index]}
                  index={index}
                  remove={remove}
                />
              ))}

              <Row
                className="prerelease--item-artists-add"
                gutter={8}
                align="middle"
              >
                {/* This cannot be simplified to `onClick={add}`, or it will post unwanted parameters */}
                <Col onClick={() => add()} className="height--32">
                  <Icon name="add-blue" />
                </Col>
                <Col onClick={() => add()}>
                  <Paragraph className="text--blue m__b--0" preset="semibold18">
                    Add artist
                  </Paragraph>
                </Col>
              </Row>
            </div>
          )}
        </Form.List>
      )}

      <Paragraph className="prerelease--item-learn">
        <Link to="#">Learn more</Link> about the data you can collect from
        Spotify pre-saves
      </Paragraph>
    </div>
  )
}

export default React.memo(PreReleaseLinkItem)
