"use client";

import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import Header from "@/components/main/Header";
import TabNavigation from "@/components/TabNavigation";
import PageTitle from "@/components/settings/PageTitle";
import AuthNextButton from "@/components/auth/AuthNextButton";
import RoundedInput from "@/components/elements/RoundedInput";
import BuyerInfoModal from "@/components/shops/orders/BuyerInfoModal";
import ShopInfoModal from "@/components/shops/orders/ShopInfoModal";
import { IMAGE_BASE_URL, staticIconUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import Image from "next/image";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const TRACKING_REQUIRED_METHODS = ["post", "tipax", "chapar", "intercity_freight"];
const SELLER_STATUSES = ["on_hold", "processing", "shipped", "ready_for_pickup"];
/** These carriers have a public tracking page we can deep-link to. */
const BOLD_TRACKING_METHODS = ["post", "tipax", "chapar"];

function trackingUrl(method: string, code: string): string | null {
  if (method === "post") return `https://tracking.post.ir/?id=${code}`;
  if (method === "tipax") return `https://tipaxco.com/tracking?code=${code}`;
  if (method === "chapar") return `https://www.chapar.co/tracking?code=${code}`;
  return null;
}

type OrderReport = { _id: string; description: string; status: string; createdAt: string };
type ReturnRequest = { _id: string; reason: string; status: string; createdAt: string };
type ShopRating = { _id: string; rating: number; comment?: string | null };

type OrderDetail = {
  _id: string;
  order_number: string;
  quantity: number;
  unit_price: number;
  total_amount: number;
  shipping_cost: number;
  shipping_method?: string | null;
  tracking_code?: string | null;
  status: string;
  createdAt: string;
  isPaymentExpired?: boolean;
  buyer: string;
  variantId: string;
  returnWindowExpiresAt?: string | null;
  variantSnapshot: { color?: string | null; size?: string | null; weight?: string | null };
  buyerAddressSnapshot?: {
    first_name?: string | null;
    last_name?: string | null;
    mobile?: string | null;
    address?: string | null;
    province?: { name?: string } | null;
    city?: { name?: string } | null;
    lat?: string | null;
    lng?: string | null;
  } | null;
  listing: { _id: string; title: string; images: string[]; primaryImageIndex: number };
  shop: {
    _id: string;
    name: string;
    logo?: string | null;
    owner: string;
    estimated_delivery_text?: string | null;
    has_physical_location?: boolean;
    province?: { name?: string } | null;
    city?: { name?: string } | null;
    address?: string | null;
    lat?: string | null;
    lng?: string | null;
  };
};

export default function OrderDetailPage() {
  const { t } = useTranslation("common");
  const params = useParams<{ orderId: string }>();
  const searchParams = useSearchParams();
  const router = useRouter();
  const { request, loading } = useAxios();
  const user = useUser();
  const [repurchasing, setRepurchasing] = useState(false);

  const [order, setOrder] = useState<OrderDetail | null>(null);
  const [report, setReport] = useState<OrderReport | null>(null);
  const [returnRequest, setReturnRequest] = useState<ReturnRequest | null>(null);
  const [shopRating, setShopRating] = useState<ShopRating | null>(null);
  const [trackingCode, setTrackingCode] = useState("");
  const [printMode, setPrintMode] = useState<"invoice" | "label-a5" | "label-a6" | null>(
    null
  );
  const [showRating, setShowRating] = useState(false);
  const [ratingScore, setRatingScore] = useState(0);
  const [ratingComment, setRatingComment] = useState("");
  const [showReport, setShowReport] = useState(false);
  const [reportText, setReportText] = useState("");
  const [showReturn, setShowReturn] = useState(false);
  const [returnReason, setReturnReason] = useState("");
  const [showBuyerInfo, setShowBuyerInfo] = useState(false);
  const [showShopInfo, setShowShopInfo] = useState(false);

  const loadOrder = () => {
    request<{
      order: OrderDetail;
      report?: OrderReport | null;
      returnRequest?: ReturnRequest | null;
      shopRating?: ShopRating | null;
    }>("GET", `/orders/${params.orderId}`)
      .then((res) => {
        setOrder(res?.order || null);
        setTrackingCode(res?.order?.tracking_code || "");
        setReport(res?.report || null);
        setReturnRequest(res?.returnRequest || null);
        setShopRating(res?.shopRating || null);
      })
      .catch(() => setOrder(null));
  };

  useEffect(() => {
    loadOrder();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [params.orderId]);

  useEffect(() => {
    if (!printMode) return;
    const timer = setTimeout(() => {
      window.print();
      setPrintMode(null);
    }, 100);
    return () => clearTimeout(timer);
  }, [printMode]);

  const isSeller = Boolean(order && user && order.shop.owner === user._id);
  const isBuyer = Boolean(order && user && order.buyer === user._id);

  useEffect(() => {
    if (isBuyer && searchParams.get("autoDownload") === "1") {
      setPrintMode("invoice");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isBuyer]);
  const canConfirmReceipt =
    isBuyer && order && ["shipped", "ready_for_pickup"].includes(order.status);
  const canRequestReturn =
    isBuyer &&
    order?.returnWindowExpiresAt &&
    new Date() < new Date(order.returnWindowExpiresAt);

  const handleRepurchase = async () => {
    if (!order) return;
    setRepurchasing(true);
    try {
      const response = await request<{ order: { _id: string } }>("POST", "/orders/draft", {
        listingId: order.listing._id,
        variantId: order.variantId,
        quantity: order.quantity,
        shippingMethod: order.shipping_method || undefined,
      });
      if (response?.order?._id) {
        router.push(`/shops/checkout/${response.order._id}`);
      }
    } catch (err: unknown) {
      const data = (err as { response?: { data?: { code?: string; message?: string } } })
        ?.response?.data;
      toast.error(data?.message || t("shops.unknownError"));
    } finally {
      setRepurchasing(false);
    }
  };

  const handleConfirmReceipt = async () => {
    if (!order) return;
    try {
      await request("PATCH", `/orders/${order._id}/confirm-receipt`, {});
      toast.success(t("shops.receiptConfirmed"));
      loadOrder();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const handleSubmitRating = async () => {
    if (!order || ratingScore < 1) return;
    try {
      await request("POST", `/orders/${order._id}/rate`, {
        rating: ratingScore,
        comment: ratingComment || undefined,
      });
      toast.success(t("shops.ratingSubmitted"));
      setShowRating(false);
      setRatingComment("");
      loadOrder();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const handleSubmitReport = async () => {
    if (!order || !reportText.trim()) return;
    try {
      await request("POST", `/orders/${order._id}/report`, {
        description: reportText.trim(),
      });
      toast.success(t("shops.reportSubmitted"));
      setShowReport(false);
      setReportText("");
      loadOrder();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const handleSubmitReturn = async () => {
    if (!order || !returnReason.trim()) return;
    try {
      await request("POST", `/orders/${order._id}/return-request`, {
        reason: returnReason.trim(),
      });
      toast.success(t("shops.returnRequestSubmitted"));
      setShowReturn(false);
      setReturnReason("");
      loadOrder();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const handleSaveTracking = async () => {
    if (!order || !trackingCode.trim()) return;
    try {
      await request("PATCH", `/orders/${order._id}/tracking-code`, {
        tracking_code: trackingCode.trim(),
      });
      toast.success(t("shops.trackingSaved"));
      loadOrder();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const handleStatusChange = async (status: string) => {
    if (!order) return;
    if (
      status === "shipped" &&
      order.shipping_method &&
      TRACKING_REQUIRED_METHODS.includes(order.shipping_method) &&
      !trackingCode.trim()
    ) {
      toast.error(t("shops.trackingRequiredForShipping"));
      return;
    }
    try {
      await request("PATCH", `/orders/${order._id}/status`, { status });
      toast.success(t("shops.statusUpdated"));
      loadOrder();
    } 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 buyerName = [
    order.buyerAddressSnapshot?.first_name,
    order.buyerAddressSnapshot?.last_name,
  ]
    .filter(Boolean)
    .join(" ");

  const boldTracking =
    order.shipping_method && BOLD_TRACKING_METHODS.includes(order.shipping_method);
  const trackingHref =
    order.tracking_code && order.shipping_method && boldTracking
      ? trackingUrl(order.shipping_method, order.tracking_code)
      : null;

  return (
    <>
      <Header />
      <LocalePageShell>
        <Container className="pb-28">
          <div className="no-print">
            <PageTitle>{t("shops.orderDetailTitle")}</PageTitle>
            <p className="mx-auto -mt-2 mb-2 max-w-md text-center text-xs text-neutral-500">
              {t("shops.orderNumberLabel")}: {order.order_number}
            </p>

            <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>
                  <p className="text-xs text-neutral-500">
                    {order.total_amount.toLocaleString()} {t("settings.toman")}
                  </p>
                </div>
              </div>

              {isSeller && (
                <button
                  type="button"
                  onClick={() => setShowBuyerInfo(true)}
                  className="rounded-2xl border border-neutral-200 p-3 text-right text-sm dark:border-neutral-700"
                >
                  <p className="font-semibold">{t("shops.buyerInfoTitle")}</p>
                  <p className="mt-1 text-xs text-neutral-500">{buyerName}</p>
                </button>
              )}

              {isBuyer && (
                <button
                  type="button"
                  onClick={() => setShowShopInfo(true)}
                  className="rounded-2xl border border-neutral-200 p-3 text-right text-sm dark:border-neutral-700"
                >
                  <p className="font-semibold">{t("shops.shopInfoTitle")}</p>
                  <p className="mt-1 text-xs text-neutral-500">{order.shop.name}</p>
                </button>
              )}

              <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.shippingTimeLabel")}</span>
                  <span>
                    {[order.createdAt, order.shop.estimated_delivery_text]
                      .filter(Boolean)
                      .join(" ")}
                  </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>
                )}
                {order.tracking_code && (
                  <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.trackingCodeLabel")}</span>
                    {trackingHref ? (
                      <a
                        href={trackingHref}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="font-bold text-blue-600 underline dark:text-blue-400"
                      >
                        {order.tracking_code}
                      </a>
                    ) : (
                      <span>{order.tracking_code}</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.grandTotalLabel")}</span>
                  <span className="font-bold text-green-600">
                    {order.total_amount.toLocaleString()} {t("settings.toman")}
                  </span>
                </div>
              </div>

              {isSeller && (
                <AuthNextButton type="button" onClick={() => setPrintMode("invoice")}>
                  {t("shops.printInvoice")}
                </AuthNextButton>
              )}

              {isBuyer && (
                <AuthNextButton type="button" onClick={() => setPrintMode("invoice")}>
                  {t("shops.downloadInvoice")}
                </AuthNextButton>
              )}

              {isSeller && (
                <div className="flex gap-2">
                  <AuthNextButton
                    type="button"
                    className="flex-1"
                    onClick={() => setPrintMode("label-a5")}
                  >
                    {t("shops.printLabelA5")}
                  </AuthNextButton>
                  <AuthNextButton
                    type="button"
                    className="flex-1"
                    onClick={() => setPrintMode("label-a6")}
                  >
                    {t("shops.printLabelA6")}
                  </AuthNextButton>
                </div>
              )}

              {isSeller && (
                <>
                  <div>
                    <p className="mb-1 text-xs font-semibold">{t("shops.trackingCodeLabel")}</p>
                    <div className="flex gap-2">
                      <RoundedInput
                        type="text"
                        value={trackingCode}
                        onChange={(e) => setTrackingCode(e.target.value)}
                      />
                      <AuthNextButton
                        type="button"
                        loading={loading}
                        disabled={loading}
                        onClick={handleSaveTracking}
                      >
                        {t("common.save")}
                      </AuthNextButton>
                    </div>
                  </div>

                  <div>
                    <p className="mb-1 text-xs font-semibold">{t("shops.changeStatusLabel")}</p>
                    <div className="flex flex-wrap gap-2">
                      {SELLER_STATUSES.map((status) => (
                        <button
                          key={status}
                          type="button"
                          onClick={() => handleStatusChange(status)}
                          className={`rounded-full border px-3 py-1 text-xs ${
                            order.status === status
                              ? "border-pink-500 bg-pink-500 text-white"
                              : "border-neutral-300 dark:border-neutral-600"
                          }`}
                        >
                          {t(`shops.orderStatus.${status}`)}
                        </button>
                      ))}
                    </div>
                  </div>

                  {report && (
                    <div className="rounded-2xl border border-amber-300 bg-amber-50 p-3 text-xs dark:border-amber-700 dark:bg-amber-950/30">
                      <p className="mb-1 font-semibold">{t("shops.reportStatusTitle")}</p>
                      <p className="text-neutral-600 dark:text-neutral-300">{report.description}</p>
                      <p className="mt-1 text-neutral-500">
                        {t(`shops.reportStatus.${report.status}`)}
                      </p>
                    </div>
                  )}

                  {returnRequest && (
                    <div className="rounded-2xl border border-neutral-200 p-3 text-xs dark:border-neutral-700">
                      <p className="mb-1 font-semibold">{t("shops.returnStatusTitle")}</p>
                      <p className="text-neutral-600 dark:text-neutral-300">{returnRequest.reason}</p>
                      <p className="mt-1 text-neutral-500">
                        {t(`shops.returnStatus.${returnRequest.status}`)}
                      </p>
                    </div>
                  )}
                </>
              )}

              {isBuyer && order.status === "pending_payment" && (
                <AuthNextButton
                  type="button"
                  loading={repurchasing}
                  disabled={repurchasing}
                  onClick={() =>
                    order.isPaymentExpired
                      ? handleRepurchase()
                      : router.push(`/shops/checkout/${order._id}`)
                  }
                >
                  {order.isPaymentExpired
                    ? t("shops.repurchase")
                    : t("shops.completePurchase")}
                </AuthNextButton>
              )}

              {isBuyer && order.status !== "pending_payment" && (
                <>
                  {canConfirmReceipt && (
                    <AuthNextButton type="button" onClick={handleConfirmReceipt}>
                      {t("shops.confirmReceipt")}
                    </AuthNextButton>
                  )}

                  {shopRating ? (
                    <div className="rounded-2xl border border-neutral-200 p-3 text-xs dark:border-neutral-700">
                      <p className="mb-1 flex items-center gap-1 font-semibold">
                        {t("shops.yourRatingLabel")}: {shopRating.rating}
                        <Image
                          src={staticIconUrl("/images/icons/star1.png")}
                          alt=""
                          width={14}
                          height={14}
                        />
                      </p>
                      {shopRating.comment && (
                        <p className="text-neutral-600 dark:text-neutral-300">
                          {shopRating.comment}
                        </p>
                      )}
                    </div>
                  ) : (
                    <>
                      <AuthNextButton type="button" onClick={() => setShowRating((v) => !v)}>
                        {t("shops.rateShop")}
                      </AuthNextButton>
                      {showRating && (
                        <div className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                          <div className="mb-2 flex items-center justify-center gap-1">
                            {[1, 2, 3, 4, 5].map((n) => (
                              <button
                                key={n}
                                type="button"
                                onClick={() => setRatingScore(n === ratingScore ? 0 : n)}
                                className="p-0.5"
                              >
                                <Image
                                  src={staticIconUrl("/images/icons/star1.png")}
                                  alt=""
                                  width={24}
                                  height={24}
                                  className={n <= ratingScore ? "opacity-100" : "opacity-30"}
                                />
                              </button>
                            ))}
                          </div>
                          <textarea
                            className="h-20 w-full rounded-2xl border border-neutral-300 bg-white p-2 text-xs dark:border-neutral-600 dark:bg-neutral-950"
                            placeholder={t("shops.ratingCommentPlaceholder")}
                            value={ratingComment}
                            onChange={(e) => setRatingComment(e.target.value)}
                          />
                          <AuthNextButton
                            type="button"
                            className="mt-2"
                            disabled={ratingScore < 1}
                            onClick={handleSubmitRating}
                          >
                            {t("common.save")}
                          </AuthNextButton>
                        </div>
                      )}
                    </>
                  )}

                  {report ? (
                    <div className="rounded-2xl border border-neutral-200 p-3 text-xs dark:border-neutral-700">
                      <p className="mb-1 font-semibold">{t("shops.reportStatusTitle")}</p>
                      <p className="text-neutral-600 dark:text-neutral-300">{report.description}</p>
                      <p className="mt-1 text-neutral-500">
                        {t(`shops.reportStatus.${report.status}`)}
                      </p>
                    </div>
                  ) : (
                    <>
                      <AuthNextButton type="button" onClick={() => setShowReport((v) => !v)}>
                        {t("shops.reportProblem")}
                      </AuthNextButton>
                      {showReport && (
                        <div className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                          <textarea
                            className="h-20 w-full rounded-2xl border border-neutral-300 bg-white p-2 text-xs dark:border-neutral-600 dark:bg-neutral-950"
                            placeholder={t("shops.reportPlaceholder")}
                            value={reportText}
                            onChange={(e) => setReportText(e.target.value)}
                          />
                          <AuthNextButton
                            type="button"
                            className="mt-2"
                            onClick={handleSubmitReport}
                          >
                            {t("shops.submitReport")}
                          </AuthNextButton>
                        </div>
                      )}
                    </>
                  )}

                  {returnRequest ? (
                    <div className="rounded-2xl border border-neutral-200 p-3 text-xs dark:border-neutral-700">
                      <p className="mb-1 font-semibold">{t("shops.returnStatusTitle")}</p>
                      <p className="text-neutral-600 dark:text-neutral-300">{returnRequest.reason}</p>
                      <p className="mt-1 text-neutral-500">
                        {t(`shops.returnStatus.${returnRequest.status}`)}
                      </p>
                    </div>
                  ) : (
                    canRequestReturn && (
                      <>
                        <AuthNextButton type="button" onClick={() => setShowReturn((v) => !v)}>
                          {t("shops.requestReturn")}
                        </AuthNextButton>
                        {showReturn && (
                          <div className="rounded-2xl border border-neutral-200 p-3 dark:border-neutral-700">
                            <textarea
                              className="h-20 w-full rounded-2xl border border-neutral-300 bg-white p-2 text-xs dark:border-neutral-600 dark:bg-neutral-950"
                              placeholder={t("shops.returnReasonPlaceholder")}
                              value={returnReason}
                              onChange={(e) => setReturnReason(e.target.value)}
                            />
                            <AuthNextButton
                              type="button"
                              className="mt-2"
                              onClick={handleSubmitReturn}
                            >
                              {t("shops.submitReturn")}
                            </AuthNextButton>
                          </div>
                        )}
                      </>
                    )
                  )}
                </>
              )}
            </div>
          </div>

          {printMode === "invoice" && (
            <div className="print-only">
              <div className="p-6 text-sm">
                <p className="mb-4 text-lg font-bold">{t("shops.invoiceTitle")}</p>
                <p>{order.listing.title}</p>
                <p>
                  {t("shops.quantityLabel")}: {order.quantity}
                </p>
                <p>
                  {order.total_amount.toLocaleString()} {t("settings.toman")}
                </p>
                <p className="mt-4">{buyerName}</p>
                <p>{order.createdAt}</p>
              </div>
            </div>
          )}

          {(printMode === "label-a5" || printMode === "label-a6") && (
            <div className="print-only">
              <div className="p-6 text-sm">
                <p className="mb-4 text-lg font-bold">{order.shop.name}</p>
                <p>{t("shops.buyerInfoTitle")}:</p>
                <p>{buyerName}</p>
                <p>
                  {order.buyerAddressSnapshot?.province?.name}{" "}
                  {order.buyerAddressSnapshot?.city?.name}
                </p>
                <p>{order.buyerAddressSnapshot?.address}</p>
                {order.tracking_code && (
                  <p className="mt-4">
                    {t("shops.trackingCodeLabel")}: {order.tracking_code}
                  </p>
                )}
              </div>
            </div>
          )}

          <style>{`
            .print-only { display: none; }
            @media print {
              .no-print { display: none !important; }
              .print-only { display: block !important; }
              @page { size: ${printMode === "label-a6" ? "A6" : "A5"}; }
            }
          `}</style>
        </Container>
      </LocalePageShell>
      <TabNavigation currentPage="/settings" />
      <BuyerInfoModal
        isOpen={showBuyerInfo}
        onClose={() => setShowBuyerInfo(false)}
        buyer={order.buyerAddressSnapshot}
      />
      <ShopInfoModal
        isOpen={showShopInfo}
        onClose={() => setShowShopInfo(false)}
        shop={order.shop}
      />
    </>
  );
}
