import { AsqMeItem } from '@komi-app/profiles-sdk'
import selfless from '@komi-app/selfless'
import { BooleanArraySupportOption } from 'prettier'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import React from 'react'
import { useHistory } from 'react-router-dom'

import AsqMeItemModule from 'components/AsqMeItemModule/AsqMeItemModule'
import DragDropContext from 'components/DragDropContext'
import PortalComponent from 'components/PortalComponent/PortalComponent'
import { Text } from 'components/Typography'
import { useAnalyticsStartItemCreation } from 'hooks/useAnalyticsStartItemCreation'
import { useModules } from 'hooks/useModules'
import { TalentProfileModule } from 'models/talent/talent-profile-module.model'
import {
  getAsqMeUrlSegmentForModuleType,
  useIsAsqMeFeatureEnabled
} from 'utils/asqme-utils'
import ModuleEditor from '../ModuleEditor'
import { ModuleAsqMeHeader } from './ModuleAsqMeHeader'
import { AsqMeModuleType } from '@komi-app/meta-profiles'

type ModuleAsqMeProps = {
  module: TalentProfileModule<AsqMeItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: BooleanArraySupportOption
}

type ModuleAsqMeViewProps = ModuleAsqMeProps & {
  onNewItem: () => void
  onEditItem: (item: AsqMeItem) => void
  onDeleteItem: (item: AsqMeItem) => void
  onReorderItems: (items: AsqMeItem[]) => void
  isFeatureOn: boolean
}

function useModuleAsqMe(props: ModuleAsqMeProps): ModuleAsqMeViewProps {
  const router = useHistory()
  const modules = useModules()
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const isFeatureOn = useIsAsqMeFeatureEnabled(
    props.module.type as AsqMeModuleType
  )

  function onNewItem() {
    if (!isFeatureOn) {
      return
    }

    trackStartAddingItemToModule(props.module)
    const urlSegment = getAsqMeUrlSegmentForModuleType(props.module.type)
    router.push(
      `/admin/modules/${urlSegment}?moduleId=${props.module.id}&returnUrl=${window.location.pathname}`
    )
  }

  function onEditItem(item: AsqMeItem) {
    const urlSegment = getAsqMeUrlSegmentForModuleType(props.module.type)
    router.push(
      `/admin/modules/${urlSegment}?moduleId=${props.module.id}&itemId=${item.id}&returnUrl=${window.location.pathname}`
    )
  }

  function onDeleteItem(item: AsqMeItem) {
    modules.setModule?.({
      ...props.module,
      items: props.module.items.filter(i => i.id !== item.id),
      isUpdate: true
    })
  }

  function onReorderItems(items: AsqMeItem[]) {
    const updatedModule = {
      ...props.module,
      items: items.map((item, index) => ({ ...item, order: index })),
      isUpdate: true
    }
    modules.setModule?.(updatedModule)
  }

  return {
    ...props,
    onNewItem,
    onEditItem,
    onDeleteItem,
    onReorderItems,
    isFeatureOn
  }
}

function ModuleAsqMeView({
  module,
  dragHandleProps,
  onNewItem,
  onEditItem,
  onDeleteItem,
  onReorderItems,
  active,
  isFeatureOn
}: ModuleAsqMeViewProps) {
  return (
    <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
      <ModuleAsqMeHeader
        moduleType={module.type as AsqMeModuleType}
        onClickNewItem={isFeatureOn ? onNewItem : undefined}
        numberOfItems={module.items.length}
      />
      <DragDropContext
        droppableId="asqme-item-drop"
        listClassName="product-list"
        itemIdPrefix="asqme-item"
        direction="vertical"
        list={module.items}
        onDropEndCallback={onReorderItems}
      >
        {(dragProvided, snapshot, item, productIndex) => {
          const isRender = active ? active : productIndex < 2

          return isRender ? (
            <PortalComponent
              innerRef={dragProvided.innerRef}
              key={productIndex}
              namespaceClass="product-list"
              provided={dragProvided}
              snapshot={snapshot}
              single={module.items?.length === 1}
            >
              <AsqMeItemModule
                titleShortcut
                disableDragDrop={module.items?.length <= 1}
                index={productIndex}
                disableDrag={module.items?.length === 1}
                item={item}
                onEdit={onEditItem}
                onDelete={onDeleteItem}
                dragHandleProps={dragProvided.dragHandleProps ?? undefined}
                module={module}
                isInCollection={false}
              />
            </PortalComponent>
          ) : (
            <></>
          )
        }}
      </DragDropContext>
      {!active && module.items.length > 2 && (
        <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
          <Text preset="medium14" className="opacity-6">
            +{module.items.length - 2} More
          </Text>
        </div>
      )}
    </ModuleEditor>
  )
}

export default React.memo(
  selfless<ModuleAsqMeProps, ModuleAsqMeViewProps>(
    ModuleAsqMeView,
    useModuleAsqMe
  )
)
