'use client'

import { useGetSites } from '@/features/site'
import { ProgressBarLink, ThemeSwitch } from '@/shared/components'
import { Badge } from '@/shared/components/ui/badge'
import { Button } from '@/shared/components/ui/button'
import { ButtonGroup } from '@/shared/components/ui/button-group'
import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerTitle,
  DrawerTrigger
} from '@/shared/components/ui/drawer'
import { Skeleton } from '@/shared/components/ui/skeleton'
import { Spinner } from '@/shared/components/ui/spinner'
import { buttonVariants } from '@/shared/components/ui/variants/button'
import { useSignout } from '@/features/auth'
import { useGetNotificationsCounts } from '@/features/notification'
import { SiteUrl } from '@/shared/lib/icon'
import { cn } from '@/shared/lib/utils'
import {
  HomeIcon,
  BellRingIcon,
  MenuIcon,
  PlusIcon,
  SettingsIcon,
  LifeBuoyIcon,
  ChevronRightIcon,
  SunMoonIcon,
  ChevronsUpDownIcon,
  DoorOpenIcon
} from 'lucide-react'
import { usePathname, useRouter } from 'next/navigation'
import { useEffect, useState, useTransition } from 'react'
import { toast } from 'sonner'

export const AppMobileNav = () => {
  const pathname = usePathname()
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const { data: sites, isPending, isSuccess } = useGetSites()
  const signout = useSignout()
  const [isPendingG, startTransition] = useTransition()
  const { data: counts, isSuccess: isSuc } = useGetNotificationsCounts()

  const handleSignout = () => {
    startTransition(async () => {
      toast.info('Выход...')
      await signout()
      router.refresh()
    })
  }

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setOpen(false)
  }, [pathname])

  return (
    <Drawer open={open} onOpenChange={setOpen}>
      <div className='md:hidden fixed bottom-0 z-10 pb-4 px-6 w-full'>
        <div className='container rounded-2xl p-2 border mx-auto bg-secondary/60 backdrop-blur-lg'>
          <div className='grid grid-cols-3 items-center'>
            <ProgressBarLink
              href='/app'
              className={cn(
                'flex items-center flex-col text-xs gap-0.5 text-foreground',
                pathname === '/app' && 'text-primary'
              )}
            >
              <HomeIcon className='size-6' />
              Главная
            </ProgressBarLink>
            <ProgressBarLink
              href='/app/notifications'
              className={cn(
                'flex items-center flex-col text-xs gap-0.5 text-foreground relative',
                pathname.startsWith('/app/notifications') && 'text-primary'
              )}
            >
              <BellRingIcon className='size-6' />
              Уведомления
              {isSuc && counts.total > 0 && (
                <Badge className='absolute top-0 right-0'>
                  {counts?.total}
                </Badge>
              )}
            </ProgressBarLink>
            <DrawerTrigger asChild>
              <button
                type='button'
                className={cn(
                  'flex items-center flex-col text-xs gap-0.5 text-foreground'
                )}
              >
                <MenuIcon />
                Меню
              </button>
            </DrawerTrigger>
          </div>
        </div>
        <DrawerContent className='h-full'>
          <DrawerTitle className='sr-only'>Меню</DrawerTitle>
          <DrawerDescription className='sr-only'>
            Все меню располагается здесь
          </DrawerDescription>
          <div className='flex flex-col overflow-y-auto gap-8 my-4 px-4 h-full'>
            <ButtonGroup orientation='vertical' className='w-full *:h-12!'>
              <ProgressBarLink
                href='/app'
                className={cn(
                  buttonVariants({ variant: 'secondary', size: 'lg' }),
                  pathname === '/app' && 'text-primary'
                )}
              >
                <HomeIcon />
                Главная
                <ChevronRightIcon className='ml-auto' />
              </ProgressBarLink>
              <ProgressBarLink
                href='/app/notifications'
                className={cn(
                  buttonVariants({ variant: 'secondary', size: 'lg' }),
                  pathname.startsWith('/app/notifications') && 'text-primary'
                )}
              >
                <BellRingIcon />
                Уведомления
                <ChevronRightIcon className='ml-auto' />
              </ProgressBarLink>
              <ProgressBarLink
                href='/app/settings'
                className={cn(
                  buttonVariants({ variant: 'secondary', size: 'lg' }),
                  pathname === '/app/settings' && 'text-primary'
                )}
              >
                <SettingsIcon />
                Настройки
                <ChevronRightIcon className='ml-auto' />
              </ProgressBarLink>
              <ThemeSwitch variant='secondary' size='lg'>
                <SunMoonIcon />
                Тема
                <ChevronsUpDownIcon className='ml-auto' />
              </ThemeSwitch>
            </ButtonGroup>
            <ButtonGroup orientation='vertical' className='w-full *:h-12!'>
              {isPending && (
                <>
                  <Skeleton className='w-full rounded-md h-9' />
                  <Skeleton className='w-full rounded-md h-9' />
                  <Skeleton className='w-full rounded-md h-9' />
                </>
              )}
              {isSuccess &&
                sites.map((site) => (
                  <ProgressBarLink
                    key={site.id}
                    href={`/app/sites/${site.id}`}
                    className={cn(
                      buttonVariants({ variant: 'secondary', size: 'lg' }),
                      pathname === `/app/sites/${site.id}` && 'text-primary'
                    )}
                  >
                    <img
                      src={SiteUrl(site.domain, 16)}
                      alt='site icon'
                      width={16}
                      height={16}
                    />
                    {site.title}
                    <ChevronRightIcon className='ml-auto' />
                  </ProgressBarLink>
                ))}
              <ProgressBarLink
                href='/app/sites/add'
                className={cn(
                  buttonVariants({ variant: 'secondary', size: 'lg' }),
                  pathname === '/app/sites/add' && 'text-primary'
                )}
              >
                <PlusIcon />
                Добавить сайт
                <ChevronRightIcon className='ml-auto' />
              </ProgressBarLink>
            </ButtonGroup>
            <ButtonGroup orientation='vertical' className='w-full *:h-12!'>
              <Button
                onClick={() => {
                  if (typeof window !== 'undefined') {
                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                    // @ts-ignore
                    window?.BX?.LiveChat?.openLiveChat()
                  }
                }}
                className={buttonVariants({ variant: 'secondary', size: 'lg' })}
              >
                <LifeBuoyIcon />
                Поддержка
              </Button>
            </ButtonGroup>
            <ButtonGroup
              orientation='vertical'
              className='mt-auto w-full *:h-12!'
            >
              <Button
                disabled={isPendingG}
                variant='destructive'
                size='lg'
                onClick={handleSignout}
              >
                <DoorOpenIcon />
                Выйти
                {isPendingG ? (
                  <Spinner className='ml-auto' />
                ) : (
                  <span className='ml-auto' />
                )}
              </Button>
            </ButtonGroup>
          </div>
        </DrawerContent>
      </div>
    </Drawer>
  )
}
