import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useLogout } from '@/hooks/auth';
import { useNimChat, useNimConversation } from '@/context/NimChat/useNimChat';
import { useSetAtom } from 'jotai';
import {
  conversationListAtom,
  msgListAtom,
  userListAtom,
  imSyncedAtom,
  imReconnectStatusAtom,
  IMReconnectStatus,
  selectedConversationIdAtom,
} from '@/atoms/im';
import { QueueMap } from '@/lib/queue';
import Link from 'next/link';
import { useState } from 'react';
import { useLayoutStore } from '@/stores';

const ProfileDropdownItem = ({
  icon,
  children,
  onClick,
}: {
  icon: string;
  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">
        <i className={`iconfont ${icon} text-xl text-white`} />
        <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 { mutateAsync: logout } = useLogout();
  const { nim } = useNimChat();
  const { clearAllConversations } = useNimConversation();
  const [isLogoutDialogOpen, setIsLogoutDialogOpen] = useState(false);
  const [isLogoutDialogLoading, setIsLogoutDialogLoading] = useState(false);
  const { isSidebarExpanded, setSidebarExpanded } = useLayoutStore();

  // IM相关状态重置
  const setConversationList = useSetAtom(conversationListAtom);
  const setMsgList = useSetAtom(msgListAtom);
  const setUserList = useSetAtom(userListAtom);
  const setImSynced = useSetAtom(imSyncedAtom);
  const setImReconnectStatus = useSetAtom(imReconnectStatusAtom);
  const setSelectedConversationId = useSetAtom(selectedConversationIdAtom);

  const handleLogout = async () => {
    try {
      setIsLogoutDialogLoading(true);

      // 1. 断开IM连接
      try {
        console.log('开始断开IM连接...');
        await nim.V2NIMLoginService.logout();
        console.log('IM连接已断开');
      } catch (imError) {
        console.error('断开IM连接失败:', imError);
        // 即使IM断开失败，也继续执行后续步骤
      }

      // 2. 清除所有聊天数据
      try {
        console.log('开始清除聊天历史数据...');
        await clearAllConversations();
        console.log('聊天历史数据已清除');
      } catch (clearError) {
        console.error('清除聊天数据失败:', clearError);
        // 即使清除失败，也继续执行后续步骤
      }

      // 3. 重置所有IM相关的本地状态
      setConversationList(new Map());
      setMsgList(new QueueMap(20, 'rightToLeft'));
      setUserList(new Map());
      setImSynced(false);
      setImReconnectStatus(IMReconnectStatus.DISCONNECTED);
      setSelectedConversationId(null);

      if (isSidebarExpanded) {
        setSidebarExpanded(false);
      }

      // 4. 执行用户登出
      await logout();

      setIsLogoutDialogOpen(false);
      setIsLogoutDialogLoading(false);
    } catch (error) {
      console.error('登出过程中发生错误:', error);
      setIsLogoutDialogLoading(false);
    }
  };

  // 菜单项配置
  const items: Array<
    | { type: 'separator' }
    | {
        type: 'item';
        label: string;
        icon: string;
        href?: string;
        target?: string;
        onClick?: () => void;
      }
  > = [
    {
      type: 'item',
      label: 'Edit Profile',
      icon: 'icon-icon_order_remark',
      href: '/profile/edit',
    },
    {
      type: 'item',
      label: 'Account',
      icon: 'icon-card',
      href: '/profile/account',
    },
    { type: 'separator' },
    {
      type: 'item',
      label: 'About Us',
      icon: 'icon-info',
      href: '/about',
    },
    {
      type: 'item',
      label: 'Terms of Services',
      icon: 'icon-audits',
      href: '/policy/tos',
    },
    {
      type: 'item',
      label: 'Privacy Policy',
      icon: 'icon-shield',
      href: '/policy/privacy',
    },
    { type: 'separator' },
    {
      type: 'item',
      label: 'Log out',
      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>Log Out</AlertDialogTitle>
          </AlertDialogHeader>
          <AlertDialogDescription>Are you sure you want to log out?</AlertDialogDescription>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              loading={isLogoutDialogLoading}
              onClick={handleLogout}
            >
              Log out
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default ProfileDropdown;
