"use client";
import React, { useEffect, useState } from "react";
import Sidebar from "@/components/Sidebar";
import Footer from "@/components/Footer";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";

type OrderDetailCopy =
  (typeof staticCopy.orderDetailPage)[keyof typeof staticCopy.orderDetailPage];

function getTrackingSteps(order: any, t: OrderDetailCopy) {
  const na = "N/A";
  const isDelivered = order.delivered_at_label !== na;
  const isOutForDelivery = order.out_for_delivery_at_label !== na || isDelivered;
  const isInTransit = order.shipped_at_label !== na || order.in_transit_at_label !== na || isOutForDelivery;
  const isPreparing = order.preparing_at_label !== na || isInTransit;

  return [
    {
      id: "placed",
      title: t.stepPlacedTitle,
      description: t.stepPlacedDescription,
      date: order.placed_at_label || t.notAvailable,
      status: "done",
      color: "green",
    },
    {
      id: "preparing",
      title: t.stepPreparingTitle,
      description: t.stepPreparingDescription,
      date: order.preparing_at_label !== na ? order.preparing_at_label : isPreparing ? t.completed : t.pending,
      status: isPreparing ? "done" : "pending",
      color: "orange",
    },
    {
      id: "transit",
      title: t.stepTransitTitle,
      description: t.stepTransitDescription,
      date:
        order.shipped_at_label !== na
          ? order.shipped_at_label
          : order.in_transit_at_label !== na
            ? order.in_transit_at_label
            : isInTransit
              ? t.completed
              : t.pending,
      status: isInTransit ? "done" : "pending",
      color: "blue",
    },
    {
      id: "delivery",
      title: t.stepDeliveryTitle,
      description: t.stepDeliveryDescription,
      date: order.out_for_delivery_at_label !== na ? order.out_for_delivery_at_label : isOutForDelivery ? t.completed : t.pending,
      status: isOutForDelivery ? "done" : "pending",
      color: "blue",
    },
    {
      id: "delivered",
      title: t.stepDeliveredTitle,
      description: t.stepDeliveredDescription,
      date: order.delivered_at_label || t.pending,
      status: isDelivered ? "done" : "pending",
      color: "green",
    },
  ];
}

function IconDownload() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="7 10 12 15 17 10" />
      <line x1="12" y1="15" x2="12" y2="3" />
    </svg>
  );
}

function IconCheck() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12" />
    </svg>
  );
}

function IconTruck() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2" />
      <path d="M15 18h2" />
      <path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14" />
    </svg>
  );
}

function IconTruckLarge() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2" />
      <path d="M15 18h2" />
      <path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14" />
    </svg>
  );
}

async function downloadPdf(url: string, filename: string) {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
  };

  try {
    const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
    const user = raw ? JSON.parse(raw) : null;
    const token = String(user?.token ?? user?.access_token ?? "").trim();
    if (token) headers.Authorization = `Bearer ${token}`;
  } catch {}

  const res = await fetch(url, {
    method: "GET",
    headers,
    credentials: "include",
  });

  if (!res.ok) throw new Error("Failed to download PDF");

  const blob = await res.blob();
  const objectUrl = window.URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = objectUrl;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();

  window.URL.revokeObjectURL(objectUrl);
}

function OrderDetailPage({ orderId }: { orderId: string }) {
  const [order, setOrder] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

  const t =
    staticCopy.orderDetailPage[uiLocale as keyof typeof staticCopy.orderDetailPage] ??
    staticCopy.orderDetailPage["en-EN"];

  useEffect(() => {
    const syncLocale = () => setUiLocale(getStoredLocale());
    syncLocale();
    window.addEventListener("storage", syncLocale);
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => {
      window.removeEventListener("storage", syncLocale);
      window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    };
  }, []);

  useEffect(() => {
    const fetchOrder = async () => {
      const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
      if (!base) return;

      try {
        const headers: Record<string, string> = {
          "Content-Type": "application/json",
          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        };

        const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
        const user = raw ? JSON.parse(raw) : null;
        const authTok = String(user?.token ?? user?.access_token ?? "").trim();
        if (authTok) headers.Authorization = `Bearer ${authTok}`;

        const res = await fetch(`${base}/store/customers/my-orders`, {
          headers,
          credentials: "include",
          cache: "no-store",
        });

        if (res.ok) {
          const json = await res.json();
          const list = json.orders || (json.data && json.data.orders) || [];
          console.log(list);
          const found = list.find((o: any) => o.id === orderId);
          if (found) {
            setOrder(found);
          }
        }
      } catch (error) {
      } finally {
        setLoading(false);
      }
    };

    fetchOrder();
  }, [orderId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px] text-[#053F31] font-lexend">
        {t.loading}
      </div>
    );
  }

  if (!order) {
    return (
      <div className="flex items-center justify-center min-h-[400px] text-red-500 font-lexend">
        {t.notFound}
      </div>
    );
  }

  const trackingSteps = getTrackingSteps(order, t);

  const handleDownloadInvoice = async () => {
    const id = order.id ?? orderId;
    if (!id) return;
    const invoiceUrl = order.invoice_url ?? `/store/orders/${id}/invoice`;
    try {
      const fullUrl = invoiceUrl.startsWith("http")
        ? invoiceUrl
        : `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}${invoiceUrl}`;
      await downloadPdf(fullUrl, `invoice-${id}.pdf`);
    } catch {
    }
  };

  return (
    <>
      <main className="px-4 pt-6 pb-20 md:pr-8">
        <div className="min-h-screen flex items-start gap-6 xl:max-w-[1240px] 2xl:max-w-[1440px] sm:mx-auto">
          <Sidebar />

          <div className="w-full pb-24 md:pb-10">
            <div className="mb-3 font-lexend text-[18px] mb-10 md:mb-12 border-b border-[#DDDDDD] pb-[20px] mb-[20px] xl:pb-[30px] xl:mb-[30px] text-[#053F31]">{t.pageTitle.replace("{orderNo}", String(order.order_no || orderId))}</div>

            <div className="flex flex-col lg:flex-row gap-4 md:gap-6 lg:gap-8">
              <section className="flex-1 min-w-0 rounded-[20px] bg-white shadow-[0_4px_20px_rgba(0,0,0,0.06)] p-4 md:p-6 border border-[#E6E6E6]/60 transition-all duration-300">
                <h3 className="font-outfit font-bold text-[#053F31] text-base md:text-lg mb-3 md:mb-4 pb-3 border-b border-[#E6E6E6]">
                  {t.orderInformation}
                </h3>
                <dl className="space-y-0 font-outfit">
                  {[
                    { label: t.labelProduct, value: order.product_name },
                    {
                      label: t.labelProductCertification,
                      value:
                        order.product_tags && order.product_tags.length > 0
                          ? order.product_tags.join(", ")
                          : order.product_tag || t.notAvailable,
                    },
                    { label: t.labelCode, value: order.product_type_label || order.product_type || "" },
                    { label: t.labelQuantity, value: order.quantity_label || `${order.quantity} ${order.quantity_unit}` },
                    { label: t.labelUnitPrice, value: order.unit_price_label || `€${order.unit_price}` },
                    { label: t.labelTotalAmount, value: order.amount_label },
                    {
                      label: t.labelOrderDate,
                      value: order.date_label || new Date(order.created_at).toLocaleDateString(),
                    },
                    { label: t.labelStatus, value: order.status_label },
                    {
                      label: t.labelPaymentStatus,
                      value: order.payment_status
                        ? order.payment_status.charAt(0).toUpperCase() + order.payment_status.slice(1)
                        : t.paymentPending,
                    },
                    {
                      label: t.labelPaymentMethod,
                      value: order.payment_card_brand
                        ? `${order.payment_card_brand.charAt(0).toUpperCase() + order.payment_card_brand.slice(1)} ${t.paymentEndingIn} ${order.payment_card_last4}`
                        : t.standardPayment,
                    },
                  ].map(({ label, value }) => (
                    <div key={label} className="flex justify-between items-start gap-3 py-3 border-b border-[#E6E6E6] last:border-b-0">
                      <dt className="text-[#053F31] font-medium shrink-0 text-sm md:text-base">{label}</dt>
                      <dd className="text-[#757575] text-right text-sm md:text-base break-words min-w-0 max-w-[60%]">{value}</dd>
                    </div>
                  ))}
                </dl>
                <div className="flex flex-col gap-3 mt-5 md:mt-6 sm:flex-row">
                  <button
                    type="button"
                    onClick={handleDownloadInvoice}
                    disabled={!order.id}
                    className="w-full sm:w-auto inline-flex items-center justify-center gap-2 cursor-pointer rounded-[50px] border-2 border-[#053F31] bg-white text-[#053F31] font-outfit font-semibold py-3.5 px-5 hover:bg-[#F7FAF8] transition-colors min-h-[48px] disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {t.downloadInvoice}
                    <IconDownload />
                  </button>
                </div>
              </section>

              <section className="flex-1 min-w-0 rounded-[20px] bg-white shadow-[0_4px_20px_rgba(0,0,0,0.06)] p-4 md:p-6 border border-[#E6E6E6]/60">
                <h3 className="font-outfit font-bold text-[#053F31] text-base md:text-lg mb-3 md:mb-4 pb-3 border-b border-[#E6E6E6]">
                  {t.transportTracking}
                </h3>

                <div className="relative pl-6 md:pl-8 space-y-0">
                  {trackingSteps.map((step, index) => {
                    const isDone = step.status === "done";
                    const isLast = index === trackingSteps.length - 1;
                    const lineBorderColor =
                      step.color === "green"
                        ? "border-[#053F31]"
                        : step.color === "orange"
                          ? "border-[#f97316]"
                          : step.color === "blue"
                            ? "border-[#3b82f6]"
                            : "border-[#E6E6E6]";
                    const pillBg = isDone
                      ? (step.color === "green"
                        ? "bg-[#053F31] text-white"
                        : step.color === "orange"
                          ? "bg-[#f97316] text-white"
                          : step.color === "blue"
                            ? "bg-[#3b82f6] text-white"
                            : "bg-[#DAE6DC] text-[#053F31]")
                      : "bg-[#F5F5F5] text-[#9E9E9E]";

                    return (
                      <div key={step.id} className="relative flex gap-4 pb-6">
                        {!isLast && (
                          <div
                            className={`absolute left-[11px] md:left-[15px] top-7 w-0.5 border-l-2 border-dashed ${isDone ? lineBorderColor : "border-[#E6E6E6]"}`}
                            style={{ height: "calc(100% - 0.25rem)" }}
                          />
                        )}
                        <div
                          className={`relative z-10 shrink-0 w-6 h-6 md:w-7 md:h-7 rounded-full flex items-center justify-center ${isDone
                            ? (step.color === "green"
                            ? "bg-[#053F31] text-white"
                            : step.color === "orange"
                            ? "bg-[#f97316] text-white"
                            : "bg-[#3b82f6] text-white")
                            : "bg-white border-2 border-[#E6E6E6]"
                            }`}
                        >
                          {isDone ? (step.id === "transit" || step.id === "delivery" ? <IconTruck /> : <IconCheck />) : null}
                        </div>
                        <div className="flex-1 min-w-0 pt-0.5">
                          <p className={`font-outfit font-semibold ${isDone ? "text-[#424242]" : "text-[#9E9E9E]"}`}>{step.title}</p>
                          <p className="font-outfit text-sm text-[#757575] mt-0.5">{step.description}</p>
                          <span
                            className={`inline-block mt-2 rounded-full px-3 py-1 text-xs font-outfit font-medium ${pillBg}`}
                          >
                            {step.date}
                          </span>
                        </div>
                      </div>
                    );
                  })}
                </div>

                <div className="mt-6 p-4 rounded-[10px] bg-[#DAE6DC]/40 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-[#053F31] text-white flex items-center justify-center shrink-0">
                      <IconTruckLarge />
                    </div>
                    <div>
                      <p className="font-outfit font-semibold text-[#424242]">{t.transportStatus}</p>
                      <p className="font-outfit text-sm text-[#757575]">{order.status_label}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="font-outfit font-medium text-[#424242]">{t.method}</span>
                    <span className="font-outfit text-sm font-medium text-[#053F31] bg-[#DAE6DC] px-3 py-1.5 rounded-full">
                      {t.standardDelivery}
                    </span>
                  </div>
                </div>
              </section>
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}

export default function Page({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const resolvedParams = React.use(params);
  return <OrderDetailPage orderId={resolvedParams.id} />;
}

