"use client";

import { useEffect } from "react";
import { LogOut } from "lucide-react";
import { signOut } from "next-auth/react";
import { useRouter } from "next/navigation";

import { BackButton } from "@/app/_components";
import { MobileShell } from "@/app/_components/core";
import { ROUTES } from "@/router/routes";
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import { useUserDispatch, useUserState } from "@/stores/user/user-context";

import {
  SidebarWalletCard,
  UserHeader,
  type SidebarUserState,
} from "./components";

import styles from "./components/sidebar-screen.module.css";

const FALLBACK_USERNAME = "User name";
const VIP_SUBSCRIPTION_URL = `${ROUTES.subscription}?type=vip`;
const TOP_UP_SUBSCRIPTION_URL = `${ROUTES.subscription}?type=topup`;

export function SidebarScreen() {
  const router = useRouter();
  const user = useUserState();
  const userDispatch = useUserDispatch();
  const auth = useAuthState();
  const authDispatch = useAuthDispatch();

  useEffect(() => {
    if (!auth.hasInitialized || auth.isLoading) return;
    if (auth.loginStatus === "notLoggedIn") return;

    userDispatch({ type: "UserFetch" });
  }, [
    auth.hasInitialized,
    auth.isLoading,
    auth.loginStatus,
    userDispatch,
  ]);

  const handleLogoutClick = () => {
    userDispatch({ type: "UserClearLocal" });
    authDispatch({ type: "AuthLogoutSubmitted" });
    void signOut({ redirect: false });
  };

  // 状态派生：未登录 / 已登录未 VIP / 已登录 VIP
  const sidebarState: SidebarUserState =
    auth.loginStatus === "notLoggedIn"
      ? "guest"
      : user.currentUser?.isVip === true
        ? "vip"
        : "member";

  const isInitializingUser =
    sidebarState !== "guest" && user.currentUser == null;

  const name = user.currentUser?.username ?? FALLBACK_USERNAME;
  const avatarUrl = user.avatarUrl ?? user.currentUser?.avatarUrl ?? null;

  return (
    <MobileShell background="#fcf3f4">
      <div className={styles.shell}>
        <div className={styles.bgOrbOne} aria-hidden="true" />
        <div className={styles.bgOrbTwo} aria-hidden="true" />

        <div className={styles.topBar}>
          <BackButton href={ROUTES.chat} variant="soft" />
        </div>

        <section className={`${styles.userSlot} ${styles.revealOne}`}>
          <UserHeader
            state={sidebarState}
            name={name}
            avatarUrl={avatarUrl}
            isLoading={isInitializingUser}
            onLoginClick={() => router.push(ROUTES.auth)}
          />
        </section>

        <section className={`${styles.cardSlot} ${styles.revealTwo}`}>
          <SidebarWalletCard
            creditBalance={user.creditBalance}
            onActivateVip={
              sidebarState === "vip"
                ? undefined
                : () => router.push(VIP_SUBSCRIPTION_URL)
            }
            onTopUp={() => router.push(TOP_UP_SUBSCRIPTION_URL)}
            onRulesClick={() => router.push(ROUTES.coinsRules)}
          />
        </section>

        {sidebarState !== "guest" ? (
          <section className={`${styles.settingsSlot} ${styles.revealThree}`}>
            <p className={styles.settingsLabel}>Other</p>
            <button
              type="button"
              className={styles.logoutCard}
              onClick={handleLogoutClick}
            >
              <span className={styles.logoutIcon} aria-hidden="true">
                <LogOut size={19} strokeWidth={2.2} />
              </span>
              <span className={styles.logoutText}>
                <span className={styles.logoutTitle}>Log out</span>
                <span className={styles.logoutSubtitle}>
                  End the current session safely
                </span>
              </span>
            </button>
          </section>
        ) : null}
      </div>
    </MobileShell>
  );
}
