'use client';

import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { usePathname, useRouter } from 'next/navigation';
import Link from 'next/link';
import { useMemo } from 'react';
import { useAuthStore } from '@/store/authStore';
import {
  LogOut,
  Settings,
  Share2,
  ShieldAlert,
  ShoppingBag,
  Store,
  User,
  Wallet,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

type Locale = 'vi' | 'en';

const copy = {
  vi: {
    language: 'Chọn ngôn ngữ',
    profile: 'Hồ sơ',
    settings: 'Cài đặt',
    orders: 'Đơn hàng',
    complaints: 'Khiếu nại của tôi',
    wallet: 'Ví',
    affiliate: 'Affiliate của tôi',
    sellerCenter: 'Kênh bán hàng',
    administration: 'Quản trị hệ thống',
    logout: 'Đăng xuất',
    user: 'Người dùng',
    buyer: 'Khách hàng',
  },
  en: {
    language: 'Language',
    profile: 'Profile',
    settings: 'Settings',
    orders: 'Orders',
    complaints: 'My complaints',
    wallet: 'Wallet',
    affiliate: 'My affiliate',
    sellerCenter: 'Seller Center',
    administration: 'Administration',
    logout: 'Log out',
    user: 'User',
    buyer: 'Customer',
  },
} as const;

export default function UserDropdown() {
  const pathname = usePathname();
  const router = useRouter();
  const logout = useAuthStore((state) => state.logout);
  const token = useAuthStore((state) => state.token);

  const currentLocale: Locale = pathname.startsWith('/en') ? 'en' : 'vi';
  const text = copy[currentLocale];

  const decodedUser = useMemo(() => {
    if (!token) return null;
    try {
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(
        atob(base64)
          .split('')
          .map((character) => `%${`00${character.charCodeAt(0).toString(16)}`.slice(-2)}`)
          .join(''),
      );
      return JSON.parse(jsonPayload);
    } catch {
      return null;
    }
  }, [token]);

  const user = {
    name: decodedUser?.email ? decodedUser.email.split('@')[0] : text.user,
    email: decodedUser?.email || 'shopmmo@gmail.com',
    role: decodedUser?.role || 'BUYER',
  };

  const roleMeta: Record<string, { label: string; className: string }> = {
    BUYER: {
      label: text.buyer,
      className: 'border border-slate-400/30 bg-slate-500/15 text-slate-600 dark:text-slate-200',
    },
    SELLER: {
      label: 'Seller',
      className: 'border border-violet-400/30 bg-violet-500/15 text-violet-700 dark:text-violet-200',
    },
    ADMIN: {
      label: 'Admin',
      className: 'border border-red-400/30 bg-red-500/15 text-red-700 dark:text-red-200',
    },
    SUPER_ADMIN: {
      label: 'Super Admin',
      className: 'border border-red-400/30 bg-red-500/20 text-red-700 dark:text-red-100',
    },
  };
  const roleBadge = roleMeta[user.role] || roleMeta.BUYER;

  const changeLanguage = (locale: Locale) => {
    if (locale === currentLocale) return;
    const hasLocalePrefix = /^\/(vi|en)(?=\/|$)/.test(pathname);
    const localizedPath = hasLocalePrefix
      ? pathname.replace(/^\/(vi|en)(?=\/|$)/, `/${locale}`)
      : `/${locale}${pathname === '/' ? '' : pathname}`;

    document.cookie = `NEXT_LOCALE=${locale}; path=/; max-age=31536000; samesite=lax`;
    document.documentElement.lang = locale;
    router.replace(localizedPath, { scroll: false });
  };

  const menuItems: Array<{ icon: LucideIcon; label: string; href: string }> = [
    { icon: User, label: text.profile, href: `/${currentLocale}/profile` },
    { icon: Settings, label: text.settings, href: `/${currentLocale}/profile/edit` },
    { icon: ShoppingBag, label: text.orders, href: `/${currentLocale}/orders` },
    { icon: ShieldAlert, label: text.complaints, href: `/${currentLocale}/profile/complaints` },
    { icon: Wallet, label: text.wallet, href: `/${currentLocale}/wallet` },
    { icon: Share2, label: text.affiliate, href: `/${currentLocale}/affiliate` },
  ];

  if (user.role === 'SELLER') {
    menuItems.push({ icon: Store, label: text.sellerCenter, href: `/${currentLocale}/seller/dashboard` });
  }

  if (user.role === 'ADMIN' || user.role === 'SUPER_ADMIN') {
    menuItems.push({
      icon: ShieldAlert,
      label: text.administration,
      href: `/${currentLocale}/admin`,
    });
  }

  const optionClass = (active: boolean) =>
    `flex items-center justify-center gap-1.5 rounded-full px-2 py-1.5 text-xs font-bold transition-colors ${
      active
        ? 'bg-foreground text-background shadow-sm'
        : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
    }`;

  return (
    <DropdownMenu.Root>
      <DropdownMenu.Trigger asChild>
        <button
          aria-label={text.profile}
          className="flex h-9 items-center gap-2 rounded-full border border-border bg-card pl-1 pr-3 text-card-foreground outline-none transition-colors hover:bg-accent"
        >
          <img
            src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(user.name)}`}
            className="h-7 w-7 rounded-full bg-muted"
            alt=""
          />
          <span className="text-sm font-medium">{user.name}</span>
        </button>
      </DropdownMenu.Trigger>

      <DropdownMenu.Portal>
        <DropdownMenu.Content
          className="z-50 w-[340px] rounded-2xl border border-border bg-popover p-3 text-popover-foreground shadow-2xl animate-in fade-in zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=closed]:zoom-out-95"
          sideOffset={8}
          align="end"
        >
          <div className="mb-3 flex items-center gap-3 rounded-xl bg-muted p-3">
            <img
              src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(user.name)}`}
              className="h-12 w-12 rounded-full border border-border bg-card"
              alt=""
            />
            <div className="min-w-0">
              <div className="truncate text-base font-bold">{user.name}</div>
              <div className="truncate text-xs text-muted-foreground">{user.email}</div>
              <div className={`mt-1 w-fit rounded-full px-2 py-0.5 text-[10px] font-bold ${roleBadge.className}`}>
                {roleBadge.label}
              </div>
            </div>
          </div>

          <DropdownMenu.Separator className="my-2 h-px bg-border" />

          <div className="flex items-center justify-between px-3 py-2">
            <span className="text-sm font-semibold text-muted-foreground">{text.language}</span>
            <div className="grid grid-cols-2 rounded-full border border-border bg-muted p-0.5">
              <button type="button" onClick={() => changeLanguage('en')} className={optionClass(currentLocale === 'en')}>
                EN
              </button>
              <button type="button" onClick={() => changeLanguage('vi')} className={optionClass(currentLocale === 'vi')}>
                VI
              </button>
            </div>
          </div>

          <DropdownMenu.Separator className="my-2 h-px bg-border" />

          <div className="flex flex-col gap-0.5">
            {menuItems.map((item) => {
              const Icon = item.icon;
              return (
                <DropdownMenu.Item key={item.href} className="outline-none">
                  <Link
                    href={item.href}
                    className="flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
                  >
                    <Icon className="h-4 w-4" />
                    {item.label}
                  </Link>
                </DropdownMenu.Item>
              );
            })}
            <DropdownMenu.Separator className="my-1 h-px bg-border" />
            <DropdownMenu.Item className="outline-none" onSelect={logout}>
              <button className="flex w-full cursor-pointer items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-red-500 transition-colors hover:bg-red-500/10">
                <LogOut className="h-4 w-4" />
                {text.logout}
              </button>
            </DropdownMenu.Item>
          </div>
        </DropdownMenu.Content>
      </DropdownMenu.Portal>
    </DropdownMenu.Root>
  );
}
