import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { IconButton } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Separator } from "@/components/ui/separator";
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 { useMainLayout } from "@/context/mainLayout";

const ProfileDropdownItem = ({ icon, children, onClick }: { icon: string, children: React.ReactNode, onClick?: () => void }) => {
  return (
    <DropdownMenuItem onClick={onClick}>
      <div className="w-[288px] flex items-center gap-2">
        <i className={`iconfont ${icon}`} />
        <div className="txt-body-l text-txt-primary-normal">
          {children}
        </div>
      </div>
    </DropdownMenuItem>
  );
}

const ProfileDropdown = () => {
  const { mutateAsync: logout } = useLogout();
  const { nim } = useNimChat();
  const { clearAllConversations } = useNimConversation();
  const [isLogoutDialogOpen, setIsLogoutDialogOpen] = useState(false);
  const [isLogoutDialogLoading, setIsLogoutDialogLoading] = useState(false);
  const { isSidebarExpanded, dispatch } = useMainLayout();

  // 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) {
        dispatch({
          type: "updateState",
          payload: {
            isSidebarExpanded: false,
          },
        });
      }

      // 4. 执行用户登出
      await logout();
      
      setIsLogoutDialogOpen(false);
      setIsLogoutDialogLoading(false);
    } catch (error) {
      console.error('登出过程中发生错误:', error);
      setIsLogoutDialogLoading(false);
    }
  }

  // todo iconfont
  return (
    <div className="absolute top-4 right-0">
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <IconButton variant="tertiary">
            <i className="iconfont icon-More" style={{ fontSize: '24px' }} />
          </IconButton>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <Link href="/profile/edit">
            <ProfileDropdownItem icon="icon-icon_order_remark">Edit Personal Info</ProfileDropdownItem>
          </Link>
          <Link href="/profile/account">
            <ProfileDropdownItem icon="icon-card">Account</ProfileDropdownItem>
          </Link>
          <div className="px-2 my-3">
            <Separator className="bg-outline-normal" />
          </div>
          <Link href="/about" target="_blank">
            <ProfileDropdownItem icon="icon-info">About us</ProfileDropdownItem>
          </Link>
          <Link href="/policy/tos" target="_blank">
            <ProfileDropdownItem icon="icon-audits">User Agreement</ProfileDropdownItem>
          </Link>
          <Link href="/policy/privacy" target="_blank">
            <ProfileDropdownItem icon="icon-shield">Privacy Policy</ProfileDropdownItem>
          </Link>
          <div className="px-2 my-3">
            <Separator className="bg-outline-normal" />
          </div>
          <ProfileDropdownItem icon="icon-icon_exit" onClick={() => setIsLogoutDialogOpen(true)}>Log Out</ProfileDropdownItem>
        </DropdownMenuContent>
      </DropdownMenu>

      
      <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>
    </div>
  );
}
 
export default ProfileDropdown;