'use client'

import React, { useEffect, useState } from 'react'
import {
  createTheme,
  Sidebar as FlowbiteSidebar,
  SidebarCollapse,
  SidebarItem,
  SidebarItemGroup,
  SidebarItems,
} from 'flowbite-react'
import { FiBell, FiGrid, FiUsers } from 'react-icons/fi'
import { usePathname } from 'next/navigation'
import Image from 'next/image'
import { TbUserDollar, TbUserBolt, TbUserStar } from 'react-icons/tb'
import { AiOutlineBank } from 'react-icons/ai'
import { LuStore, LuTrophy, LuLink2 } from 'react-icons/lu'
import Link from 'next/link'
import { BsBoxArrowDown } from 'react-icons/bs'
import { MdOutlineAutoGraph } from 'react-icons/md'

import { useSidebar } from '@/lib/context/SidebarContext'
import { useAuth } from '@/lib/context/AuthContext'
import { useNotifications } from '@/lib/context/NotificationContext'

interface SidebarItemProps {
  id: number
  link?: string
  icon?: React.FC<React.SVGProps<SVGSVGElement>> | undefined
  title: string
  isActive?: boolean
  isShow?: boolean
  subItems?: {
    id: number
    link: string
    title: string
    isActive?: boolean
    isShow?: boolean
  }[]
}

interface SidebarLinkProps {
  id: number
  category: string | null
  items: SidebarItemProps[]
}

export default function Sidebar() {
  const [screenWidth, setScreenWidth] = useState(window.innerWidth)
  const pathname = usePathname()
  const { isSidebarOpened, hideSidebar } = useSidebar()
  const { user } = useAuth()
  const {
    unreadCount,
    isLoading: isLoadingNotificationCount,
    setMerchantId,
  } = useNotifications()

  const sidebarLinks: SidebarLinkProps[] = [
    {
      id: 1,
      category: null,
      items: [
        {
          id: 1,
          link: '/',
          icon: FiGrid,
          title: 'Dashboard',
          isActive: pathname === '/',
          isShow: true,
        },
        {
          id: 2,
          link: '/notifications',
          icon: FiBell,
          title: 'Notifications',
          isActive: pathname === '/notifications',
          isShow: user?.role !== 'super_admin',
        },
      ],
    },
    {
      id: 2,
      category: 'Management',
      items: [
        {
          id: 1,
          link: '/merchants',
          icon: TbUserStar,
          title: 'Merchants',
          isActive: pathname === '/merchants',
          isShow: true,
        },
        {
          id: 2,
          link: '/agents',
          icon: TbUserDollar,
          title: 'Agents (B2B)',
          isActive: pathname === '/agents',
          isShow: user?.role === 'super_admin' || user?.role === 'manager',
        },
        {
          id: 3,
          icon: TbUserBolt,
          title: 'Partners',
          isShow: user?.role === 'super_admin' || user?.role === 'manager',
          subItems: [
            {
              id: 1,
              link: '/travel-partners',
              title: 'Travel Partners',
              isActive: pathname === '/travel-partners',
            },
            {
              id: 2,
              link: '/affiliate-partners',
              title: 'Affiliate Partners',
              isActive: pathname === '/affiliate-partners',
            },
          ],
        },
        {
          id: 4,
          link: '/marketplaces',
          icon: LuStore,
          title: 'Marketplaces',
          isActive: pathname === '/marketplaces',
          isShow: user?.role === 'super_admin' || user?.role === 'manager',
        },
        {
          id: 5,
          link: '/users',
          icon: FiUsers,
          title: 'Users',
          isActive: pathname === '/users',
          isShow: user?.role === 'super_admin',
        },
        {
          id: 6,
          link: '/banks',
          icon: AiOutlineBank,
          title: 'Banks',
          isActive: pathname === '/banks',
          isShow:
            user?.role === 'super_admin' ||
            user?.role === 'manager' ||
            user?.role === 'accounting',
        },
      ],
    },
    {
      id: 3,
      category:
        user?.role === 'supervisor' || user?.role === 'reservation_manager'
          ? null
          : 'Partnership Program',
      items: [
        {
          id: 1,
          link: '/partner-performance',
          icon: MdOutlineAutoGraph,
          title: 'Partner Performance',
          isActive: pathname === '/partner-performance',
          isShow: user?.role === 'manager',
        },
        {
          id: 2,
          link: '/affiliate-levels',
          icon: LuTrophy,
          title: 'Affiliate Levels',
          isActive: pathname === '/affiliate-levels',
          isShow: user?.role === 'super_admin' || user?.role === 'manager',
        },
        {
          id: 3,
          link: '/referral-links',
          icon: LuLink2,
          title: 'Referral Links',
          isActive: pathname === '/referral-links',
          isShow: user?.role === 'super_admin' || user?.role === 'manager',
        },
        {
          id: 4,
          icon: BsBoxArrowDown,
          title: 'Withdrawals',
          isShow:
            user?.role === 'super_admin' ||
            user?.role === 'manager' ||
            user?.role === 'accounting',
          subItems: [
            {
              id: 1,
              link: '/withdrawals',
              title: 'Withdrawal Requests',
              isActive: pathname === '/withdrawals',
              isShow: user?.role === 'manager' || user?.role === 'accounting',
            },
            {
              id: 2,
              link: '/withdrawal-settings',
              title: 'Withdrawal Settings',
              isActive: pathname === '/withdrawal-settings',
              isShow: user?.role === 'super_admin' || user?.role === 'manager',
            },
          ],
        },
      ],
    },
  ]

  function handleResize(): void {
    setScreenWidth(window.innerWidth)
  }

  window.addEventListener('resize', handleResize)

  if (!isSidebarOpened && screenWidth <= 930) {
    document.body.classList.remove('overflow-hidden')
  } else if (isSidebarOpened && screenWidth <= 930) {
    document.body.classList.add('overflow-hidden')
  } else {
    document.body.classList.remove('overflow-hidden')
  }

  const sidebarTheme = createTheme({
    sidebar: {
      root: {
        base: `!h-screen ${screenWidth <= 930 && isSidebarOpened ? '!w-screen fixed bg-black/80 z-10' : ''}`,
        inner: `h-full fixed z-20 top-0 bottom-0 border-r border-slate-200 left-0 overflow-y-auto bg-white py-4 scrollbar-hide transition-all ${!isSidebarOpened ? 'px-0' : 'px-3'} ${!isSidebarOpened ? 'opacity-0 w-0' : 'w-64 opacity-100'}`,
      },
      collapse: {
        button:
          'group flex w-full items-center rounded-lg p-2 text-base font-medium text-black transition duration-75 bg-white hover:bg-gray-100 hover:text-primary',
        icon: {
          base: 'h-6 w-6 text-black font-normal transition duration-75 group-hover:text-primary text-sm',
          open: {
            off: '',
            on: '',
          },
        },
        label: {
          base: 'ml-3 flex-1 whitespace-nowrap text-left',
          icon: {
            base: 'h-6 w-6 transition delay-0 ease-in-out',
            open: {
              on: 'rotate-180',
              off: '',
            },
          },
        },
        list: 'space-y-2 py-2 border-l-2 border-slate-200 border-dashed ml-3',
      },
      item: {
        base: 'group flex items-center justify-center rounded-lg p-2 text-base font-medium text-black hover:!bg-gray-100 hover:!text-primary',
        active: '!bg-gray-100 !text-primary',
        label:
          'bg-red-500 rounded-full whitespace-nowrap text-white text-left group-hover:bg-red-500',
        icon: {
          base: 'h-6 w-6 flex-shrink-0 text-black transition duration-75 group-hover:!text-primary',
          active: 'text-primary',
        },
      },
      itemGroup: {
        base: 'mt-4 space-y-2 pt-4 first:mt-0 border-t-0 first:pt-0',
      },
    },
  })

  useEffect(() => {
    setMerchantId(undefined)
  }, [setMerchantId])

  return (
    <FlowbiteSidebar
      id="drawer-navigation"
      theme={sidebarTheme.sidebar}
      onClick={(e) => {
        if ((e.target as HTMLElement).id === 'drawer-navigation') {
          hideSidebar()
        }
      }}
    >
      <Link href="/" className="mb-10 bg-gray-100 rounded-md p-5 block">
        <Image
          src="/images/logo/balirsv-hs-blue.png"
          alt="BALI RSV"
          width={150}
          height={50}
          className="w-52 h-auto"
        />
      </Link>

      {screenWidth <= 930 && (
        <button
          className="fixed text-xl text-white top-2 left-[270px] rounded-full bg-slate-700 w-10 h-10 !border-0 !outline-none"
          onClick={hideSidebar}
        >
          <span>&times;</span>
        </button>
      )}

      <SidebarItems>
        {sidebarLinks.map((sidebarLink) => (
          <SidebarItemGroup key={sidebarLink.id}>
            <React.Fragment>
              {sidebarLink.category !== null && (
                <h4 className="text-slate-500 text-sm font-medium mb-4">
                  {sidebarLink.category}
                </h4>
              )}
            </React.Fragment>

            {sidebarLink.items.map((item) =>
              item.isShow ? (
                <React.Fragment key={item.id}>
                  {item.link ? (
                    <SidebarItem
                      href={item.link}
                      active={item.isActive}
                      icon={item.icon}
                      label={
                        item.title === 'Notifications' &&
                        unreadCount > 0 &&
                        !isLoadingNotificationCount
                          ? String(unreadCount > 99 ? '99+' : unreadCount)
                          : undefined
                      }
                    >
                      {item.title}
                    </SidebarItem>
                  ) : (
                    <SidebarCollapse
                      icon={item.icon}
                      label={item.title}
                      open={item.subItems?.some((subItem) => subItem.isActive)}
                    >
                      {item.subItems
                        ?.filter((subItem) => subItem.isShow !== false)
                        .map((subItem) => (
                          <SidebarItem
                            key={subItem.id}
                            href={subItem.link}
                            active={subItem.isActive}
                            className="!ml-0 pl-4"
                          >
                            {subItem.title}
                          </SidebarItem>
                        ))}
                    </SidebarCollapse>
                  )}
                </React.Fragment>
              ) : null,
            )}
          </SidebarItemGroup>
        ))}
      </SidebarItems>
    </FlowbiteSidebar>
  )
}
