"use client";

import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import PageTitle from "@/components/settings/PageTitle";
import AuthNextButton from "@/components/auth/AuthNextButton";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Image from "next/image";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type OrderDetail = {
  _id: string;
  createdAt: string;
  quantity: number;
  unit_price: number;
  total_amount: number;
  shipping_cost: number;
  shipping_method?: string | null;
  variantSnapshot: { color?: string | null; size?: string | null; weight?: string | null };
  listing: {
    title: string;
    images: string[];
    primaryImageIndex: number;
  };
  shop: {
    name: string;
    estimated_delivery_text?: string | null;
  };
};

export default function CheckoutPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ orderId: string }>();
  const { request, loading } = useAxios();
  const [order, setOrder] = useState<OrderDetail | null>(null);

  useEffect(() => {
    request<{ order: OrderDetail }>("GET", `/orders/${params.orderId}`)
      .then((res) => setOrder(res?.order || null))
      .catch(() => setOrder(null));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [params.orderId]);

  const handlePay = async () => {
    try {
      const response = await request<{ authority?: string }>(
        "POST",
        "/payment/shop-order/initiate",
        { orderId: params.orderId }
      );
      if (response?.authority) {
        router.push(`https://www.zarinpal.com/pg/StartPay/${response.authority}`);
      }
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!order) return null;

  const primaryImage =
    order.listing.images?.[order.listing.primaryImageIndex] ||
    order.listing.images?.[0];
  const variantLabel = [
    order.variantSnapshot.color,
    order.variantSnapshot.size,
    order.variantSnapshot.weight,
  ]
    .filter(Boolean)
    .join(" / ");

  const itemsSubtotal = order.total_amount - order.shipping_cost;

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("shops.checkoutTitle")}</PageTitle>

        <div className="mx-auto flex max-w-md flex-col gap-4">
          <div className="flex items-center gap-3 rounded-2xl border border-neutral-200 p-2 dark:border-neutral-700">
            {primaryImage && (
              <div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-xl bg-neutral-200 dark:bg-neutral-800">
                <Image
                  src={IMAGE_BASE_URL + primaryImage}
                  alt={order.listing.title}
                  fill
                  className="object-cover"
                  sizes="64px"
                  unoptimized
                />
              </div>
            )}
            <div className="min-w-0">
              <p className="truncate text-sm font-semibold">
                {order.listing.title}{" "}
                <span className="font-normal text-neutral-500">× {order.quantity}</span>
              </p>
              {variantLabel && (
                <p className="text-xs text-neutral-500">{variantLabel}</p>
              )}
              <p className="text-xs text-neutral-500">{order.shop.name}</p>
            </div>
          </div>

          <div className="rounded-2xl border border-neutral-200 p-4 text-sm dark:border-neutral-700">
            <div className="flex items-center justify-between border-b border-neutral-100 py-2 dark:border-neutral-800">
              <span className="text-neutral-500">{t("shops.itemsTotal")}</span>
              <span>
                {itemsSubtotal.toLocaleString()} {t("settings.toman")}
              </span>
            </div>
            <div className="flex items-center justify-between border-b border-neutral-100 py-2 dark:border-neutral-800">
              <span className="text-neutral-500">{t("shops.shippingTimeLabel")}</span>
              <span>{order.shop.estimated_delivery_text || "—"}</span>
            </div>
            {order.shipping_method && (
              <div className="flex items-center justify-between border-b border-neutral-100 py-2 dark:border-neutral-800">
                <span className="text-neutral-500">{t("shops.shippingTypeLabel")}</span>
                <span>{t(`shops.shippingMethods.${order.shipping_method}`)}</span>
              </div>
            )}
            <div className="flex items-center justify-between border-b border-neutral-100 py-2 dark:border-neutral-800">
              <span className="text-neutral-500">{t("shops.shippingCostLabel")}</span>
              <span>
                {order.shipping_cost.toLocaleString()} {t("settings.toman")}
              </span>
            </div>
            <div className="flex items-center justify-between pt-2">
              <span className="font-semibold">{t("shops.payOnlineTotal")}</span>
              <span className="font-bold text-green-600">
                {order.total_amount.toLocaleString()} {t("settings.toman")}
              </span>
            </div>
          </div>

          <AuthNextButton
            type="button"
            loading={loading}
            disabled={loading}
            onClick={handlePay}
          >
            {t("shops.proceedToPayment")}
          </AuthNextButton>
        </div>
      </Container>
    </LocalePageShell>
  );
}
