import React, { useCallback, useEffect, useState } from 'react'

import { MediaUpload } from 'redux/Common/types'
import { MusicItem } from 'models/talent/talent-profile-module.model'

import isEmpty from 'lodash/isEmpty'
import { JSONService } from 'utils/json-patch'
import { noop } from 'utils/noop'

import { MusicItemInformationForm } from './stages/MusicItemInformationForm'
import { SmartItemLinksForm } from './stages/SmartItemLinksForm'
import { SmartItemReleaseForm } from './stages/SmartItemReleaseForm'

import { MultistageModalForm } from 'components/MultistageForm'
import {
  SmartItemCompletionModal,
  SmartItemCompletionModalProps
} from './completion/SmartItemCompletionModal'
import { v4 as uuidV4 } from 'uuid'
import './PreReleaseModal.scss'

import {
  MusicReleaseMode,
  MusicReleaseScope,
  MusicReleaseType
} from '@komi-app/shared-types'

interface PreReleaseSmartModalProps {
  isEdit: boolean
  music?: MusicItem
  onFinish?: (data: any) => void
  onCancel?: () => void
}

export const PreReleaseSmartModal: React.FC<PreReleaseSmartModalProps> = ({
  isEdit,
  music,
  onCancel = noop,
  onFinish = noop
}) => {
  const [releaseType, setReleaseType] = useState(
    music?.releaseType || MusicReleaseMode.KOMI
  )
  const [photo, setPhoto] = useState<MediaUpload>({})

  const [formState, setFormState] = useState<SmartItemCompletionModalProps>()

  useEffect(() => {
    if (isEdit && music) {
      setReleaseType(music.releaseType || MusicReleaseMode.KOMI)
    }
  }, [isEdit, music])

  const handleSubmit = useCallback(
    async values => {
      const {
        artists,
        musicLinks,
        releaseDate,
        releaseTime,
        releaseScope,
        timezone,
        title
      } = values

      const [firstArtist] = artists

      const fixedReleaseDateInfo = {
        year: releaseDate.year(),
        month: releaseDate.month(),
        date: releaseDate.date(),
        hour: releaseTime?.hours() || 0,
        minute: releaseTime?.minutes() || 0,
        second: 0
      }
      const tzReleaseDateTime =
        releaseScope === MusicReleaseScope.GLOBAL
          ? releaseDate
          : releaseDate.utc()
      const releaseDateTime = tzReleaseDateTime.set(fixedReleaseDateInfo)

      const musicLinkTypes = Object.keys(musicLinks)
      const links = musicLinkTypes.map(type => {
        const { ...musicLink } = musicLinks[type]

        return {
          type,
          ...musicLink
        }
      })

      const metadata = {
        artists: artists.map((item: any) => ({
          name: item.name
        })),
        name: title,
        images: [{ url: photo.url }]
      }
      const data = {
        id: music?.id,
        order: music?.order,
        metadata,
        links,
        type: MusicReleaseType.PRE_SAVE,
        releaseDate: releaseDateTime.toISOString(),
        releaseScope,
        releaseType,
        timezone,
        persistentId: music?.persistentId || uuidV4()
      }

      setFormState({
        artistName: firstArtist.name,
        songName: title,
        isTemporary: links.some(link => link.isTemporary),
        photoUrl: photo.url?.toString() || '',
        releaseDate: releaseDateTime.toISOString(),
        releaseScope,
        timezone
      })

      const patch = JSONService.getPatch(data, music, {
        actions: ['add', 'remove', 'replace'],
        ignoreFields: []
      })

      onFinish({
        ...data,
        isUpdate: music?.isUpdate ? music.isUpdate : !isEmpty(patch)
      })

      if (isEdit) {
        onCancel()
      }

      return data
    },
    [onFinish, photo, releaseType]
  )

  const completionStage = React.useMemo(() => {
    if (!isEdit && formState) {
      return <SmartItemCompletionModal {...formState} />
    }
  }, [isEdit, formState])

  return (
    <MultistageModalForm
      completionStage={completionStage}
      title="Pre-Release Smart Link"
      onCancel={onCancel}
      onFinish={handleSubmit}
    >
      <MusicItemInformationForm
        isEdit={isEdit}
        music={music}
        photo={photo}
        setPhoto={setPhoto}
      />
      <SmartItemReleaseForm isEdit={isEdit} music={music} />
      <SmartItemLinksForm isEdit={isEdit} music={music} />
    </MultistageModalForm>
  )
}
