'use client'

import { formatCNPJ } from '@brazilian-utils/brazilian-utils'
import {
  BadgeCheckIcon,
  CheckIcon,
  ChevronsUpDownIcon,
  PlusIcon
} from 'lucide-react'
import { createContext, use } from 'react'
import { useLocation } from 'react-router'

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar
} from '@repo/ui/components/ui/sidebar'
import { initials } from '@repo/ui/lib/utils'
import { Link } from 'react-router'

import type { Workspace, WorkspaceContextProps } from '@/middleware/workspace'

const WorkspaceContext = createContext<WorkspaceContextProps | null>(null)

export function useWorksapce() {
  const ctx = use(WorkspaceContext)

  if (!ctx) {
    throw new Error('WorkspaceContext is null')
  }

  return ctx
}

export function WorkspaceProvider({
  children,
  ...props
}: WorkspaceContextProps & {
  children: React.ReactNode
}) {
  return <WorkspaceContext value={props}>{children}</WorkspaceContext>
}

export function WorkspaceSwitcher() {
  const location = useLocation()
  const { isMobile, state } = useSidebar()
  const { activeWorkspace, workspaces, subscription } = useWorksapce()
  const [, fragment, _] = location.pathname.slice(1).split('/')

  const onSelect = (workspace: Workspace) => {
    window.location.assign(`/${workspace.id}/${fragment}`)
  }

  return (
    <SidebarMenu className="group-data-[state=expanded]:p-2">
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground bg-secondary hover:bg-secondary/80 border cursor-pointer"
            >
              <div
                className="aria-expanded:border flex aspect-square size-8 items-center justify-center rounded-lg relative"
                aria-expanded={state === 'expanded'}
              >
                {subscription ? (
                  <BadgeCheckIcon className="fill-blue-500 stroke-white absolute size-4 dark:size-3.5 -top-1.5 -right-1.5" />
                ) : null}

                {initials(activeWorkspace.name)}
              </div>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">
                  {activeWorkspace.name}
                </span>
                <span className="truncate text-xs text-muted-foreground">
                  {formatCNPJ(activeWorkspace.cnpj)}
                </span>
              </div>
              <ChevronsUpDownIcon className="ml-auto" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>

          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            align="start"
            side={isMobile ? 'bottom' : 'right'}
            sideOffset={4}
          >
            <DropdownMenuLabel className="text-muted-foreground text-xs">
              Empresas
            </DropdownMenuLabel>

            {workspaces.map((workspace, index) => (
              <DropdownMenuItem
                key={index}
                onClick={() => onSelect(workspace)}
                className="group gap-2 p-2 cursor-pointer aria-selected:pointer-events-none"
                aria-selected={workspace.id === activeWorkspace?.id}
              >
                <div className="flex size-8 items-center justify-center rounded-lg border">
                  {initials(workspace?.name)}
                </div>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">
                    {workspace?.name}
                  </span>
                  <span className="truncate text-xs text-muted-foreground">
                    {formatCNPJ(workspace?.cnpj)}
                  </span>
                </div>
                <DropdownMenuShortcut className="not-group-aria-selected:hidden">
                  <CheckIcon />
                </DropdownMenuShortcut>
              </DropdownMenuItem>
            ))}

            <DropdownMenuSeparator />

            <DropdownMenuItem className="gap-2 p-2 cursor-pointer" asChild>
              <Link to="/setup">
                <div className="flex size-6 items-center justify-center rounded-md border bg-transparent">
                  <PlusIcon className="size-4" />
                </div>
                <div className="text-muted-foreground font-medium">
                  Adicionar empresa
                </div>
              </Link>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}
