import React from 'react'
import { Avatar } from './Avatar'
import { DropdownMenu, type DropdownMenuItemProps } from './DropdownMenu'
import { cn } from '@/utils/cn'

export interface UserMenuUser {
  name?: string | null
  email: string
  avatarUrl?: string | null
}

export interface UserMenuIntegration {
  label: string
  status: 'connected' | 'disconnected' | 'warning'
  helperText?: string
}

export interface UserMenuExtraItem {
  label: string
  leftIcon?: string
  description?: string
  tone?: DropdownMenuItemProps['tone']
  disabled?: boolean
  onSelect?: () => void
}

export interface UserMenuProps {
  user: UserMenuUser
  integrations?: UserMenuIntegration[]
  placement?: 'sidebar' | 'topbar'
  onSettingsClick?: () => void
  onLogout?: () => void
  extraItems?: UserMenuExtraItem[]
  className?: string
}

const integrationConfig: Record<
  UserMenuIntegration['status'],
  { label: string; dot: string; text: string; avatarStatus: 'online' | 'offline' | 'warning' }
> = {
  connected: {
    label: '연결됨',
    dot: 'bg-teal-500',
    text: 'text-teal-700',
    avatarStatus: 'online',
  },
  disconnected: {
    label: '미연결',
    dot: 'bg-slate-300',
    text: 'text-slate-500',
    avatarStatus: 'offline',
  },
  warning: {
    label: '확인 필요',
    dot: 'bg-amber-500',
    text: 'text-amber-700',
    avatarStatus: 'warning',
  },
}

const getAvatarStatus = (integrations: UserMenuIntegration[]): 'online' | 'offline' | 'warning' | 'none' => {
  if (integrations.some((integration) => integration.status === 'warning')) return 'warning'
  if (integrations.some((integration) => integration.status === 'connected')) return 'online'
  if (integrations.length > 0) return 'offline'
  return 'none'
}

export const UserMenu: React.FC<UserMenuProps> = ({
  user,
  integrations = [],
  placement = 'sidebar',
  onSettingsClick,
  onLogout,
  extraItems = [],
  className,
}) => {
  const displayName = user.name || user.email
  const avatarStatus = getAvatarStatus(integrations)
  const isSidebar = placement === 'sidebar'

  const trigger = (
    <button
      type="button"
      className={cn(
        'flex min-w-0 items-center gap-2.5 rounded-[10px] border border-slate-200 bg-white text-left transition-all duration-150',
        'hover:border-teal-200 hover:bg-teal-50/30 hover:shadow-soft-md',
        'focus:outline-2 focus:outline-teal-400 focus:outline-offset-2',
        isSidebar ? 'w-full px-3 py-2.5' : 'max-w-[260px] px-2.5 py-2',
        className
      )}
      aria-label={`계정 메뉴: ${displayName}`}
    >
      <Avatar src={user.avatarUrl} name={user.name} email={user.email} size="sm" status={avatarStatus} />
      <span className="min-w-0 flex-1">
        <span className="block truncate text-[13px] font-bold text-slate-900">{displayName}</span>
        <span className="block truncate text-[11px] font-medium text-slate-500">{user.email}</span>
      </span>
      <span className="material-symbols-outlined shrink-0 text-[18px] leading-none text-slate-400" aria-hidden="true">
        expand_more
      </span>
    </button>
  )

  return (
    <DropdownMenu trigger={trigger} align="end" width={isSidebar ? 'trigger' : 'md'}>
      <div className="px-2 py-2">
        <div className="flex min-w-0 items-center gap-2.5">
          <Avatar src={user.avatarUrl} name={user.name} email={user.email} size="md" status={avatarStatus} />
          <div className="min-w-0">
            <p className="truncate text-[13px] font-bold text-slate-900">{displayName}</p>
            <p className="truncate text-[11px] font-medium text-slate-500">{user.email}</p>
          </div>
        </div>
      </div>

      {integrations.length > 0 && (
        <>
          <DropdownMenu.Separator />
          <DropdownMenu.Label>연동 상태</DropdownMenu.Label>
          <div className="space-y-1 px-2 py-1">
            {integrations.map((integration) => {
              const cfg = integrationConfig[integration.status]
              return (
                <div key={integration.label} className="flex min-w-0 items-start gap-2 rounded-lg bg-slate-50 px-2.5 py-2">
                  <span className={cn('mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full', cfg.dot)} />
                  <div className="min-w-0 flex-1">
                    <div className="flex min-w-0 items-center justify-between gap-2">
                      <span className="truncate text-[12px] font-bold text-slate-700">{integration.label}</span>
                      <span className={cn('shrink-0 text-[11px] font-bold', cfg.text)}>{cfg.label}</span>
                    </div>
                    {integration.helperText && (
                      <p className="mt-0.5 truncate text-[11px] text-slate-400">{integration.helperText}</p>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        </>
      )}

      {(extraItems.length > 0 || onSettingsClick || onLogout) && <DropdownMenu.Separator />}

      {extraItems.map((item) => (
        <DropdownMenu.Item
          key={item.label}
          leftIcon={item.leftIcon}
          description={item.description}
          tone={item.tone}
          disabled={item.disabled}
          onSelect={item.onSelect}
        >
          {item.label}
        </DropdownMenu.Item>
      ))}

      {onSettingsClick && (
        <DropdownMenu.Item leftIcon="settings" onSelect={onSettingsClick}>
          계정 설정
        </DropdownMenu.Item>
      )}

      {onLogout && (
        <DropdownMenu.Item leftIcon="logout" tone="danger" onSelect={onLogout}>
          로그아웃
        </DropdownMenu.Item>
      )}
    </DropdownMenu>
  )
}
