import React from 'react'
import { mdiClose } from '@mdi/js'
import BaseIcon from './BaseIcon'
import AsideMenuList from './AsideMenuList'
import { MenuAsideItem } from '../interfaces'
import { useAppDispatch, useAppSelector } from '../stores/hooks'
import { createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
import Logo from './Logo'

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

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 handleAsideLgCloseClick = (e: React.MouseEvent) => {
    e.preventDefault()
    props.onAsideLgCloseClick()
  }

  const dispatch = useAppDispatch()
  const { currentUser } = useAppSelector((state) => state.auth)
  const organizationsId = currentUser?.organizations?.id
  const [organizations, setOrganizations] = React.useState<any[]>([])

  const fetchOrganizations = createAsyncThunk('/org-for-auth', async () => {
    try {
      const response = await axios.get('/org-for-auth')
      setOrganizations(response.data)
      return response.data
    } catch (error: any) {
      console.error(error?.response || error)
      throw error
    }
  })

  React.useEffect(() => {
    dispatch(fetchOrganizations())
  }, [dispatch])

  let organizationName = organizations?.find((item) => item.id === organizationsId)?.name
  if (organizationName?.length > 28) {
    organizationName = organizationName.substring(0, 28) + '...'
  }

  return (
    <aside
      id='asideMenu'
      className={`${className} zzz lg:py-2 lg:pl-2 w-60 fixed flex z-40 top-0 h-screen transition-position overflow-hidden`}
    >
      <div className={`flex-1 flex flex-col overflow-hidden dark:bg-dark-900 ${asideStyle} ${corners}`}>
        <div className={`flex min-h-14 items-center justify-between gap-3 px-4 py-3 ${asideBrandStyle}`}>
          <div className='flex min-w-0 items-center gap-3'>
            <Logo className='h-10 w-auto shrink-0 rounded-xl bg-white p-1.5 shadow-sm' />
            <div className='min-w-0'>
              <p className='truncate text-sm font-semibold text-slate-900 dark:text-white'>DakikTabela</p>
              <p className='truncate text-xs text-slate-500 dark:text-slate-300'>Operasyon Platformu</p>
              {organizationName && (
                <p className='truncate text-[11px] text-slate-400 dark:text-slate-400'>{organizationName}</p>
              )}
            </div>
          </div>
          <button className='hidden lg:inline-block xl:hidden p-3' onClick={handleAsideLgCloseClick}>
            <BaseIcon path={mdiClose} />
          </button>
        </div>
        <div
          className={`flex-1 overflow-y-auto overflow-x-hidden ${
            darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
          }`}
        >
          <AsideMenuList menu={menu} />
        </div>
      </div>
    </aside>
  )
}
