"use client";

import { useEffect, useState } from "react";
import SectionTitle from "@/components/Shared/SectionTitle/Index";
import GlobalActions from "@/components/Shared/GlobalActions/Index";
import { useRouter } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import { FaExclamationCircle } from "react-icons/fa";
import ReservationSummary from "@/components/sections/ConfirmationPage/ReservationSummary/Index";
import type { StoreOrderResponse, OrderData } from "@/types/booking";
import { retryPayment } from "@/actions/bookingActions";
import { useTranslations as useTranslationsCommon } from "next-intl";
import { formatApiErrorMessage } from "@/lib/apiUtils";
import ApiErrorAlert from "@/components/Shared/ApiErrorAlert/Index";

export default function PaymentFailedSection() {
  const router = useRouter();
  const locale = useLocale();
  const t = useTranslations("PaymentFailedPage");
  const tCommon = useTranslationsCommon("Common");
  const [orderData, setOrderData] = useState<OrderData | null>(null);
  const [isRetrying, setIsRetrying] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const storedResponse = sessionStorage.getItem("orderResponse");

      if (storedResponse) {
        try {
          const response: StoreOrderResponse = JSON.parse(storedResponse);

          if (
            response &&
            response.data &&
            response.data.order &&
            !Array.isArray(response.data.order)
          ) {
            setOrderData(response.data.order as OrderData);
          }
        } catch (error) {
          console.error("Error parsing order response:", error);
        }
      }
    }
  }, []);

  const handleTryAgain = async () => {
    // Clear previous error
    setErrorMessage(null);

    // Validate that orderData exists and has a valid order_id
    if (!orderData || !orderData.id || orderData.id === 0 || isRetrying) {
      if (!orderData || !orderData.id || orderData.id === 0) {
        setErrorMessage(tCommon("noOrderDataAvailable"));
      }
      return;
    }

    setIsRetrying(true);

    try {
      const response = await retryPayment(orderData.id, locale);

      // Check if the operation was successful (status === 1)
      // Success response: { status: 1, message: "success", data: { order: {...}, payment_url: "..." } }
      // Error response: { status: 0, message: "failed", data: { field1: ["error1"], field2: ["error2"] } }
      if (response.status === 1) {
        // Store order response in sessionStorage only if successful
        if (typeof window !== "undefined") {
          sessionStorage.setItem("orderResponse", JSON.stringify(response));
        }

        // If payment_url exists, redirect to payment page
        if (
          response.data?.payment_url &&
          typeof response.data.payment_url === "string"
        ) {
          window.location.href = response.data.payment_url;
        } else {
          // If no payment_url, show error
          setErrorMessage(tCommon("failedToCreateOrder"));
          setIsRetrying(false);
        }
      } else {
        // Operation failed (status === 0), show formatted error message
        const formattedError = formatApiErrorMessage(
          response,
          tCommon("failedToCreateOrder"),
        );
        setErrorMessage(formattedError);
        setIsRetrying(false);
      }
    } catch (error) {
      console.error("Error retrying payment:", error);
      setErrorMessage(tCommon("failedToCreateOrder"));
      setIsRetrying(false);
    }
  };

  const handleGoToHome = () => {
    router.push("/ticket");
  };

  return (
    <section className="flex flex-col gap-5 md:gap-10">
      <div className="flex items-center gap-2 sm:gap-3">
        <FaExclamationCircle className="text-red-500 w-10 h-10 sm:w-12 sm:h-12 md:w-16 md:h-16 flex-shrink-0" />
        <SectionTitle title={t("title")} />
      </div>

      {errorMessage && (
        <ApiErrorAlert
          message={errorMessage}
          onClose={() => setErrorMessage(null)}
        />
      )}

      <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 sm:p-5 md:p-6 flex flex-col gap-2 sm:gap-3">
        <p className="text-[16px] sm:text-[18px] md:text-[20px] text-red-800 dark:text-red-200 font-medium leading-relaxed">
          {t("failureMessage")}
        </p>
        <p className="text-[14px] sm:text-[15px] md:text-[16px] text-red-700 dark:text-red-300 leading-relaxed">
          {t("failureDescription")}
        </p>
      </div>

      {orderData && (
        <div className="flex flex-col gap-4">
          <ReservationSummary orderData={orderData} />
        </div>
      )}

      <div className="w-full">
        <GlobalActions
          continueText={isRetrying ? tCommon("loading") : t("tryAgain")}
          cancelText={t("goToHome")}
          onContinue={handleTryAgain}
          onCancel={handleGoToHome}
          isContinueDisabled={
            isRetrying || !orderData || !orderData.id || orderData.id === 0
          }
        />
      </div>
    </section>
  );
}
