'use client'

import React, { useEffect, useState } from 'react'
import {
  createTheme,
  Sidebar as FlowbiteSidebar,
  SidebarCollapse,
  SidebarItem,
  SidebarItemGroup,
  SidebarItems,
} from 'flowbite-react'
import {
  FiBell,
  FiCalendar,
  FiFileText,
  FiGrid,
  FiLayers,
} from 'react-icons/fi'
import { usePathname } from 'next/navigation'
import Image from 'next/image'
import { TbCreditCardRefund } from 'react-icons/tb'
import Link from 'next/link'
import { LuMegaphone, LuMonitor } from 'react-icons/lu'
import { IoBanOutline } from 'react-icons/io5'

import { useSidebar } from '@/lib/context/SidebarContext'
import { useMerchant } from '@/lib/context/MerchantContext'
import { useAuth } from '@/lib/context/AuthContext'
import { useOrderConfirmation } from '@/lib/context/OrderConfirmationContext'
import { useNotifications } from '@/lib/context/NotificationContext'
import { MdOutlineEventSeat } from 'react-icons/md'

interface SidebarItemProps {
  id: number
  link?: string
  icon?: React.FC<React.SVGProps<SVGSVGElement>> | undefined
  title: string
  isActive?: boolean
  isShow?: boolean
  key?: string
  subItems?: {
    id: number
    key?: string
    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 { isLoading, counts } = useOrderConfirmation()
  const pathname = usePathname()
  const { isSidebarOpened, hideSidebar } = useSidebar()
  const { merchant } = useMerchant()
  const { user } = useAuth()
  const {
    unreadCount,
    isLoading: isLoadingNotificationCount,
    setMerchantId,
  } = useNotifications()

  const sidebarLinks: SidebarLinkProps[] = [
    {
      id: 1,
      category: null,
      items: [
        {
          id: 1,
          link: `/merchant-dashboard/${merchant?.id}`,
          icon: FiGrid,
          title: 'Dashboard',
          isActive: pathname === `/merchant-dashboard/${merchant?.id}`,
          isShow: user?.role !== 'super_admin',
        },
        {
          id: 2,
          link: `/merchant-dashboard/${merchant?.id}/notifications`,
          icon: FiBell,
          title: 'Notifications',
          key: 'notifications',
          isActive:
            pathname === `/merchant-dashboard/${merchant?.id}/notifications`,
          isShow: user?.role !== 'super_admin',
        },
        {
          id: 3,
          icon: FiCalendar,
          title: 'Order Confirmations',
          key: 'order-confirmations',
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'supervisor' ||
            user?.role === 'reservation_manager',
          subItems: [
            {
              id: 1,
              link: `/merchant-dashboard/${merchant?.id}/order-confirmations/fastboat`,
              title: 'Fast Boats',
              key: 'fastboat-order-confirmations',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/order-confirmations/fastboat`,
            },
            {
              id: 2,
              link: `/merchant-dashboard/${merchant?.id}/order-confirmations/tour-package`,
              title: 'Packages',
              key: 'tour-package-order-confirmations',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/order-confirmations/tour-package`,
            },
            {
              id: 3,
              link: `/merchant-dashboard/${merchant?.id}/order-confirmations/activity`,
              title: 'Experiences',
              key: 'activity-order-confirmations',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/order-confirmations/activity`,
            },
          ],
        },
      ],
    },
    {
      id: 2,
      category: 'OPERATIONS',
      items: [
        {
          id: 1,
          link: `/merchant-dashboard/${merchant?.id}/orders`,
          icon: FiLayers,
          title: 'Orders',
          isActive: pathname === `/merchant-dashboard/${merchant?.id}/orders`,
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'supervisor' ||
            user?.role === 'reservation_manager',
        },
        {
          id: 2,
          link: `/merchant-dashboard/${merchant?.id}/bookings`,
          icon: LuMonitor,
          title: 'Offline Bookings',
          isActive: pathname === `/merchant-dashboard/${merchant?.id}/bookings`,
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'supervisor' ||
            user?.role === 'reservation_manager',
        },
        {
          id: 3,
          icon: TbCreditCardRefund,
          title: 'Refunds',
          link: `/merchant-dashboard/${merchant?.id}/refunds`,
          isActive: pathname === `/merchant-dashboard/${merchant?.id}/refunds`,
          isShow: user?.role !== 'reservation_manager',
        },
        {
          id: 4,
          icon: FiCalendar,
          title: 'Reschedules',
          link: `/merchant-dashboard/${merchant?.id}/reschedules`,
          isActive:
            pathname === `/merchant-dashboard/${merchant?.id}/reschedules`,
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'supervisor' ||
            user?.role === 'reservation_manager',
        },
        {
          id: 5,
          icon: FiFileText,
          title: 'Sales Report',
          isShow:
            user?.role === 'accounting' ||
            user?.role === 'manager' ||
            user?.role === 'general_manager',
          subItems: [
            {
              id: 1,
              link: `/merchant-dashboard/${merchant?.id}/sales`,
              title: 'All Transactions',
              isActive:
                pathname === `/merchant-dashboard/${merchant?.id}/sales`,
            },
            {
              id: 2,
              link: `/merchant-dashboard/${merchant?.id}/fastboat-sales`,
              title: 'Fast Boats',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/fastboat-sales`,
            },
            {
              id: 3,
              link: `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
              title: 'Packages',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
            },
            {
              id: 4,
              link: `/merchant-dashboard/${merchant?.id}/activity-sales`,
              title: 'Experiences',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/activity-sales`,
            },
            {
              id: 5,
              link: `/merchant-dashboard/${merchant?.id}/transport-sales`,
              title: 'Transports',
              isActive:
                pathname ===
                `/merchant-dashboard/${merchant?.id}/transport-sales`,
            },
          ],
        },
      ],
    },
    {
      id: 3,
      category:
        user?.role === 'manager' ||
        user?.role === 'general_manager' ||
        user?.role === 'reservation_manager'
          ? 'MANAGEMENT'
          : null,
      items: [
        {
          id: 1,
          link: `/merchant-dashboard/${merchant?.id}/announcements`,
          icon: LuMegaphone,
          title: 'Announcements',
          isActive:
            pathname === `/merchant-dashboard/${merchant?.id}/announcements`,
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'reservation_manager',
        },
        {
          id: 2,
          link: `/merchant-dashboard/${merchant?.id}/fastboat-seat-availabilities`,
          icon: MdOutlineEventSeat,
          title: 'Blocked Seats',
          isActive:
            pathname ===
            `/merchant-dashboard/${merchant?.id}/fastboat-seat-availabilities`,
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'reservation_manager',
        },
        {
          id: 3,
          link: `/merchant-dashboard/${merchant?.id}/fastboat-disabled-operations`,
          icon: IoBanOutline,
          title: 'Disabled Operations',
          isActive:
            pathname ===
            `/merchant-dashboard/${merchant?.id}/fastboat-disabled-operations`,
          isShow:
            user?.role === 'manager' ||
            user?.role === 'general_manager' ||
            user?.role === 'reservation_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',
      },
    },
  })

  function getLabel(item: SidebarItemProps) {
    switch (item.key) {
      case 'fastboat-order-confirmations':
        return !isLoading && counts?.fastboat?.ready_for_confirmation > 0
          ? counts.fastboat.ready_for_confirmation
          : null
      case 'tour-package-order-confirmations':
        return !isLoading && counts?.tourPackage?.ready_for_confirmation > 0
          ? counts.tourPackage.ready_for_confirmation
          : null
      case 'activity-order-confirmations':
        return !isLoading && counts?.activity?.ready_for_confirmation > 0
          ? counts.activity.ready_for_confirmation
          : null
      case 'notifications':
        return unreadCount > 0 && !isLoadingNotificationCount
          ? unreadCount > 99
            ? '99+'
            : unreadCount
          : null
      default:
        return null
    }
  }

  // Set merchant in Notifications Context
  useEffect(() => {
    if (merchant) {
      setMerchantId(merchant.id)
    }
  }, [merchant, setMerchantId])

  return (
    <FlowbiteSidebar
      id="drawer-navigation"
      theme={sidebarTheme.sidebar}
      onClick={(e) => {
        if ((e.target as HTMLElement).id === 'drawer-navigation') {
          hideSidebar()
        }
      }}
    >
      <Link
        href={`/merchant-dashboard/${merchant?.id}`}
        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}>
            {sidebarLink.category && (
              <h4 className="text-slate-500 text-sm font-medium mb-4">
                {sidebarLink.category}
              </h4>
            )}

            {sidebarLink.items.map((item) =>
              item.isShow ? (
                <React.Fragment key={item.id}>
                  {item.link ? (
                    <SidebarItem
                      href={item.link}
                      active={item.isActive}
                      icon={item.icon}
                      label={
                        getLabel(item) ? String(getLabel(item)) : 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"
                          label={
                            getLabel(subItem)
                              ? String(getLabel(subItem))
                              : undefined
                          }
                        >
                          {subItem.title}
                        </SidebarItem>
                      ))}
                    </SidebarCollapse>
                  )}
                </React.Fragment>
              ) : null,
            )}
          </SidebarItemGroup>
        ))}
      </SidebarItems>
    </FlowbiteSidebar>
  )
}
