import { LOCAL_STORAGE_KEYS } from 'common'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { cn } from 'ui'

import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { IS_PLATFORM } from '@/lib/constants'
import { useTrack } from '@/lib/telemetry/track'

export const HomeIcon = ({ className }: { className?: string }) => {
  const { data: selectedOrganization } = useSelectedOrganizationQuery()
  const { data: organizations } = useOrganizationsQuery()
  const track = useTrack()

  const largeLogo = useIsFeatureEnabled('branding:large_logo')

  const router = useRouter()
  const [lastVisitedOrganization] = useLocalStorageQuery(
    LOCAL_STORAGE_KEYS.LAST_VISITED_ORGANIZATION,
    ''
  )

  const getDefaultOrgRedirect = () => {
    if (lastVisitedOrganization) return `/org/${lastVisitedOrganization}`
    if (selectedOrganization?.slug) return `/org/${selectedOrganization.slug}`
    if (organizations && organizations.length > 0) return `/org/${organizations[0].slug}`
    return '/organizations'
  }

  const href = IS_PLATFORM ? getDefaultOrgRedirect() : '/project/default'

  return (
    <Link
      href={href}
      onClick={() => track('header_home_logo_clicked')}
      className={cn('items-center justify-center shrink-0 flex', className)}
    >
      <img
        alt="Briven"
        src={`${router.basePath}/img/briven-logo.svg`}
        className={largeLogo ? 'h-[20px]' : 'h-[18px]'}
      />
    </Link>
  )
}
