"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import Image from "next/image";
import { useTranslation } from "react-i18next";

export default function ShopPaymentFailedPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const searchParams = useSearchParams();
  const orderId = searchParams.get("orderId");
  const [shopId, setShopId] = useState<string | null>(null);

  useEffect(() => {
    if (!orderId) return;
    request<{ order: { shop: { _id: string } | string } }>(
      "GET",
      `/orders/${orderId}`,
      null,
      { noToast: true }
    )
      .then((res) => {
        const shop = res?.order?.shop;
        setShopId(typeof shop === "object" ? shop._id : shop || null);
      })
      .catch(() => setShopId(null));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orderId]);

  const retry = async () => {
    if (!orderId) return;
    try {
      const response = await request<{ authority?: string }>(
        "POST",
        "/payment/shop-order/initiate",
        { orderId }
      );
      if (response?.authority) {
        router.push(`https://www.zarinpal.com/pg/StartPay/${response.authority}`);
      }
    } catch {
      // toast already shown by the axios interceptor
    }
  };

  return (
    <LocalePageShell>
      <Container>
        <h6 className="mb-4 mt-2 text-center text-lg font-bold text-red-600 md:text-xl">
          {t("shops.paymentFailedTitle")}
        </h6>
        <div className="flex flex-col items-center text-sm">
          <Image
            width={50}
            height={50}
            alt=""
            src="/images/icons/failed.svg"
            className="mb-5 pb-1"
          />
          <span>{t("shops.paymentFailedHint")}</span>
        </div>
        <div className="mt-10 flex flex-col items-center gap-4">
          <RoundedButton
            variant="primary"
            className="h-9 w-32"
            onClick={retry}
            disabled={loading || !orderId}
          >
            {t("shops.retryPayment")}
          </RoundedButton>
          <RoundedButton
            className="!border-transparent h-9 w-32 !bg-neutral-100 text-neutral-600 dark:!bg-neutral-800 dark:text-neutral-300"
            onClick={() =>
              router.push(shopId ? `/shops/profile/${shopId}` : "/shops/discover")
            }
          >
            {t("shops.backToShopList")}
          </RoundedButton>
        </div>
      </Container>
    </LocalePageShell>
  );
}
