import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useLogout } from '@/hooks/auth';
import Link from 'next/link';
import { useState } from 'react';
import { useLayoutStore } from '@/stores';
import { useStreamChatStore } from '../../chat/[id]/stream-chat';
import { useAsyncFn } from '@/hooks/tools';
import IconFont from '@/components/ui/iconFont';
import { useTranslations } from 'next-intl';

const ProfileDropdownItem = ({
  icon,
  children,
  onClick,
}: {
  icon: string | React.ReactNode;
  children: React.ReactNode;
  onClick?: () => void;
}) => {
  return (
    <div
      onClick={onClick}
      className="flex w-full items-center justify-between gap-3 cursor-pointer px-5 py-4 hover:bg-white/5 transition-colors"
    >
      <div className="flex items-center gap-3">
        {typeof icon === 'string' ? <i className={`iconfont ${icon} text-xl text-white`} /> : icon}
        <div className="txt-body-l text-white">{children}</div>
      </div>
      <i className="iconfont icon-arrow-right-border text-white/60 text-lg" />
    </div>
  );
};

const ProfileDropdown = () => {
  const t = useTranslations('profile');
  const tCommon = useTranslations('common');
  const { mutateAsync: logout } = useLogout();
  const [isLogoutDialogOpen, setIsLogoutDialogOpen] = useState(false);
  const setSidebarExpanded = useLayoutStore((s) => s.setSidebarExpanded);
  const clearClient = useStreamChatStore((s) => s.clearClient);

  const { run: handleLogout, loading } = useAsyncFn(async () => {
    try {
      await clearClient();
      setSidebarExpanded(false);
      await logout();
      setIsLogoutDialogOpen(false);
    } catch (error) {
      console.error('登出过程中发生错误:', error);
    }
  });

  // 菜单项配置
  const items: Array<
    | { type: 'separator' }
    | {
        type: 'item';
        label: string;
        icon: string | React.ReactNode;
        href?: string;
        target?: string;
        onClick?: () => void;
      }
  > = [
    {
      type: 'item',
      label: t('editProfile'),
      icon: 'icon-icon_order_remark',
      href: '/profile/edit',
    },
    {
      type: 'item',
      label: t('maskedIdentityMode'),
      icon: <IconFont type="icon-shezhi" />,
      href: '/profile/mask',
    },
    {
      type: 'item',
      label: t('account'),
      icon: 'icon-card',
      href: '/profile/account',
    },
    { type: 'separator' },
    {
      type: 'item',
      label: t('aboutUs'),
      icon: 'icon-info',
      href: '/about',
    },
    {
      type: 'item',
      label: t('termsOfServices'),
      icon: 'icon-audits',
      href: '/policy/tos',
    },
    {
      type: 'item',
      label: t('privacyPolicy'),
      icon: 'icon-shield',
      href: '/policy/privacy',
    },
    { type: 'separator' },
    {
      type: 'item',
      label: t('logOut'),
      icon: 'icon-icon_exit',
      onClick: () => setIsLogoutDialogOpen(true),
    },
  ];

  return (
    <>
      <div className="bg-[rgba(26,21,42,1)] mt-8 w-full rounded-2xl overflow-hidden">
        {items.map((item, index) => {
          if (item.type === 'separator') {
            return (
              <div key={`separator-${index}`} className="my-2 px-4">
                <div className="h-px bg-white/10" />
              </div>
            );
          }

          const menuItem = (
            <ProfileDropdownItem icon={item.icon} onClick={item.onClick}>
              {item.label}
            </ProfileDropdownItem>
          );

          if (item.href) {
            return (
              <Link key={item.label} href={item.href} target={item.target}>
                {menuItem}
              </Link>
            );
          }

          return <div key={item.label}>{menuItem}</div>;
        })}
      </div>

      <AlertDialog open={isLogoutDialogOpen} onOpenChange={setIsLogoutDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('logOut')}</AlertDialogTitle>
          </AlertDialogHeader>
          <AlertDialogDescription>{t('logOutConfirm')}</AlertDialogDescription>
          <AlertDialogFooter>
            <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
            <AlertDialogAction variant="destructive" loading={loading} onClick={handleLogout}>
              {t('logOut')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default ProfileDropdown;
