"use client";

import Link from "next/link";
import { useEffect, useMemo, useState, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Building2, Check, CreditCard, Hash, MessageCircle, Phone } from "lucide-react";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { useAuth } from "@/context/AuthContext";
import {
  api,
  mediaOrPlaceholder,
  type CheckoutPayload,
  type CheckoutPreviewResponse,
  type OrderCreateResponse,
  type OrderDetailsResponse,
} from "@/lib/api";
import { company } from "@/data/company";

const EXAMPLE_BANK = {
  bank: "UBL Bank",
  accountTitle: "N.G Electric Gas Appliances (PVT) LTD",
  branchCode: "1199",
  accountNumber: "350174224",
  iban: "PK84UNIL0109000350174224",
};

const WHATSAPP_NUMBER = "923310444708";

const formatPkr = (amount: number) =>
  `Rs ${amount.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

type StoredOrder = {
  order: OrderCreateResponse;
  payload: CheckoutPayload;
  preview: CheckoutPreviewResponse;
  createdAt: string;
};

function SuccessInner() {
  const searchParams = useSearchParams();
  const orderId = searchParams.get("orderId");
  const { token } = useAuth();
  const [stored, setStored] = useState<StoredOrder | null>(null);
  const [remote, setRemote] = useState<OrderDetailsResponse | null>(null);

  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const raw = window.sessionStorage.getItem("gns_glow_last_order_v1");
      if (raw) setStored(JSON.parse(raw) as StoredOrder);
    } catch {
      setStored(null);
    }
  }, []);

  useEffect(() => {
    if (!orderId || !token) return;
    void api.checkout
      .orderById(orderId, token)
      .then(setRemote)
      .catch(() => setRemote(null));
  }, [orderId, token]);

  const firstName =
    stored?.payload.shipping_address.first_name ||
    remote?.shipping_address?.first_name ||
    "Customer";

  const confirmation =
    stored?.order.confirmation_code ||
    (orderId ? `#${String(orderId).padStart(8, "0").toUpperCase()}` : "#PENDING");

  const summary = stored?.order.summary || stored?.preview.summary || remote?.summary;
  const paymentMethod =
    stored?.order.payment_method ||
    stored?.payload.payment_method ||
    remote?.payment_method ||
    "cod";

  const items = useMemo(() => {
    if (stored?.preview.items?.length) return stored.preview.items;
    if (remote?.items?.length) {
      return remote.items.map((item) => ({
        product_id: item.product_id,
        product_name: item.product_name || `Product #${item.product_id}`,
        quantity: item.quantity,
        unit_price: Number(item.unit_price),
        subtotal: Number(item.subtotal),
        image: item.image,
      }));
    }
    return [];
  }, [stored, remote]);

  const shipping = stored?.payload.shipping_address || remote?.shipping_address;
  const billing =
    stored?.payload.same_as_shipping === false
      ? stored.payload.billing_address
      : shipping;
  const email =
    stored?.payload.email || remote?.email || remote?.contact?.email || "";

  const whatsappMessage = encodeURIComponent(
    `Hi, I placed order ${confirmation}. Please verify my payment screenshot.\nName: ${firstName}\nTotal: ${summary ? formatPkr(summary.total) : "N/A"}`,
  );

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <div className="container mx-auto px-4 py-10 lg:px-8">
        <div className="grid gap-10 lg:grid-cols-[1.4fr_1fr]">
          <div>
            <div className="flex items-start gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground">
                <Check className="h-6 w-6" strokeWidth={3} />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Confirmation {confirmation}</p>
                <h1 className="mt-1 text-3xl font-bold">Thank you, {firstName}!</h1>
                <p className="mt-2 text-sm text-muted-foreground">
                  Thank you for shopping with {company.shortName}. Your order is now being processed.
                </p>
              </div>
            </div>

            <section className="mt-10 border-y border-border py-8">
              <h2 className="text-xl font-bold">Complete Your Bank Transfer</h2>
              <div className="mt-5 space-y-3 text-sm">
                <p className="flex items-center gap-2">
                  <Building2 className="h-4 w-4 text-primary" />
                  <span className="font-semibold">Bank:</span> {EXAMPLE_BANK.bank}
                </p>
                <p className="flex items-center gap-2">
                  <CreditCard className="h-4 w-4 text-primary" />
                  <span className="font-semibold">Account Title:</span> {EXAMPLE_BANK.accountTitle}
                </p>
                <p className="flex items-center gap-2">
                  <Hash className="h-4 w-4 text-primary" />
                  <span className="font-semibold">Branch Code:</span> {EXAMPLE_BANK.branchCode}
                </p>
                <p className="flex items-center gap-2">
                  <Hash className="h-4 w-4 text-primary" />
                  <span className="font-semibold">Account Number:</span> {EXAMPLE_BANK.accountNumber}
                </p>
                <p className="flex items-center gap-2">
                  <Hash className="h-4 w-4 text-primary" />
                  <span className="font-semibold">IBAN:</span> {EXAMPLE_BANK.iban}
                </p>
              </div>
              <p className="mt-5 text-sm text-muted-foreground">
                Send your payment screenshot on WhatsApp using the button below. We&apos;ll verify your payment and confirm your order shortly.
              </p>
              <a
                href={`https://wa.me/${WHATSAPP_NUMBER}?text=${whatsappMessage}`}
                target="_blank"
                rel="noopener noreferrer"
                className="mt-5 inline-flex items-center gap-2 rounded-xl border border-border bg-card px-5 py-3 text-sm font-bold transition-colors hover:border-primary/40"
              >
                <MessageCircle className="h-4 w-4 text-[#25D366]" />
                Verify Payment on WhatsApp
              </a>
            </section>

            <section className="mt-6 rounded-2xl border border-border bg-secondary/40 px-5 py-4 text-sm">
              Your order is confirmed. You&apos;ll receive a confirmation email soon.
              {paymentMethod === "cod" ? " Please keep cash ready for delivery." : null}
            </section>

            <section className="mt-8 rounded-2xl border border-border bg-card p-6 shadow-card">
              <div className="grid gap-8 sm:grid-cols-2">
                <div className="space-y-5">
                  <div>
                    <h3 className="text-sm font-bold">Contact information</h3>
                    <p className="mt-1 text-sm text-muted-foreground">{email || "—"}</p>
                  </div>
                  <div>
                    <h3 className="text-sm font-bold">Shipping address</h3>
                    {shipping ? (
                      <p className="mt-1 text-sm leading-relaxed text-muted-foreground">
                        {shipping.first_name} {shipping.last_name}
                        <br />
                        {shipping.address}
                        {shipping.apartment ? `, ${shipping.apartment}` : ""}
                        <br />
                        {shipping.city}
                        {shipping.postal_code ? ` ${shipping.postal_code}` : ""}
                        <br />
                        {shipping.country}
                        <br />
                        {shipping.phone}
                      </p>
                    ) : (
                      <p className="mt-1 text-sm text-muted-foreground">—</p>
                    )}
                  </div>
                  <div>
                    <h3 className="text-sm font-bold">Shipping method</h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {stored?.payload.shipping_method.name ||
                        remote?.shipping_method?.name ||
                        "Shipping charges"}
                    </p>
                  </div>
                </div>
                <div className="space-y-5">
                  <div>
                    <h3 className="text-sm font-bold">Payment method</h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {paymentMethod === "cod"
                        ? `Cash on Delivery (COD)${summary ? ` — ${formatPkr(summary.total)} PKR` : ""}`
                        : "Debit - Credit Card / Bank Transfer"}
                    </p>
                  </div>
                  <div>
                    <h3 className="text-sm font-bold">Billing address</h3>
                    {billing ? (
                      <p className="mt-1 text-sm leading-relaxed text-muted-foreground">
                        {billing.first_name} {billing.last_name}
                        <br />
                        {billing.address}
                        {billing.apartment ? `, ${billing.apartment}` : ""}
                        <br />
                        {billing.city}
                        {billing.postal_code ? ` ${billing.postal_code}` : ""}
                        <br />
                        {billing.country}
                      </p>
                    ) : (
                      <p className="mt-1 text-sm text-muted-foreground">Same as shipping address</p>
                    )}
                  </div>
                </div>
              </div>
            </section>

            <div className="mt-8 flex flex-wrap items-center justify-between gap-3">
              <a
                href={company.phoneHref}
                className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-primary"
              >
                <Phone className="h-4 w-4" />
                Need help? Contact us
              </a>
              <Link
                href="/products"
                className="rounded-xl bg-primary px-6 py-3 text-sm font-bold text-primary-foreground transition-all hover:opacity-90"
              >
                Continue shopping
              </Link>
            </div>
          </div>

          <aside className="h-fit rounded-2xl border border-border bg-secondary/40 p-5 lg:sticky lg:top-28">
            <div className="space-y-4">
              {items.length ? (
                items.map((item) => (
                  <div key={`${item.product_id}-${item.product_name}`} className="flex gap-3">
                    <div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-xl border border-border bg-card">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={mediaOrPlaceholder(item.image)}
                        alt={item.product_name}
                        className="h-full w-full object-cover"
                      />
                      <span className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-foreground text-[10px] font-bold text-primary-foreground">
                        {item.quantity}
                      </span>
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="line-clamp-2 text-sm font-medium">{item.product_name}</p>
                    </div>
                    <p className="shrink-0 text-sm font-semibold">{formatPkr(item.subtotal)}</p>
                  </div>
                ))
              ) : (
                <p className="text-sm text-muted-foreground">Order summary unavailable.</p>
              )}
            </div>

            {summary ? (
              <div className="mt-6 space-y-2 border-t border-border pt-4 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Subtotal</span>
                  <span className="font-medium">{formatPkr(summary.subtotal)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Shipping</span>
                  <span className="font-medium">{formatPkr(summary.shipping)}</span>
                </div>
                <div className="flex items-end justify-between border-t border-border pt-3">
                  <span className="text-base font-bold">Total</span>
                  <span className="text-right">
                    <span className="mr-2 text-xs text-muted-foreground">
                      {summary.currency || "PKR"}
                    </span>
                    <span className="text-xl font-extrabold">{formatPkr(summary.total)}</span>
                  </span>
                </div>
              </div>
            ) : null}
          </aside>
        </div>
      </div>
      <Footer />
    </div>
  );
}

export default function CheckoutSuccessPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-background">
          <Navbar />
          <p className="p-10 text-center text-sm text-muted-foreground">Loading order confirmation…</p>
        </div>
      }
    >
      <SuccessInner />
    </Suspense>
  );
}
