'use client'

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { User as SupabaseUser } from '@supabase/supabase-js'
import { Button } from '@/components/ui/button'
import { Avatar } from '@/components/ui/avatar'
import { ChevronDown, User, LogOut, Settings } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useUser } from '@/hooks/useUser'
import { useRouter } from 'next/navigation'

interface UserAvatarDropdownProps {
  user: SupabaseUser
  onSignOut: () => void
  onProfileClick: () => void
  className?: string
}

// Mobile version for mobile menu
export function MobileUserMenu({ 
  user, 
  onSignOut, 
  onProfileClick,
  className 
}: UserAvatarDropdownProps) {
  const t = useTranslations('navigation')
  const { isAdmin } = useUser()
  const router = useRouter()

  const userName = user.user_metadata?.full_name || 
                   user.user_metadata?.name || 
                   user.email?.split('@')[0] || 
                   'User'
  const userAvatar = user.user_metadata?.avatar_url || 
                     user.user_metadata?.picture

  return (
    <div className={cn("space-y-1", className)}>
      {/* User info section */}
      <div className="px-3 py-2 border-b border-border">
        <div className="flex items-center gap-3">
          <Avatar 
            src={userAvatar} 
            alt={userName}
            size={48}
            className="w-12 h-12"
          />
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium truncate">
              {userName}
            </div>
            <div className="text-xs text-muted-foreground truncate">
              {user.email}
            </div>
          </div>
        </div>
      </div>

      {/* Menu items */}
      <div className="space-y-1">
        <button
          className={cn(
            "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors",
            "hover:bg-accent hover:text-accent-foreground",
            "focus:bg-accent focus:text-accent-foreground focus:outline-none"
          )}
          onClick={onProfileClick}
        >
          <User className="h-4 w-4" />
          <span>{t('profile')}</span>
        </button>

        {isAdmin && (
          <button
            className={cn(
              "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors",
              "hover:bg-accent hover:text-accent-foreground",
              "focus:bg-accent focus:text-accent-foreground focus:outline-none"
            )}
            onClick={() => router.push('/admin')}
          >
            <Settings className="h-4 w-4" />
            <span>{t('admin')}</span>
          </button>
        )}

        <button
          className={cn(
            "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors",
            "hover:bg-accent hover:text-accent-foreground",
            "focus:bg-accent focus:text-accent-foreground focus:outline-none",
            "text-destructive hover:text-destructive"
          )}
          onClick={onSignOut}
        >
          <LogOut className="h-4 w-4" />
          <span>{t('signOut')}</span>
        </button>
      </div>
    </div>
  )
}

export function UserAvatarDropdown({ 
  user, 
  onSignOut, 
  onProfileClick, 
  className 
}: UserAvatarDropdownProps) {
  const t = useTranslations('navigation')
  const { isAdmin } = useUser()
  const router = useRouter()
  const [isOpen, setIsOpen] = useState(false)

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element
      if (!target.closest('[data-user-dropdown]')) {
        setIsOpen(false)
      }
    }

    if (isOpen) {
      document.addEventListener('click', handleClickOutside)
      return () => document.removeEventListener('click', handleClickOutside)
    }
  }, [isOpen])

  // Get user display name and avatar
  const userName = user.user_metadata?.full_name || 
                   user.user_metadata?.name || 
                   user.email?.split('@')[0] || 
                   'User'
  const userAvatar = user.user_metadata?.avatar_url || 
                     user.user_metadata?.picture

  return (
    <div className={cn("relative", className)} data-user-dropdown>
      <Button
        variant="ghost"
        size="sm"
        className="h-9 gap-2 px-2 hover:bg-accent/50"
        onClick={() => setIsOpen(!isOpen)}
        aria-expanded={isOpen}
        aria-haspopup="menu"
      >
        <Avatar 
          src={userAvatar} 
          alt={userName}
          size={32}
          className="w-8 h-8"
        />
        <span className="hidden sm:inline-block text-sm font-medium max-w-24 truncate">
          {userName}
        </span>
        <ChevronDown className={cn(
          "h-3 w-3 transition-transform",
          isOpen && "rotate-180"
        )} />
        <span className="sr-only">User menu</span>
      </Button>

      {isOpen && (
        <div className="absolute right-0 top-full mt-1 w-48 rounded-md border border-border bg-popover p-1 shadow-md z-50">
          {/* User info section */}
          <div className="px-3 py-2 border-b border-border">
            <div className="flex items-center gap-3">
              <Avatar 
                src={userAvatar} 
                alt={userName}
                size={40}
                className="w-10 h-10"
              />
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium truncate">
                  {userName}
                </div>
                <div className="text-xs text-muted-foreground truncate">
                  {user.email}
                </div>
              </div>
            </div>
          </div>

          {/* Menu items */}
          <div className="py-1">
            <button
              className={cn(
                "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-sm transition-colors",
                "hover:bg-accent hover:text-accent-foreground",
                "focus:bg-accent focus:text-accent-foreground focus:outline-none"
              )}
              onClick={() => {
                onProfileClick()
                setIsOpen(false)
              }}
              role="menuitem"
            >
              <User className="h-4 w-4" />
              <span>{t('profile')}</span>
            </button>

            {isAdmin && (
              <button
                className={cn(
                  "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-sm transition-colors",
                  "hover:bg-accent hover:text-accent-foreground",
                  "focus:bg-accent focus:text-accent-foreground focus:outline-none"
                )}
                onClick={() => {
                  router.push('/admin')
                  setIsOpen(false)
                }}
                role="menuitem"
              >
                <Settings className="h-4 w-4" />
                <span>{t('admin')}</span>
              </button>
            )}

            <button
              className={cn(
                "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-sm transition-colors",
                "hover:bg-accent hover:text-accent-foreground",
                "focus:bg-accent focus:text-accent-foreground focus:outline-none",
                "text-destructive hover:text-destructive"
              )}
              onClick={() => {
                onSignOut()
                setIsOpen(false)
              }}
              role="menuitem"
            >
              <LogOut className="h-4 w-4" />
              <span>{t('signOut')}</span>
            </button>
          </div>
        </div>
      )}
    </div>
  )
}