import React, { useMemo } from 'react'

import { Navbar, Text, NavLink, Skeleton, clsx } from '@mantine/core'
import {
  IconServer,
  IconStethoscope,
  IconPresentation,
  IconNotes,
  IconSettings,
  IconFileDownload,
  IconChartBar,
  IconFlame
} from '@tabler/icons-react'
import { Link, useLocation } from 'react-router-dom'

import { useCurCluster, useCurOrg, useUserStore } from '~/hooks/state'
import { clusterDetailTelemetry } from '~/telemetry'

import { NavLinkItem } from './OrgNavBar'

const ClusterNavBar: React.FC = () => {
  const { curOrg } = useCurOrg()
  const { curCluster } = useCurCluster()
  const isInternalUser = useUserStore((state) => state.user?.internal)

  const loc = useLocation()

  const links: NavLinkItem[] = useMemo(() => {
    const indexPath = `/orgs/${curOrg?.id}/clusters/${curCluster?.id}`
    const diagnosisPath = indexPath
    const reportPath = `${indexPath}/report`
    const configPath = `${indexPath}/configurations`
    const settingsPath = `${indexPath}/settings`
    const eventCenterPath = `${indexPath}/event-center`
    const drillTestPath = `${indexPath}/drill-test`
    const filesPath = `${indexPath}/files`
    const metricsPath = `${indexPath}/metrics`
    const topRuPath = `${indexPath}/top-ru`
    const statementPath = `${indexPath}/sql-statement`

    return [
      {
        label: 'Diagnosis',
        icon: IconStethoscope,
        link: diagnosisPath,
        active:
          loc.pathname === diagnosisPath ||
          loc.pathname.startsWith(reportPath) ||
          loc.pathname.startsWith(configPath) ||
          loc.pathname.startsWith(statementPath),
        visible: true
      },
      {
        label: 'Key Metrics',
        icon: IconChartBar,
        link: metricsPath,
        active: loc.pathname.includes(metricsPath),
        visible:
          !!isInternalUser &&
          (curCluster?.computed.isDedicated ||
            curCluster?.computed.isPremium ||
            curCluster?.computed.isStarter ||
            (curCluster?.computed.isEssential &&
              !curCluster?.id?.startsWith('bran-')))
      },
      {
        label: 'Top RU',
        icon: IconFlame,
        link: topRuPath,
        active: loc.pathname.includes(topRuPath),
        visible:
          !!isInternalUser &&
          (curCluster?.computed.isPremium ||
            (curCluster?.computed.isEssential &&
              !curCluster?.id?.startsWith('bran-')))
      },
      {
        label: 'Settings',
        icon: IconSettings,
        link: settingsPath,
        active: loc.pathname === settingsPath,
        visible: curOrg?.isAdmin || curOrg?.isAnalyst || false
      },
      {
        label: 'Event Center',
        icon: IconNotes,
        link: eventCenterPath,
        active: loc.pathname.includes(eventCenterPath),
        visible:
          !!isInternalUser &&
          (curCluster?.computed.isServerless ||
            curCluster?.computed.isDedicated ||
            curCluster?.computed.isPremium ||
            curCluster?.computed.isResourcePool ||
            curCluster?.computed.isByoc)
      },
      {
        label: 'Drill Test',
        icon: IconPresentation,
        link: drillTestPath,
        active: loc.pathname.includes(drillTestPath),
        visible: !!isInternalUser && curCluster?.computed.isDedicated
      },
      {
        label: 'Download',
        icon: IconFileDownload,
        link: filesPath,
        active: loc.pathname === filesPath,
        visible:
          !!isInternalUser &&
          (curCluster?.computed.isDedicated || curCluster?.computed.isPremium)
      }
    ].filter((l) => l.visible) as NavLinkItem[]
  }, [
    loc.pathname,
    curOrg?.id,
    curOrg?.isAdmin,
    curOrg?.isAnalyst,
    curCluster,
    isInternalUser
  ])

  return (
    <Navbar width={{ base: 219 }}>
      <Navbar.Section className='px-6 py-3 border-0 border-b border-gray-200 border-solid'>
        <Skeleton visible={!curOrg || !curCluster}>
          <div className='flex flex-nowrap gap-1'>
            <div className='flex-shrink-0 w-8' />

            <Link to={`/orgs/${curOrg?.id}`}>
              <Text
                fz='xs'
                color='dimmed'
                className='break-all hover:text-cc-primary'
              >
                {curOrg?.name}
              </Text>
              <Text
                fz='xs'
                color='dimmed'
                className='break-all hover:text-cc-primary'
              >
                {curOrg?.externalID}
              </Text>
            </Link>
          </div>

          <div className='flex flex-nowrap gap-1'>
            <IconServer size={32} className='flex-shrink-0' />

            <Text className='font-semibold break-all'>{curCluster?.name}</Text>
          </div>
        </Skeleton>
      </Navbar.Section>

      {curOrg && curCluster && (
        <Navbar.Section className='p-3'>
          {links.map(({ label, icon: Icon, link, active }) => (
            <NavLink
              key={label}
              className={clsx(
                'rounded-lg mb-1',
                !active && 'hover:text-inherit'
              )}
              label={label}
              icon={<Icon strokeWidth={1.5} />}
              component={Link}
              to={link}
              active={active}
              variant='filled'
              onClick={() => clusterDetailTelemetry.clickNav(label)}
            />
          ))}
        </Navbar.Section>
      )}
    </Navbar>
  )
}

export default ClusterNavBar
