"use client";

import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  getStoredLocaleRaw,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";

const BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
const API_KEY = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY;

type Order = {
  id: string;
  display_id: number;
  status: string;
  currency_code: string;
  total: number;
  subtotal: number;
  tax_total: number;
  shipping_total: number;
  email: string;
  metadata?: Record<string, unknown>;
  items?: Array<{
    id: string;
    title: string;
    quantity: number;
    unit_price: number;
    metadata?: Record<string, unknown>;
  }>;
  billing_address?: {
    company?: string;
    address_1?: string;
    city?: string;
    postal_code?: string;
    country_code?: string;
  };
  shipping_address?: {
    company?: string;
    address_1?: string;
    city?: string;
    postal_code?: string;
    country_code?: string;
  };
  shipping_methods?: Array<{ name: string; amount: number }>;
};

function formatMoney(amount: number, currency: string) {
  const sym = currency.toLowerCase() === "eur" ? "€" : currency.toUpperCase() + " ";
  return `${sym}${Number(amount).toFixed(2)}`;
}

function OrderConfirmationBody() {
  const searchParams = useSearchParams();
  const orderId = searchParams.get("orderId");
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

  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(() => {
    if (!orderId) { setError("No order ID found"); setLoading(false); return; }

    let cancelled = false;

    const loadOrder = (showLoadingSpinner: boolean) => {
      if (showLoadingSpinner) {
        setLoading(true);
        setError(null);
      }
      const headers: Record<string, string> = {
        "Content-Type": "application/json",
        "x-publishable-api-key": API_KEY ?? "",
        "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
      };
      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 {}

      fetch(`${BACKEND_URL}/store/orders/${orderId}`, { headers })
        .then((r) => r.json())
        .then((d: { order?: Order }) => {
          if (cancelled) return;
          if (d.order) setOrder(d.order);
          else setError("Order not found");
        })
        .catch(() => {
          if (!cancelled) setError("Could not load order");
        })
        .finally(() => {
          if (!cancelled && showLoadingSpinner) setLoading(false);
        });
    };

    void loadOrder(true);

    const onLocaleChange = () => {
      void loadOrder(false);
    };
    if (typeof window !== "undefined") {
      window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
    }
    return () => {
      cancelled = true;
      if (typeof window !== "undefined") {
        window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
      }
    };
  }, [orderId]);

  const t =
    staticCopy.orderConfirmation[uiLocale as keyof typeof staticCopy.orderConfirmation] ??
    staticCopy.orderConfirmation["en-EN"];
  const orderDateLocaleTag = uiLocale === "es-ES" ? "es-ES" : "en-GB";

  if (loading) return (
    <main className="min-h-screen flex items-center justify-center bg-white">
      <div className="w-12 h-12 border-4 border-green-600 border-t-transparent rounded-full animate-spin" />
    </main>
  );

  if (error || !order) return (
    <main className="min-h-screen flex items-center justify-center bg-white">
      <div className="text-center">
        <p className="text-red-600 mb-4">{error ?? t.errorOrderNotFound}</p>
        <Link href="/marketplace" className="bg-[#053F31] text-white px-6 py-3 rounded-full font-outfit">
          {t.backToMarketplace}
        </Link>
      </div>
    </main>
  );

  const currency = order.currency_code ?? "eur";
  const shippingAmount = order.shipping_methods?.[0]?.amount ?? order.shipping_total ?? 0;

  return (
    <main className="min-h-screen bg-white px-4 py-8">
      <div className="mx-auto max-w-[860px]">

        <div className="rounded-[20px] bg-[#053F31] text-white p-[40px] mb-6 text-center relative overflow-hidden">
          <div className="w-16 h-16 rounded-full border-4 border-white flex items-center justify-center mx-auto mb-4">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3">
              <path d="M20 6L9 17l-5-5" />
            </svg>
          </div>
          <h1 className="font-outfit text-[36px] font-light mb-2">
            {t.successHeroTitlePrefix}{" "}
            <strong>{t.successHeroTitleEmphasis}</strong>
          </h1>
          <p className="font-outfit font-light opacity-80">
            {t.successHeroSubtitle}
          </p>
        </div>

        <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px] mb-6">
          <h2 className="font-outfit text-[20px] font-semibold text-[#053F31] mb-5">{t.sectionOrderConfirmation}</h2>
          <div className="grid grid-cols-2 gap-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-[#E8F5E9] flex items-center justify-center">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#053F31" strokeWidth="2">
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/>
                </svg>
              </div>
              <div>
                <p className="font-outfit text-[12px] text-[#999999]">{t.labelOrderNumber}</p>
                <p className="font-outfit font-semibold text-[#053F31]">ORD-{order.display_id}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-[#E8F5E9] flex items-center justify-center">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#053F31" strokeWidth="2">
                  <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                </svg>
              </div>
              <div>
                <p className="font-outfit text-[12px] text-[#999999]">{t.labelOrderDate}</p>
                <p className="font-outfit font-semibold text-[#053F31]">
                  {new Date().toLocaleDateString(orderDateLocaleTag, { weekday: "long", year: "numeric", month: "long", day: "numeric" })}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px] mb-6">
          <h2 className="font-outfit text-[20px] font-semibold text-[#053F31] mb-5">{t.sectionOrderSummary}</h2>
          {order.items?.map((item) => (
            <div key={item.id} className="flex justify-between items-center py-3 border-b border-[#000]/10 last:border-0">
              <div>
                <p className="font-outfit font-medium text-[#000]">{item.title}</p>
                <p className="font-outfit font-light text-[14px] text-[#999]">{t.quantityPrefix} {item.quantity}</p>
              </div>
              <p className="font-outfit font-semibold text-[#053F31]">
                {formatMoney((item.unit_price ?? 0) * item.quantity, currency)}
              </p>
            </div>
          ))}
          <div className="mt-4 space-y-2">
            <div className="flex justify-between font-outfit text-[16px] text-[#000]">
              <span>{t.subtotal}</span>
              <span>{formatMoney(order.subtotal ?? 0, currency)}</span>
            </div>
            <div className="flex justify-between font-outfit text-[16px] text-[#000]">
              <span>{t.vat}</span>
              <span>{formatMoney(order.tax_total ?? 0, currency)}</span>
            </div>
            <div className="flex justify-between font-outfit text-[16px] text-[#000]">
              <span>{t.transport}</span>
              <span>{formatMoney(shippingAmount, currency)}</span>
            </div>
            <div className="flex justify-between font-outfit text-[18px] font-semibold text-[#053F31] border-t border-[#000]/10 pt-3 mt-2">
              <span>{t.totalPaid}</span>
              <span>{formatMoney(order.total ?? 0, currency)}</span>
            </div>
          </div>
        </div>

        {order.billing_address && (
          <div className="rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] p-[30px] mb-6">
            <h2 className="font-outfit text-[20px] font-semibold text-[#053F31] mb-3">{t.sectionBillingInformation}</h2>
            <p className="font-outfit text-[#000]">{order.billing_address.company}</p>
            <p className="font-outfit font-light text-[#999]">{order.billing_address.address_1}</p>
            <p className="font-outfit font-light text-[#999]">{order.billing_address.city}, {order.billing_address.postal_code}</p>
            <p className="font-outfit font-light text-[#999]">{order.billing_address.country_code?.toUpperCase()}</p>
          </div>
        )}

        <div className="flex gap-4 flex-wrap">
          <Link
            href="/marketplace"
            className="flex-1 text-center bg-[#053F31] text-white font-outfit font-semibold py-4 px-8 rounded-full hover:bg-[#082a21] transition"
          >
            {t.continueShopping}
          </Link>
          <Link
            href="/account/orders"
            className="flex-1 text-center border-2 border-[#053F31] text-[#053F31] font-outfit font-semibold py-4 px-8 rounded-full hover:bg-[#053F31] hover:text-white transition"
          >
            {t.viewOrderStatus}
          </Link>
        </div>

      </div>
    </main>
  );
}

export default function OrderConfirmationPage() {
  return (
    <Suspense fallback={
      <main className="min-h-screen flex items-center justify-center bg-white">
        <div className="w-12 h-12 border-4 border-green-600 border-t-transparent rounded-full animate-spin" />
      </main>
    }>
      <OrderConfirmationBody />
    </Suspense>
  );
}
