import React from 'react'
import Link from 'next/link'
import axios from 'axios'
import { mdiArrowTopRight, mdiClose, mdiOfficeBuildingOutline } from '@mdi/js'
import BaseIcon from './BaseIcon'
import AsideMenuList from './AsideMenuList'
import { MenuAsideItem } from '../interfaces'
import { useAppSelector } from '../stores/hooks'
import { getWorkspaceConfig, getWorkspaceRoute } from '../helpers/workspace'

type Props = {
  menu: MenuAsideItem[]
  className?: string
  onAsideLgCloseClick: () => void
}

type OrganizationOption = {
  id: string
  name: string
}

export default function AsideMenuLayer({ menu, className = '', ...props }: Props) {
  const corners = useAppSelector((state) => state.style.corners)
  const asideStyle = useAppSelector((state) => state.style.asideStyle)
  const asideBrandStyle = useAppSelector((state) => state.style.asideBrandStyle)
  const asideScrollbarsStyle = useAppSelector((state) => state.style.asideScrollbarsStyle)
  const darkMode = useAppSelector((state) => state.style.darkMode)
  const { currentUser } = useAppSelector((state) => state.auth)

  const [organizations, setOrganizations] = React.useState<OrganizationOption[]>([])

  const roleName = currentUser?.app_role?.name || ''
  const workspaceConfig = getWorkspaceConfig(roleName)
  const workspaceHref = getWorkspaceRoute(roleName)
  const organizationId = currentUser?.organizations?.id

  React.useEffect(() => {
    let mounted = true

    const fetchOrganizations = async () => {
      try {
        const response = await axios.get('/org-for-auth')

        if (mounted) {
          setOrganizations(Array.isArray(response.data) ? response.data : [])
        }
      } catch (error: any) {
        console.error('Failed to load organizations for sidebar', error?.response || error)
      }
    }

    fetchOrganizations()

    return () => {
      mounted = false
    }
  }, [])

  const handleAsideLgCloseClick = (e: React.MouseEvent) => {
    e.preventDefault()
    props.onAsideLgCloseClick()
  }

  const organizationName = React.useMemo(() => {
    const matchedOrganization = organizations.find((item) => item.id === organizationId)?.name

    if (!matchedOrganization) {
      return 'Organization workspace'
    }

    return matchedOrganization.length > 26 ? `${matchedOrganization.substring(0, 26)}...` : matchedOrganization
  }, [organizationId, organizations])

  return (
    <aside
      id='asideMenu'
      className={`${className} fixed top-0 z-40 flex h-screen w-72 overflow-hidden transition-position lg:py-2 lg:pl-2`}
    >
      <div className={`flex flex-1 flex-col overflow-hidden border ${asideStyle} ${corners}`}>
        <div className={`border-b px-4 py-4 ${asideBrandStyle}`}>
          <div className='flex items-start justify-between gap-3'>
            <div className='min-w-0 flex-1'>
              <p className='text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-500 dark:text-slate-400'>FDSU ERP</p>
              <h2 className='mt-2 line-clamp-2 text-lg font-semibold leading-6 text-slate-900 dark:text-white'>
                {workspaceConfig.sidebarLabel}
              </h2>
              <div className='mt-3 flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400'>
                <BaseIcon path={mdiOfficeBuildingOutline} size={14} />
                <span className='line-clamp-2 leading-5'>{organizationName}</span>
              </div>
            </div>
            <button className='hidden rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 hover:text-slate-900 lg:inline-flex xl:hidden dark:hover:bg-slate-900 dark:hover:text-white' onClick={handleAsideLgCloseClick}>
              <BaseIcon path={mdiClose} />
            </button>
          </div>

          <div className='mt-4 border-t border-slate-200 pt-3 dark:border-slate-800'>
            <p className='truncate text-sm font-semibold text-slate-900 dark:text-white'>
              {currentUser?.firstName || currentUser?.email || 'Authenticated user'}
            </p>
            <div className='mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-slate-500 dark:text-slate-400'>
              <span>{roleName || 'Workspace access'}</span>
              <span aria-hidden='true'>•</span>
              <Link href={workspaceHref} className='inline-flex items-center gap-1 font-medium text-blue-700 transition hover:text-slate-950 dark:text-sky-400 dark:hover:text-white'>
                Open workspace home
                <BaseIcon path={mdiArrowTopRight} size={14} />
              </Link>
            </div>
          </div>
        </div>

        <div className={`flex-1 overflow-y-auto overflow-x-hidden px-2 py-3 ${darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle}`}>
          <AsideMenuList menu={menu} />
        </div>
      </div>
    </aside>
  )
}
