'use client'

import { formatCNPJ } from '@brazilian-utils/brazilian-utils'
import { CheckIcon, ChevronsUpDownIcon, PlusIcon } from 'lucide-react'
import { createContext, useContext, useState } from 'react'
import { useLocation, useParams } 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'

export type Workspace = {
  id: string
  name: string
  cnpj: string
}

type WorkspaceContextProps = {
  workspaces: Workspace[]
  activeWorkspace: Workspace
  setActiveWorkspace: React.Dispatch<React.SetStateAction<Workspace | null>>
}

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

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

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

  return ctx
}

export function WorkspaceProvider({
  workspaces,
  children
}: {
  workspaces: Workspace[]
  children: React.ReactNode
}) {
  const { orgid } = useParams()
  const [activeWorkspace, setActiveWorkspace] = useState<Workspace | any>(
    () => workspaces.find(({ id }) => id === orgid) || {}
  )

  return (
    <WorkspaceContext
      value={{ workspaces, activeWorkspace, setActiveWorkspace }}
    >
      {children}
    </WorkspaceContext>
  )
}

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

  const onSelect = (workspace: Workspace) => {
    setActiveWorkspace(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"
                aria-expanded={state === 'expanded'}
              >
                {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>
  )
}
