// app/(lib)/services/thankYouPageService.ts
import { apiClient } from "../../app/api/client";
import { handleAPIError } from "../utils/apiErrorHandler";

export interface ThankYouPageContentInfo {
  // Hero
  greetingText?: string;
  paymentSuccessSubheadingText?: string;
  paylaterSuccessSubheadingText?: string;
  setupSuccessSubheadingText?: string;
  // Verifying state
  verifyingPaymentText?: string;
  verifyingSetupText?: string;
  paymentProcessingText?: string;
  paymentVerifyingHintText?: string;
  paymentVerifyingSecureText?: string;
  // Failed state
  paymentFailedHeadingText?: string;
  paymentFailedText?: string;
  // Success card
  mainHeadingText?: string;
  mainSubheadingText?: string;
  // Section headings
  recipientSectionLabel?: string;
  programSectionLabel?: string;
  paymentSectionLabel?: string;
  // Detail row labels
  orderNumberLabel?: string;
  programNameLabel?: string;
  studyPeriodLabel?: string;
  numberOfLessonsLabel?: string;
  classScheduleLabel?: string;
  parentNameLabel?: string;
  parentEmailLabel?: string;
  childNameLabel?: string;
  totalValueLabel?: string;
  pricePerLessonLabel?: string;
  paymentFrequencyLabel?: string;
  couponAppliedLabel?: string;
  paidLabel?: string;
  paymentDateLabel?: string;
  paymentMethodLabel?: string;
  // Actions
  downloadReceiptText?: string;
  downloadInvoiceText?: string;
}

export interface ThankYouPageContent {
  thankYouPage?: ThankYouPageContentInfo;
}

export interface ThankYouPageData {
  id: string;
  franchisee_id: string | null;
  is_global: boolean;
  title: string;
  slug: string;
  template_id: string;
  content: ThankYouPageContent;
  translated_content?: ThankYouPageContent;
  status: string;
  seo_title?: string | null;
  seo_description?: string | null;
}

export interface ThankYouPageDataWithTranslations {
  default: ThankYouPageContent;
  translated?: ThankYouPageContent;
}

const DEFAULTS: ThankYouPageContentInfo = {
  greetingText: "Thank You!",
  paymentSuccessSubheadingText: "Your payment has been received successfully.",
  paylaterSuccessSubheadingText: "Your submission has been received successfully.",
  setupSuccessSubheadingText: "Your account has been setup successfully.",
  verifyingPaymentText: "Verifying your payment",
  verifyingSetupText: "Verifying your account setup",
  paymentProcessingText:
    "Please wait while we securely confirm your transaction with our payment provider. This usually takes only a few moments.",
  paymentVerifyingHintText: "Please do not close or refresh this page.",
  paymentVerifyingSecureText: "Secure payment verification",
  paymentFailedHeadingText: "Payment Failed",
  paymentFailedText:
    "Your payment could not be completed. Please try again or contact support.",
  mainHeadingText: "Thank You! Your payment was successful",
  mainSubheadingText: "Our manager will contact you for more details.",
  recipientSectionLabel: "Recipient",
  programSectionLabel: "Program",
  paymentSectionLabel: "Payment",
  orderNumberLabel: "Order number",
  programNameLabel: "Program name",
  studyPeriodLabel: "Study period",
  numberOfLessonsLabel: "Number of lessons",
  classScheduleLabel: "Class Schedule",
  parentNameLabel: "Parent",
  parentEmailLabel: "Email",
  childNameLabel: "Child",
  totalValueLabel: "Total value of the class",
  pricePerLessonLabel: "Price",
  paymentFrequencyLabel: "Payment frequency",
  couponAppliedLabel: "Coupon applied",
  paidLabel: "Paid",
  paymentDateLabel: "Payment date",
  paymentMethodLabel: "Payment method",
  downloadReceiptText: "Download Receipt",
  downloadInvoiceText: "Download Invoice",
};

export class ThankYouPageService {
  // Matches the page slug created in the admin ("Thank You" → "thank-you").
  // The template slug is "thank-you-page", but pages are fetched by the page slug.
  private readonly endpoint = "pages/thank-you";

  async fetchByDomain(domain: string, franchiseeId?: string | null, language?: string | null): Promise<ThankYouPageDataWithTranslations> {
    const startTime = Date.now();

    try {
      const params: Record<string, string> = {};
      if (franchiseeId) params.franchiseeId = franchiseeId;
      if (language && language !== "default") params.lang = language;

      const response = await apiClient.get<{ status: boolean; data: ThankYouPageData }>(
        this.endpoint,
        {
          headers: { "X-Domain": domain },
          params: Object.keys(params).length > 0 ? params : undefined,
        }
      );

      if (!response.data?.status || !response.data?.data?.content) {
        return this.getDefaultData();
      }

      const elapsed = Date.now() - startTime;

      return {
        default: response.data.data.content,
        translated: response.data.data.translated_content || undefined,
      };
    } catch (error) {
      return handleAPIError(error, domain, startTime, this.getDefaultData.bind(this));
    }
  }

  private async getDefaultData(): Promise<ThankYouPageDataWithTranslations> {
    return {
      default: { thankYouPage: DEFAULTS },
      translated: undefined,
    };
  }
}

export const thankYouPageService = new ThankYouPageService();
