'use client'

import classNames from 'classnames'
import { ForwardedRef, forwardRef } from 'react'

import { Representing, User, UserMenuItem } from '../header/types'
import { PktIcon } from '../icon/Icon'
import { PktLink } from '../link/Link'

// Internal type for rendering links/buttons (supports both href and onClick)
interface IInternalMenuItemBase {
  title: string
  iconName?: string
}

interface InternalMenuLink extends IInternalMenuItemBase {
  href: string
}

interface InternalMenuButton extends IInternalMenuItemBase {
  onClick: () => void
}

type TInternalMenuItem = InternalMenuLink | InternalMenuButton

// Helper to convert UserMenuItem (with target) to internal format
const convertUserMenuItem = (item: UserMenuItem): TInternalMenuItem => {
  if (typeof item.target === 'string') {
    return { title: item.title, iconName: item.iconName, href: item.target }
  }
  return { title: item.title, iconName: item.iconName, onClick: item.target }
}

export interface IPktHeaderUserMenu {
  user: User
  formattedLastLoggedIn?: string
  representing?: Representing
  userMenu?: UserMenuItem[]
  canChangeRepresentation?: boolean
  changeRepresentation?: () => void
  logoutOnClick?: () => void
}

const LinkOrButtonComponent = ({ item, className }: { item: TInternalMenuItem; className?: string }) => {
  const isLink = 'href' in item

  return isLink ? (
    <PktLink
      iconName={item.iconName}
      href={item.href}
      aria-hidden="true"
      className={classNames('pkt-user-menu__link', className)}
    >
      {item.title}
    </PktLink>
  ) : (
    <button
      className={classNames('pkt-user-menu__link pkt-link-button pkt-link pkt-link--icon-left', className)}
      type="button"
      onClick={() => {
        if ('onClick' in item && typeof item.onClick === 'function') {
          item.onClick()
        } else {
          // eslint-disable-next-line no-console
          console.error('UserMenuButton item is missing onClick handler or onClick is not a function:', item)
        }
      }}
    >
      {item.iconName && <PktIcon name={item.iconName} className="pkt-link__icon" aria-hidden="true" />}
      {item.title}
    </button>
  )
}

const LinkSection = ({ links }: { links: TInternalMenuItem[] }) => {
  return (
    <ul className="pkt-user-menu__sublist">
      {links.map((item, index) => {
        return (
          <li key={index} className="pkt-user-menu__subitem">
            <LinkOrButtonComponent item={item} />
          </li>
        )
      })}
    </ul>
  )
}

export const PktHeaderUserMenu = forwardRef(
  (
    {
      user,
      formattedLastLoggedIn,
      representing,
      userMenu,
      canChangeRepresentation,
      changeRepresentation,
      logoutOnClick,
    }: IPktHeaderUserMenu,
    ref: ForwardedRef<HTMLDivElement>,
  ) => {
    // Convert userMenu items to internal format
    const internalMenuItems = userMenu?.map(convertUserMenuItem)

    return (
      <nav className="pkt-user-menu" ref={ref} aria-label="Meny for innlogget bruker">
        <ul className="pkt-user-menu__list">
          {/* User section */}
          {user && (
            <li className="pkt-user-menu__item">
              <div className="pkt-user-menu__label">Pålogget som</div>
              <div className="pkt-user-menu__name" translate="no">
                {user.name}
              </div>
              {formattedLastLoggedIn && (
                <div className="pkt-user-menu__last-logged-in">
                  Sist pålogget: <time>{formattedLastLoggedIn}</time>
                </div>
              )}
            </li>
          )}

          {/* User menu items */}
          {internalMenuItems && internalMenuItems.length > 0 && (
            <li className="pkt-user-menu__item">
              <LinkSection links={internalMenuItems} />
            </li>
          )}

          {/* Representing section */}
          {representing && (
            <li className="pkt-user-menu__item">
              <div className="pkt-user-menu__label">Representerer</div>
              <div className="pkt-user-menu__name" translate="no">
                {representing.name}
              </div>
              {representing.orgNumber && (
                <div className="pkt-user-menu__org-number">Org.nr. {representing.orgNumber}</div>
              )}
              {canChangeRepresentation && changeRepresentation && (
                <ul className="pkt-user-menu__sublist mt-size-16">
                  <li className="pkt-user-menu__subitem">
                    <LinkOrButtonComponent
                      item={{ title: 'Endre organisasjon', iconName: 'cogwheel', onClick: changeRepresentation }}
                    />
                  </li>
                </ul>
              )}
            </li>
          )}

          {/* Change representation without representing object */}
          {!representing && canChangeRepresentation && changeRepresentation && (
            <li className="pkt-user-menu__item">
              <ul className="pkt-user-menu__sublist">
                <li className="pkt-user-menu__subitem">
                  <LinkOrButtonComponent
                    item={{ title: 'Endre organisasjon', iconName: 'cogwheel', onClick: changeRepresentation }}
                  />
                </li>
              </ul>
            </li>
          )}

          {/* Logout */}
          {logoutOnClick && (
            <li className="pkt-user-menu__item">
              <LinkOrButtonComponent item={{ title: 'Logg ut', iconName: 'exit', onClick: logoutOnClick }} />
            </li>
          )}
        </ul>
      </nav>
    )
  },
)

PktHeaderUserMenu.displayName = 'PktHeaderUserMenu'
