"use client";

import { Download, LogOut, MessageCircleQuestion } from "lucide-react";
import { signOut } from "next-auth/react";

import { BackButton } from "@/app/_components";
import {
  AppBottomNav,
  FavoriteEntryButton,
  MobileShell,
} from "@/app/_components/core";
import { getCharacterBySlug } from "@/data/constants/character";
import {
  resolveGlobalRouteContext,
  type GlobalReturnToValue,
} from "@/router/global-route-context";
import { setPendingLogoutNavigation } from "@/router/logout-navigation";
import { useGlobalAppNavigator } from "@/router/use-global-app-navigator";
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import { useUserDispatch, useUserState } from "@/stores/user/user-context";
import { getCharacterRoutes } from "@/router/routes";

import { ProfileWalletCard, UserHeader } from "./components";
import { getProfileViewModel } from "./profile-view-model";
import { usePwaInstallEntry } from "./use-pwa-install-entry";
import { useProfileUserBootstrap } from "./use-profile-user-bootstrap";

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

export interface ProfileScreenProps {
  returnTo?: GlobalReturnToValue;
}

export function ProfileScreen({ returnTo }: ProfileScreenProps) {
  const navigator = useGlobalAppNavigator();
  const navigation = resolveGlobalRouteContext(returnTo);
  const character = getCharacterBySlug(navigation.characterSlug);
  const characterRoutes = getCharacterRoutes(navigation.characterSlug);
  const user = useUserState();
  const userDispatch = useUserDispatch();
  const auth = useAuthState();
  const authDispatch = useAuthDispatch();
  const pwaInstallEntry = usePwaInstallEntry();

  useProfileUserBootstrap({ auth, userDispatch });

  const handleLogoutClick = () => {
    setPendingLogoutNavigation(navigation.splashUrl);
    userDispatch({ type: "UserClearLocal" });
    authDispatch({ type: "AuthLogoutSubmitted" });
    void signOut({ redirect: false });
    navigator.replace(navigation.splashUrl, { scroll: false });
  };

  const view = getProfileViewModel({
    loginStatus: auth.loginStatus,
    user,
  });

  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={navigation.chatUrl}
            variant="soft"
            analyticsKey="profile.back_to_chat"
          />
          <h1 className={styles.pageTitle}>Menu</h1>
          <FavoriteEntryButton
            characterSlug={navigation.characterSlug}
            tone="light"
          />
        </div>

        <section className={`${styles.userSlot} ${styles.revealOne}`}>
          <UserHeader
            state={view.state}
            name={view.name}
            avatarUrl={view.avatarUrl}
            isLoading={view.isInitializingUser}
            onLoginClick={() => navigator.openAuth(navigation.profileUrl)}
          />
        </section>

        <section className={`${styles.cardSlot} ${styles.revealTwo}`}>
          <ProfileWalletCard
            creditBalance={view.wallet.creditBalance}
            dailyFreeChatLimit={view.wallet.dailyFreeChatLimit}
            dailyFreeChatRemaining={view.wallet.dailyFreeChatRemaining}
            dailyFreePrivateLimit={view.wallet.dailyFreePrivateLimit}
            dailyFreePrivateRemaining={view.wallet.dailyFreePrivateRemaining}
            onActivateVip={
              view.canActivateVip
                ? () =>
                    navigator.openSubscription({
                      type: "vip",
                      sourceCharacterSlug: navigation.characterSlug,
                      returnTo: "profile",
                      analytics: {
                        entryPoint: "profile",
                        triggerReason: "vip_cta",
                      },
                    })
                : undefined
            }
            onTopUp={() =>
              navigator.openSubscription({
                type: "topup",
                sourceCharacterSlug: navigation.characterSlug,
                returnTo: "profile",
                analytics: {
                  entryPoint: "profile",
                  triggerReason: "profile_recharge",
                },
              })
            }
            onRulesClick={() => navigator.push(navigation.coinsRulesUrl)}
          />
        </section>

        {view.canShowSettings ? (
          <section className={`${styles.settingsSlot} ${styles.revealThree}`}>
            <p className={styles.settingsLabel}>Other</p>
            <div className={styles.settingsActions}>
              <button
                type="button"
                data-analytics-key="profile.open_feedback"
                data-analytics-label="Open feedback"
                className={`${styles.logoutCard} ${styles.feedbackCard}`}
                onClick={() => navigator.push(navigation.feedbackUrl)}
              >
                <span
                  className={`${styles.logoutIcon} ${styles.feedbackIcon}`}
                  aria-hidden="true"
                >
                  <MessageCircleQuestion size={19} strokeWidth={2.2} />
                </span>
                <span className={styles.logoutText}>
                  <span className={styles.feedbackTitle}>Feedback</span>
                  <span className={styles.logoutSubtitle}>
                    Report a problem or share an idea
                  </span>
                </span>
              </button>

              {pwaInstallEntry.canInstall ? (
                <button
                  type="button"
                  className={`${styles.logoutCard} ${styles.installCard}`}
                  onClick={() => void pwaInstallEntry.installApp()}
                >
                  <span
                    className={`${styles.logoutIcon} ${styles.installIcon}`}
                    aria-hidden="true"
                  >
                    <Download size={19} strokeWidth={2.2} />
                  </span>
                  <span className={styles.logoutText}>
                    <span className={styles.installTitle}>Install app</span>
                    <span className={styles.installSubtitle}>
                      Add CozSweet to your Home Screen
                    </span>
                  </span>
                </button>
              ) : null}

              <button
                type="button"
                data-analytics-key="profile.logout"
                data-analytics-label="Log out"
                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>
            </div>
          </section>
        ) : null}

        <AppBottomNav
          activeItem="menu"
          privateZoneLabel={
            character?.copy.privateZoneTitle ?? "Private Zone"
          }
          onChatClick={() =>
            navigator.push(navigation.splashUrl, { scroll: false })
          }
          onPrivateZoneClick={() =>
            navigator.push(characterRoutes.privateZone, { scroll: false })
          }
          onMenuClick={() => undefined}
        />
      </div>
    </MobileShell>
  );
}
