'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { LogOut } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { handleLogout } from '@/lib/actions';

type Props = {
  userName: string;
  userInitial: string;
  userAvatarUrl?: string;
  userAvatarHint?: string;
  settingsLabel: string;
  supportLabel: string;
  logoutLabel: string;
};

export function DashboardUserMenu({
  userName,
  userInitial,
  userAvatarUrl,
  userAvatarHint,
  settingsLabel,
  supportLabel,
  logoutLabel,
}: Props) {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <Button variant="outline" size="icon" className="overflow-hidden rounded-full" disabled aria-hidden="true">
        <Avatar>
          <AvatarFallback>{userInitial}</AvatarFallback>
        </Avatar>
      </Button>
    );
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="icon" className="overflow-hidden rounded-full">
          <Avatar>
            <AvatarImage
              src={userAvatarUrl}
              alt={userName}
              width={36}
              height={36}
              data-ai-hint={userAvatarHint}
            />
            <AvatarFallback>{userInitial}</AvatarFallback>
          </Avatar>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuLabel>{userName}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link href="/settings">{settingsLabel}</Link>
        </DropdownMenuItem>
        <DropdownMenuItem disabled>{supportLabel}</DropdownMenuItem>
        <DropdownMenuSeparator />
        <form action={handleLogout} className="w-full">
          <DropdownMenuItem asChild>
            <button type="submit" className="w-full text-start flex items-center cursor-pointer">
              <LogOut className="h-4 w-4 me-2" />
              <span>{logoutLabel}</span>
            </button>
          </DropdownMenuItem>
        </form>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
