'use client'

import { formatCNPJ } from '@brazilian-utils/brazilian-utils'
import { CheckIcon, ChevronsUpDownIcon, PlusIcon } from 'lucide-react'
import { 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,
  SidebarRail,
  useSidebar
} from '@repo/ui/components/ui/sidebar'
import { initials } from '@repo/ui/lib/utils'

type Org = {
  id: string
  name: string
  cnpj: string
}

export function OrgSwitcher({ orgs }: { orgs: Org[] }) {
  const location = useLocation()
  const { isMobile, state } = useSidebar()
  const { orgid } = useParams()
  const org = orgs.find((org) => org.id === orgid) as Org
  const [activeOrg, setActiveOrg] = useState<Org>(org)
  const [, fragment, _] = location.pathname.slice(1).split('/')

  const onSelect = (org: Org) => {
    setActiveOrg(org)
    window.location.assign(`/${org.id}/${fragment}`)
  }

  return (
    <SidebarMenu>
      <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(activeOrg?.name)}
              </div>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{activeOrg?.name}</span>
                <span className="truncate text-xs text-muted-foreground">
                  {formatCNPJ(activeOrg?.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>
            {orgs.map((org, index) => (
              <DropdownMenuItem
                key={index}
                onClick={() => onSelect(org)}
                className="group gap-2 p-2 cursor-pointer aria-selected:pointer-events-none"
                aria-selected={org.id === activeOrg.id}
              >
                <div className="flex size-8 items-center justify-center rounded-lg border">
                  {initials(org?.name)}
                </div>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">{org?.name}</span>
                  <span className="truncate text-xs text-muted-foreground">
                    {formatCNPJ(org?.cnpj)}
                  </span>
                </div>
                <DropdownMenuShortcut className="not-group-aria-selected:hidden">
                  <CheckIcon />
                </DropdownMenuShortcut>
              </DropdownMenuItem>
            ))}
            <DropdownMenuSeparator />
            <DropdownMenuItem className="gap-2 p-2">
              <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>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
      <SidebarRail />
    </SidebarMenu>
  )
}
