import { openUrl } from "@tauri-apps/plugin-opener";
import {
  BookOpen,
  CreditCard,
  SignIn,
  SignOut,
  UserCircle,
  GearSix,
  ArrowSquareOut,
} from "@phosphor-icons/react";
import { useEffect, useRef, useState } from "react";
import { useAuthStore } from "@/features/window/stores/auth-store";
import { useUIState } from "@/features/window/stores/ui-state-store";
import { Button } from "@/ui/button";
import { Dropdown, type MenuItem } from "@/ui/dropdown";
import { TabsList } from "@/ui/tabs";
import Tooltip from "@/ui/tooltip";
import { useDesktopSignIn } from "@/features/window/hooks/use-desktop-sign-in";
import { cn } from "@/utils/cn";

const TITLE_BAR_CONTROL_GROUP_CLASS_NAME =
  "pointer-events-auto border-transparent bg-transparent p-0";
const TITLE_BAR_ICON_BUTTON_CLASS_NAME =
  "h-6 w-7 rounded-md border-0 bg-transparent text-text-lighter hover:bg-hover/60 hover:text-text focus-visible:rounded-md data-[active=true]:bg-hover/70";

interface AccountMenuProps {
  className?: string;
}

export const AccountMenu = ({ className }: AccountMenuProps) => {
  const user = useAuthStore((s) => s.user);
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const subscription = useAuthStore((s) => s.subscription);
  const logout = useAuthStore((s) => s.logout);
  const setIsSettingsDialogVisible = useUIState((state) => state.setIsSettingsDialogVisible);
  const hasBlockingModalOpen = useUIState(
    (state) =>
      state.isQuickOpenVisible ||
      state.isCommandPaletteVisible ||
      state.isGlobalSearchVisible ||
      state.isSettingsDialogVisible ||
      state.isThemeSelectorVisible ||
      state.isIconThemeSelectorVisible ||
      state.isProjectPickerVisible ||
      state.isDatabaseConnectionVisible,
  );

  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const { signIn } = useDesktopSignIn({
    onSuccess: () => setIsOpen(false),
  });

  const handleSignIn = async () => {
    if (import.meta.env.DEV) {
      console.log("[Auth] Starting desktop sign-in flow from account menu");
    }
    await signIn();
  };

  const handleSignOut = async () => {
    await logout();
  };

  const handleManageAccount = async () => {
    await openUrl("https://athas.dev/dashboard");
  };

  const handleViewPricing = async () => {
    await openUrl("https://athas.dev/pricing");
  };

  const handleOpenDocs = async () => {
    await openUrl("https://athas.dev/docs");
  };

  const handleOpenSettings = () => {
    setIsSettingsDialogVisible(true);
  };

  const subscriptionStatus = subscription?.status ?? "free";
  const isEnterprise = subscription?.subscription?.plan === "enterprise";

  const signedOutItems: MenuItem[] = [
    {
      id: "settings",
      label: "Settings",
      icon: <GearSix weight="duotone" />,
      onClick: handleOpenSettings,
    },
    {
      id: "docs",
      label: "Docs",
      icon: <BookOpen weight="duotone" />,
      onClick: handleOpenDocs,
    },
    {
      id: "settings-separator",
      label: "",
      separator: true,
      onClick: () => {},
    },
    {
      id: "sign-in",
      label: "Sign In",
      icon: <SignIn weight="duotone" />,
      onClick: handleSignIn,
    },
  ];

  const signedInItems: MenuItem[] = [
    {
      id: "user-info",
      label: user?.name || user?.email || "Account",
      icon: user?.avatar_url ? (
        <img src={user.avatar_url} alt="" className="size-3 rounded-full" />
      ) : (
        <UserCircle weight="duotone" />
      ),
      onClick: () => {},
      disabled: true,
    },
    {
      id: "plan-separator",
      label: "",
      separator: true,
      onClick: () => {},
    },
    {
      id: "subscription",
      label: `Plan: ${isEnterprise ? "Enterprise" : subscriptionStatus === "pro" ? "Pro" : "Free"}`,
      icon: <CreditCard weight="duotone" />,
      onClick: handleViewPricing,
    },
    {
      id: "manage-account",
      label: "Manage Account",
      icon: <ArrowSquareOut weight="duotone" />,
      onClick: handleManageAccount,
    },
    {
      id: "settings",
      label: "Settings",
      icon: <GearSix weight="duotone" />,
      onClick: handleOpenSettings,
    },
    {
      id: "docs",
      label: "Docs",
      icon: <BookOpen weight="duotone" />,
      onClick: handleOpenDocs,
    },
    {
      id: "sign-out-separator",
      label: "",
      separator: true,
      onClick: () => {},
    },
    {
      id: "sign-out",
      label: "Sign Out",
      icon: <SignOut weight="duotone" />,
      onClick: handleSignOut,
    },
  ];

  const tooltipLabel = isAuthenticated ? user?.name || user?.email || "Account" : "Account";

  useEffect(() => {
    if (!isOpen || !hasBlockingModalOpen) return;
    setIsOpen(false);
  }, [hasBlockingModalOpen, isOpen]);

  return (
    <>
      <Tooltip content={tooltipLabel} side="bottom">
        <TabsList variant="segmented" className={cn(TITLE_BAR_CONTROL_GROUP_CLASS_NAME, className)}>
          <Button
            ref={buttonRef}
            onClick={() => setIsOpen((open) => !open)}
            type="button"
            variant="ghost"
            size="icon-sm"
            active={isOpen}
            className={TITLE_BAR_ICON_BUTTON_CLASS_NAME}
            aria-expanded={isOpen}
            aria-haspopup="menu"
            aria-label="Account"
          >
            {isAuthenticated && user?.avatar_url ? (
              <img src={user.avatar_url} alt="" className="size-4 rounded-full object-cover" />
            ) : (
              <UserCircle className="size-4" weight="duotone" />
            )}
          </Button>
        </TabsList>
      </Tooltip>
      <Dropdown
        isOpen={isOpen}
        anchorRef={buttonRef}
        anchorAlign="end"
        items={isAuthenticated ? signedInItems : signedOutItems}
        onClose={() => setIsOpen(false)}
      />
    </>
  );
};
