import React from 'react'

import Button from '../../Button/Button'
import Icon from '../../Icons/Icon'
import Tooltip from '../../Tooltip/Tooltip'
import { trimText } from '../../../services/HelperServiceTyped'
import { type BreadcrumbsProps, type BreadcrumbType } from './BreadcrumbTypes'
import styles from './_breadcrumb-common-components.module.scss'

const BreadcrumbArrow = () => <span className={styles.arrow} />

type BreadcrumbPopoverContentProps = {
  /** Array of breadcrumbs */
  breadcrumbs: BreadcrumbType[]
  /** Function to close the popover */
  close: () => void
  /** Breadcrumb callout */
  callout: BreadcrumbsProps['callout']
  /** Optionally remove the 1st and last index of the breadcrumbs so they are not shown in the popover. Only the Desktop experience needs this. */
  isDesktop?: boolean
}

const BreadcrumbPopoverContent = ({
  breadcrumbs,
  close,
  callout,
  isDesktop,
}: BreadcrumbPopoverContentProps) => {
  let spaces = 0

  const options = breadcrumbs
    .filter((b, index) => {
      // We want to remove the 1st and last index of the breadcrumbs array when in the desktop version.
      if (isDesktop) {
        return index !== 0 && index !== breadcrumbs.length - 1 ? b : false
      }
      return b
    })
    .map((o: BreadcrumbType, i: number) => {
      o.showIcon = i > 0
      return o
    })

  const updateBreadcrumb = (breadcrumb: BreadcrumbType) => {
    callout(breadcrumb)
    close()
  }

  return (
    <div className={styles.breadcrumbPopoverContainer}>
      {options?.map((opt, i) => {
        if (i > 1) {
          spaces = spaces + 8
        }

        return (
          <Button
            as='unstyled'
            key={`${opt.link}-${i}`}
            className={styles.popoverOption}
            onClick={() => updateBreadcrumb(opt)}
          >
            {opt.showIcon && (
              <span style={i > 1 ? { marginLeft: spaces } : {}}>
                <Icon icon='l' className={styles.lIcon} color='purple' />
              </span>
            )}
            <span className={styles.popoverOptionText}>
              {options.length - 1 !== i || isDesktop ? (
                opt.name
              ) : (
                <TextUnderline
                  text={options[options.length - 1].name ?? ''}
                  small
                />
              )}
            </span>
          </Button>
        )
      })}
    </div>
  )
}

type TextUnderlineProps = {
  /** The text that will be rendered for this component */
  text: string
  /** Optionally use the small version for this component (12px). */
  small?: boolean
  /** Length of the truncated text */
  characterLimit?: BreadcrumbsProps['textUnderlineCharacterLimit']
  /** Determines if this component is being used in the desktop version. */
  isDesktop?: boolean
}

const TextUnderline = ({
  text,
  small,
  characterLimit,
  isDesktop,
}: TextUnderlineProps): React.JSX.Element => {
  // Trim the text if characterLimit is provided
  const updatedText = characterLimit ? trimText(text, characterLimit) : text
  const textArr = updatedText?.split(' ').filter(Boolean)
  const textArrLength = textArr.length
  const firstWordLength = textArr[0]?.length || 0

  // Determine characterLength based on the conditions below
  let characterLength = null

  if (textArrLength === 1) {
    if (firstWordLength < 5) {
      characterLength = null // Single short word
    } else if (characterLimit && firstWordLength > characterLimit) {
      characterLength = characterLimit - 2 // Single word with character limit
    } else if (firstWordLength > 15) {
      characterLength = 5 // Single long word. Chose 15 because it fits mobile screen sizes. Chose 5 as the standard for the underline length for long words.
    } else {
      characterLength = firstWordLength - 2 // Normal case for single word
    }
  } else if (firstWordLength < 5) {
    characterLength = updatedText.length - 2 // Multiple words, first is short
  } else if (characterLimit && firstWordLength > characterLimit) {
    characterLength = characterLimit - 2 // Multiple words with character limit
  } else {
    characterLength = firstWordLength - 2 // Default case for multiple words
  }

  const MainComponent = () => (
    <span className={`${styles.container} ${small ? styles.small : ''}`}>
      <span className={styles.underline}>
        {characterLength ? updatedText.slice(0, characterLength) : updatedText}
      </span>
      {characterLength ? (
        <span>{updatedText.slice(characterLength)}</span>
      ) : null}
    </span>
  )

  return isDesktop ? (
    characterLimit && text.length > characterLimit ? (
      <Tooltip
        tooltipContent={text}
        position='bottom'
        className={styles.tooltipText}
      >
        {MainComponent()}
      </Tooltip>
    ) : (
      MainComponent()
    )
  ) : (
    MainComponent()
  )
}

export { BreadcrumbArrow, BreadcrumbPopoverContent, TextUnderline }
