import List from 'antd/lib/list'
import React, { useState } from 'react'
import { Text } from 'components/Typography'
import {
  TalentModuleMixItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import { Icon } from 'components/Icon'
import { Button } from 'antd'

interface ModuleVisibilityEditorProps<T> {
  module: TalentProfileModule<T>
  toggleVisible: (value: boolean) => void
  onVisiblityChanged: (
    visible: boolean,
    showTitle: boolean,
    items: TalentModuleMixItem[]
  ) => void
  onEditModule: (moduleEdit: any) => void
}

const ModuleVisibilityEditor: React.FC<
  ModuleVisibilityEditorProps<TalentModuleMixItem>
> = ({ module, onVisiblityChanged }) => {
  const relcalculateModuleItemsVisibilityAndSet = (
    visible: boolean,
    showTitle: boolean
  ) => {
    const updatedItems = Array.from(module.items)
    if (!module.visible && updatedItems.length > 0) {
      updatedItems.forEach((item: any) => {
        return (item.visible = false)
      })
    }

    onVisiblityChanged(visible, showTitle, updatedItems)
  }

  const handleToggleModuleVisibility = () => {
    // If module and title are currently shown, hide both
    if (module.visible) {
      relcalculateModuleItemsVisibilityAndSet(false, false)
    } // Else if both are hidden, show both
    else {
      relcalculateModuleItemsVisibilityAndSet(true, true)
    }
  }

  const handleToggleTitleVisiblity = () => {
    if (module.visible) {
      onVisiblityChanged(module.visible, !module.showTitle, module.items)
    }
  }

  return (
    <List
      data-testid="module-editor-action"
      className="module-editor__acitons"
      header={<Text>Manage Visibility</Text>}
    >
      <List.Item onClick={() => handleToggleModuleVisibility()}>
        <Text
          data-testid="module-visibility-action--module"
          preset="semibold14"
        >
          Module
        </Text>
        <Button type="link">
          <Icon name={module.visible ? 'open-eye' : 'closed-eye'} />
        </Button>
      </List.Item>
      <List.Item onClick={() => handleToggleTitleVisiblity()}>
        <Text
          data-testid="module-visibility-action--module-title"
          preset="semibold14"
          disabled={!module.visible}
        >
          Module Title
        </Text>
        <Button disabled={!module.visible} type="link">
          <Icon
            name={
              !module.visible
                ? 'closed-eye-inactive'
                : module.showTitle
                  ? 'open-eye'
                  : 'closed-eye'
            }
          />
        </Button>
      </List.Item>
    </List>
  )
}

export default ModuleVisibilityEditor
