"use client";

import { useRouter } from "next/navigation";

import { MobileShell } from "@/app/_components/core";
import { ROUTE_BUILDERS, ROUTES } from "@/router/routes";
import { useAuthState } from "@/stores/auth/auth-context";
import { useChatDispatch, useChatState } from "@/stores/chat/chat-context";
import { savePendingChatImageReturn } from "@/lib/navigation/chat_image_return_session";

import { getChatPaywallNavigationUrl } from "../../chat-screen.helpers";
import { FullscreenImageViewer, HistoryUnlockDialog } from "../../components";
import styles from "./chat-image-viewer-screen.module.css";

export interface ChatImageViewerScreenProps {
  messageId: string;
}

export function ChatImageViewerScreen({
  messageId,
}: ChatImageViewerScreenProps) {
  const router = useRouter();
  const authState = useAuthState();
  const chatState = useChatState();
  const chatDispatch = useChatDispatch();
  const message = chatState.messages.find(
    (item) => item.id === messageId && item.imageUrl,
  );

  const handleClose = () => {
    router.push(ROUTES.chat);
  };

  const handleUnlockImagePaywall = () => {
    savePendingChatImageReturn({
      messageId,
      returnUrl: ROUTE_BUILDERS.chatImage(messageId),
    });
    router.push(getChatPaywallNavigationUrl(authState.loginStatus));
  };

  const historyUnlockDialog = (
    <HistoryUnlockDialog
      open={chatState.unlockHistoryPromptVisible}
      lockedCount={chatState.lockedHistoryCount}
      isLoading={chatState.isUnlockingHistory}
      errorMessage={chatState.unlockHistoryError}
      onClose={() => chatDispatch({ type: "ChatUnlockHistoryDismissed" })}
      onConfirm={() => chatDispatch({ type: "ChatUnlockHistoryConfirmed" })}
    />
  );

  if (!message) {
    return (
      <>
        <MobileShell background="#0d0b14">
          <main className={styles.emptyScreen}>
            <button
              type="button"
              className={styles.backButton}
              onClick={handleClose}
            >
              Back to chat
            </button>
            <p className={styles.emptyText}>
              {chatState.historyLoaded ? "Image not found." : "Loading image..."}
            </p>
          </main>
        </MobileShell>
        {historyUnlockDialog}
      </>
    );
  }

  return (
    <>
      <MobileShell background="#000000">
        <FullscreenImageViewer
          messageId={messageId}
          imageUrl={message.imageUrl ?? ""}
          imagePaywalled={message.imagePaywalled === true}
          onUnlockImagePaywall={handleUnlockImagePaywall}
          onClose={handleClose}
        />
      </MobileShell>
      {historyUnlockDialog}
    </>
  );
}
