import { useCallback } from 'react'
import { useDispatch } from 'react-redux'
import { v4 as uuidv4 } from 'uuid'
import { useModules } from './useModules'
import { setActiveModuleAction } from '../redux/Talent/actions'
import { ModuleType } from '@komi-app/meta-profiles'
import {useAnalyticsModuleAdded} from "./useAnalyticsModuleAdded";

export function useAddNewModule(groupId?: string) {
  const dispatch = useDispatch()
  const { modules, setModuleList } = useModules()
  const { trackModuleAdded } = useAnalyticsModuleAdded()
  return useCallback(
    (type: ModuleType, data?: any) => {
      const newModule = {
        id: uuidv4(), // TODO: set from backend
        order: 0,
        name: 'New Module',
        type: type,
        items: [],
        expand: true,
        isEdit: true,
        isCreate: true,
        isLoading: false,
        groupId,
        showTitle: true,
        ...data
      }

      const list =
        modules?.map((module: any) => {
          return { ...module, order: module.order + 1 }
        }) || []
      if (groupId) {
        const module = list.find((item: any) => item.id === groupId)
        if (module) {
          module.items = [newModule, ...module.items].map((el, index) => ({
            ...el,
            order: index
          }))
        }
        setModuleList?.(list)
        return
      }

      setModuleList?.([newModule, ...list])
      trackModuleAdded(newModule)
      dispatch(setActiveModuleAction(newModule.id))

      window.scrollTo({
        behavior: 'smooth',
        top: 0
      })
    },
    [modules, groupId, setModuleList]
  )
}
