"use client";

import { shallowEqual } from "@xstate/react";

import {
  useChatDispatch,
  useChatSelector,
} from "@/stores/chat/chat-context";
import type { ChatUnlockPaywallRequest } from "@/stores/chat/chat-state";

import { HistoryUnlockDialog } from "./history-unlock-dialog";
import { InsufficientCreditsDialog } from "./insufficient-credits-dialog";

export interface ChatUnlockDialogsProps {
  unlockPaywallRequest: ChatUnlockPaywallRequest | null;
  onCloseInsufficientCreditsDialog: () => void;
  onConfirmInsufficientCreditsDialog: () => void;
  includeHistoryUnlock?: boolean;
}

export function ChatUnlockDialogs({
  unlockPaywallRequest,
  onCloseInsufficientCreditsDialog,
  onConfirmInsufficientCreditsDialog,
  includeHistoryUnlock = true,
}: ChatUnlockDialogsProps) {
  const chatState = useChatSelector(
    (state) => ({
      isUnlockingHistory: state.context.isUnlockingHistory,
      lockedHistoryCount: state.context.lockedHistoryCount,
      unlockHistoryError: state.context.unlockHistoryError,
      unlockHistoryPromptVisible: state.context.unlockHistoryPromptVisible,
    }),
    shallowEqual,
  );
  const chatDispatch = useChatDispatch();

  return (
    <>
      {includeHistoryUnlock ? (
        <HistoryUnlockDialog
          open={chatState.unlockHistoryPromptVisible}
          lockedCount={chatState.lockedHistoryCount}
          isLoading={chatState.isUnlockingHistory}
          errorMessage={chatState.unlockHistoryError}
          onClose={() => chatDispatch({ type: "ChatUnlockHistoryDismissed" })}
          onConfirm={() => chatDispatch({ type: "ChatUnlockHistoryConfirmed" })}
        />
      ) : null}
      <InsufficientCreditsDialog
        open={unlockPaywallRequest !== null}
        creditBalance={unlockPaywallRequest?.creditBalance ?? 0}
        requiredCredits={unlockPaywallRequest?.requiredCredits ?? 0}
        shortfallCredits={unlockPaywallRequest?.shortfallCredits ?? 0}
        onClose={onCloseInsufficientCreditsDialog}
        onConfirm={onConfirmInsufficientCreditsDialog}
      />
    </>
  );
}
