'use client'

import React, { useState } from 'react'
import { SvgUserMultipleGroup, SvgTaillessArrowRight } from '../../icons'
import { cn } from '../../utils/cn'
import { Button } from '../Button'
import { useSidebarContext } from '../Navigation'
import { Select, SelectContent, SelectItem, SelectTrigger } from '../Select'
import { Separator } from '../Separator'
import { Typography } from '../Typography'

interface LogoIconProps {
  index: number
  initials: string
  className?: string
}

const logoColor = ['purple-300', 'teal-300']

// Common organization display component
function OrganizationDisplay({
  org,
  color,
}: {
  org: OrgOption
  color: string
}) {
  return (
    <div className="flex items-center gap-3">
      <div
        className="flex h-8 w-8 items-center justify-center rounded"
        style={{
          backgroundColor: `var(--${color})`,
        }}
      >
        <SvgUserMultipleGroup className="h-4 w-4 !text-white" />
      </div>
      <div className="flex flex-col items-start">
        <Typography
          variant="body-semi-xs"
          color="platform-navigation-active"
          className="max-w-[110px] truncate"
        >
          {org.label}
        </Typography>
        <Typography variant="body-xs" color="platform-navigation-muted">
          Organization
        </Typography>
      </div>
    </div>
  )
}

function LogoIcon({ initials, className, index }: LogoIconProps) {
  const colorValue = logoColor[index]

  return (
    <svg
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={className}
    >
      <rect width="24" height="24" rx="2" fill={`var(--${colorValue})`} />
      <text
        x="12"
        y="16"
        textAnchor="middle"
        fill="white"
        fontSize="10"
        fontWeight="600"
        fontFamily="system-ui, -apple-system, sans-serif"
      >
        {initials}
      </text>
    </svg>
  )
}

export interface OrgOption {
  /** Unique identifier for the organization */
  value: string
  /** Display name for the organization */
  label: string
  /** Optional organization logo/icon */
  initials: string
}
export interface OrgSwitcherProps {
  /** Array of organization options */
  organizations: OrgOption[]
  /** Currently selected organization value */
  value?: string
  /** Callback when organization selection changes */
  onValueChange?: (value: string) => void
  /** Default selected organization */
  defaultValue?: string
  /** Whether the select is disabled */
  disabled?: boolean
  /** Additional CSS classes */
  className?: string
}

export function OrgSwitcher({
  organizations,
  value,
  onValueChange,
  defaultValue = organizations[0].value,
  disabled,
  className,
}: OrgSwitcherProps) {
  const [internalValue, setInternalValue] = useState(defaultValue)

  // Try to get sidebar context, but don't fail if it's not available
  const sidebarContext = useSidebarContext()

  const currentValue = value !== undefined ? value : internalValue

  const handleValueChange = (newValue: string) => {
    // Set active item optimistically if sidebar context is available
    if (sidebarContext) {
      sidebarContext.setActiveItem(newValue)
      // Close any open submenus
      sidebarContext.setOpenSubmenu(null)
    }

    if (value === undefined) {
      setInternalValue(newValue)
    }
    onValueChange?.(newValue)

    sidebarContext?.setOpenMobile(false)
  }
  const selectedOrg =
    organizations.find((org) => org.value === currentValue) || organizations[0]

  // Get the index of the selected organization for color assignment
  const selectedOrgIndex = organizations.findIndex(
    (org) => org.value === currentValue,
  )
  const selectedOrgColor = logoColor[selectedOrgIndex] || logoColor[0]

  // If only one organization, render as a button that navigates immediately
  if (organizations.length === 1) {
    const singleOrg = organizations[0]
    const singleOrgColor = logoColor[0]

    const handleClick = () => {
      handleValueChange(singleOrg.value)
    }

    // If sidebar context is available and it's an internal link, use renderLink
    if (sidebarContext && singleOrg.value.startsWith('/')) {
      return sidebarContext.renderLink({
        href: singleOrg.value,
        className: '!outline-none focus-visible:outline-none group',
        children: (
          <div
            className={cn(
              'flex w-full cursor-pointer items-center justify-between rounded bg-input p-2 hover:bg-platform-navigation-hover focus-visible:outline-none group-focus-visible:bg-platform-navigation-hover md:w-[196px] md:max-w-[196px]',
              className,
            )}
            onClick={handleClick}
          >
            <OrganizationDisplay org={singleOrg} color={singleOrgColor} />
            <SvgTaillessArrowRight className="mr-2 !h-3 !w-3 !text-input-muted-foreground" />
          </div>
        ),
      })
    }

    // Fallback to button for external links or when outside SidebarProvider
    return (
      <Button
        variant="ghost"
        className={cn(
          'w-full justify-between rounded bg-input p-2 hover:bg-platform-navigation-hover focus-visible:bg-platform-navigation-hover focus-visible:outline-none md:w-[196px] md:max-w-[196px]',
          className,
        )}
        onClick={handleClick}
        disabled={disabled}
      >
        <OrganizationDisplay org={singleOrg} color={singleOrgColor} />
        <SvgTaillessArrowRight className="mr-2 !h-3 !w-3 !text-input-muted-foreground" />
      </Button>
    )
  }

  return (
    <Select
      value={currentValue}
      onValueChange={handleValueChange}
      disabled={disabled}
    >
      <SelectTrigger
        className={cn(
          'h-auto border-none p-2 !outline-none focus-visible:bg-platform-navigation-hover focus-visible:outline-none [&_[data-slot=select-icon]]:mr-2 [&_[data-slot=select-icon]]:size-3',
          className,
        )}
      >
        <OrganizationDisplay org={selectedOrg} color={selectedOrgColor} />
      </SelectTrigger>

      <SelectContent
        side="top"
        className="border-border-active"
        data-org-switcher="true"
      >
        {organizations.map((org, index) => (
          <React.Fragment key={org.value}>
            <SelectItem
              value={org.value}
              Icon={<LogoIcon index={index} initials={org.initials} />}
            >
              {org.label}
            </SelectItem>
            {index < organizations.length - 1 && (
              <Separator className="bg-border-active" />
            )}
          </React.Fragment>
        ))}
      </SelectContent>
    </Select>
  )
}
