'use client'

import React, { useState } from 'react'
import {
  createTheme,
  Sidebar as FlowbiteSidebar,
  SidebarCollapse,
  SidebarItem,
  SidebarItemGroup,
  SidebarItems,
} from 'flowbite-react'
import { FiBell, FiGrid, FiLayers } from 'react-icons/fi'
import { usePathname } from 'next/navigation'
import Image from 'next/image'
import { LuLink2 } from 'react-icons/lu'
import Link from 'next/link'
import { BsBoxArrowDown } from 'react-icons/bs'
import { MdOutlineWidgets } from 'react-icons/md'

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

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
  }[]
}

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 { unreadCount, isLoading: isLoadingNotificationCount } =
    useNotifications()
  const { user } = useAuth()

  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: true,
        },
        {
          id: 3,
          link: '/transactions',
          icon: FiLayers,
          title: 'Transactions',
          isActive: pathname === '/transactions',
          isShow: true,
        },
        {
          id: 4,
          link: '/withdrawals',
          icon: BsBoxArrowDown,
          title: 'Withdrawals',
          isActive: pathname === '/withdrawals',
          isShow: true,
        },
        {
          id: 5,
          link: '/referral-links',
          icon: LuLink2,
          title: 'Referral Links',
          isActive: pathname === '/referral-links',
          isShow: true,
        },
        {
          id: 6,
          link: '/business-widgets',
          icon: MdOutlineWidgets,
          title: 'Business Widgets',
          isActive: pathname === '/business-widgets',
          isShow: user?.partner_type === 'travel',
        },
      ],
    },
  ]

  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 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',
      },
    },
  })

  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-67.5 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?.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>
  )
}
