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';

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 [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;
        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={loading} onClick={handleLogout}>
              Log out
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default ProfileDropdown;
