import {
  mdiAccountCircleOutline,
  mdiChartTimelineVariant,
  mdiHeartPulse,
  mdiLeafCircle,
  mdiMenu,
  mdiTargetVariant,
  mdiViewDashboardOutline,
  mdiWaterOutline,
} from '@mdi/js'
import Link from 'next/link'
import { useRouter } from 'next/router'
import React, { useEffect, useState } from 'react'
import { hasCompletedApexOnboarding } from '../helpers/apexOnboarding'
import { hasPermission } from '../helpers/userPermissions'
import { useAppSelector } from '../stores/hooks'
import BaseIcon from './BaseIcon'

type Props = {
  onMenuClick: () => void
  isMenuOpen: boolean
}

type MobileNavItem = {
  key: string
  href?: string
  label: string
  icon: string
  matchers: string[]
  onClick?: () => void
}

function isRouteActive(pathname: string, matchers: string[]) {
  return matchers.some(
    (matcher) => pathname === matcher || pathname.startsWith(`${matcher}/`),
  )
}

function getItemClass(active: boolean, isPulse: boolean) {
  if (isPulse) {
    return active
      ? 'bg-[#4A6741] text-white shadow-md dark:bg-emerald-700 dark:text-white'
      : 'bg-[#EDF4EA] text-[#4A6741] dark:bg-dark-800 dark:text-emerald-300'
  }

  return active
    ? 'bg-[#EDF4EA] text-[#4A6741] dark:bg-dark-800 dark:text-emerald-300'
    : 'text-[#7E725E] dark:text-slate-400'
}

export default function MobileBottomNav({ onMenuClick, isMenuOpen }: Props) {
  const router = useRouter()
  const { currentUser } = useAppSelector((state) => state.auth)
  const [onboardingComplete, setOnboardingComplete] = useState(false)

  useEffect(() => {
    setOnboardingComplete(hasCompletedApexOnboarding(currentUser?.id))
  }, [currentUser?.id])

  const focusItem: MobileNavItem =
    onboardingComplete && hasPermission(currentUser, 'READ_GOALS')
      ? {
          key: 'goals',
          href: '/goals/goals-list',
          label: 'Goals',
          icon: mdiTargetVariant,
          matchers: ['/goals'],
        }
      : {
          key: 'setup',
          href: '/onboarding',
          label: 'Setup',
          icon: mdiAccountCircleOutline,
          matchers: ['/onboarding'],
        }

  let trackingItem: MobileNavItem = {
    key: 'today',
    href: '/daily-pulse',
    label: 'Today',
    icon: mdiChartTimelineVariant,
    matchers: ['/daily-pulse'],
  }

  if (hasPermission(currentUser, 'READ_HEALTH_METRICS')) {
    trackingItem = {
      key: 'vitals',
      href: '/health_metrics/health_metrics-list',
      label: 'Vitals',
      icon: mdiChartTimelineVariant,
      matchers: ['/health_metrics'],
    }
  } else if (hasPermission(currentUser, 'READ_CONDITIONS')) {
    trackingItem = {
      key: 'care',
      href: '/conditions/conditions-list',
      label: 'Care',
      icon: mdiLeafCircle,
      matchers: ['/conditions'],
    }
  } else if (hasPermission(currentUser, 'READ_HYDRATION_LOGS')) {
    trackingItem = {
      key: 'hydrate',
      href: '/hydration_logs/hydration_logs-list',
      label: 'Hydrate',
      icon: mdiWaterOutline,
      matchers: ['/hydration_logs'],
    }
  }

  const navItems: MobileNavItem[] = [
    {
      key: 'home',
      href: '/dashboard',
      label: 'Home',
      icon: mdiViewDashboardOutline,
      matchers: ['/dashboard'],
    },
    {
      key: 'pulse',
      href: '/daily-pulse',
      label: 'Pulse',
      icon: mdiHeartPulse,
      matchers: ['/daily-pulse'],
    },
    focusItem,
    trackingItem,
    {
      key: 'menu',
      label: 'Menu',
      icon: mdiMenu,
      matchers: [],
      onClick: onMenuClick,
    },
  ]

  return (
    <div className="fixed inset-x-0 bottom-0 z-30 px-3 pb-3 pt-2 lg:hidden">
      <div className="mx-auto flex max-w-md items-center gap-1 rounded-3xl border border-stone-200 bg-[#FFF9F0]/95 p-2 shadow-lg backdrop-blur-md dark:border-dark-700 dark:bg-dark-900/95">
        {navItems.map((item) => {
          const isActive =
            item.key === 'menu'
              ? isMenuOpen
              : isRouteActive(router.pathname, item.matchers)
          const isPulse = item.key === 'pulse'
          const sharedClassName = [
            'flex min-w-0 flex-1 flex-col items-center justify-center gap-1 rounded-2xl px-1 py-2 text-[11px] font-semibold transition-all duration-150',
            getItemClass(isActive, isPulse),
          ].join(' ')
          const content = (
            <>
              <BaseIcon path={item.icon} size={isPulse ? 22 : 20} />
              <span className="truncate text-center leading-none">{item.label}</span>
            </>
          )

          if (item.href) {
            return (
              <Link
                key={item.key}
                href={item.href}
                aria-current={isActive ? 'page' : undefined}
                className={sharedClassName}
              >
                {content}
              </Link>
            )
          }

          return (
            <button
              key={item.key}
              type="button"
              aria-pressed={isActive}
              aria-label={item.label}
              className={sharedClassName}
              onClick={item.onClick}
            >
              {content}
            </button>
          )
        })}
      </div>
    </div>
  )
}
