/* eslint-disable react/no-unescaped-entities */
/* eslint-disable @typescript-eslint/no-explicit-any */
import Navbar from "@/components/shared/Navbar";
import Footer from "@/components/shared/Footer";
import { publicFetch } from "@/lib/server-fetch";
import { ArrowLeft, Calendar, MapPin, Package, Phone, ShoppingBag, Truck, CheckCircle2, Clock, AlertTriangle } from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import type { Metadata } from "next";

export const dynamic = "force-dynamic";

interface PageProps {
  params: Promise<{
    orderNumber: string;
  }>;
  searchParams: Promise<{
    mobile?: string;
  }>;
}

// Dynamic SEO metadata
export async function generateMetadata({ params }: { params: Promise<{ orderNumber: string }> }): Promise<Metadata> {
  const { orderNumber } = await params;
  return {
    title: `Track Order ${orderNumber}`,
    description: `Track the real-time shipping and delivery status of order ${orderNumber}.`,
  };
}

async function fetchOrderTracking(orderNumber: string, mobile: string) {
  try {
    const res = await publicFetch.get(`/storefront/orders/track/${orderNumber}?mobile=${mobile}`);
    if (!res.ok) {
      return null;
    }
    const json = await res.json();
    return json.success ? json.data : null;
  } catch (error) {
    console.error("Error fetching order tracking:", error);
    return null;
  }
}

export default async function OrderTrackPage({ params, searchParams }: PageProps) {
  const { orderNumber } = await params;
  const { mobile } = await searchParams;

  if (!mobile) {
    return (
      <div className="min-h-screen bg-brand-surface text-white flex flex-col justify-between">
        <Navbar />
        <main className="container mx-auto px-4 py-32 max-w-xl text-center">
          <div className="bg-white/5 border border-white/10 rounded-3xl p-8 backdrop-blur-xl shadow-2xl">
            <AlertTriangle className="w-16 h-16 text-brand-accent mx-auto mb-6" />
            <h1 className="text-2xl font-black uppercase tracking-wider mb-4">Mobile Number Missing</h1>
            <p className="text-brand-text-dim text-sm mb-8">
              For security reasons, we require a mobile number to verify and track your order.
            </p>
            <Link href="/#tracking">
              <Button className="w-full bg-brand-accent hover:bg-brand-accent-hover text-white font-bold py-3 uppercase tracking-wider rounded-xl transition-all">
                Go to tracking form
              </Button>
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  const order = await fetchOrderTracking(orderNumber, mobile);

  if (!order) {
    return (
      <div className="min-h-screen bg-brand-surface text-white flex flex-col justify-between">
        <Navbar />
        <main className="container mx-auto px-4 py-32 max-w-xl text-center">
          <div className="bg-white/5 border border-white/10 rounded-3xl p-8 backdrop-blur-xl shadow-2xl">
            <AlertTriangle className="w-16 h-16 text-red-500 mx-auto mb-6" />
            <h1 className="text-2xl font-black uppercase tracking-wider mb-4">Order Not Found</h1>
            <p className="text-brand-text-dim text-sm mb-8">
              We couldn't find an order with number <strong className="text-white">{orderNumber}</strong> matching mobile <strong className="text-white">{mobile}</strong>. Please check your credentials and try again.
            </p>
            <Link href="/#tracking">
              <Button className="w-full bg-white/10 hover:bg-white/20 text-white font-bold py-3 uppercase tracking-wider rounded-xl transition-all border border-white/10">
                Try Again
              </Button>
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  // Format Date
  const orderDate = order.placed_on ? new Date(order.placed_on).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }) : "N/A";

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "pending":
        return "bg-amber-500/10 text-amber-400 border-amber-500/20";
      case "confirmed":
        return "bg-blue-500/10 text-blue-400 border-blue-500/20";
      case "processing":
        return "bg-purple-500/10 text-purple-400 border-purple-500/20";
      case "dispatched":
        return "bg-indigo-500/10 text-indigo-400 border-indigo-500/20";
      case "delivered":
        return "bg-emerald-500/10 text-emerald-400 border-emerald-500/20";
      case "cancelled":
        return "bg-red-500/10 text-red-400 border-red-500/20";
      default:
        return "bg-white/10 text-white border-white/20";
    }
  };

  return (
    <div className="min-h-screen bg-brand-surface text-white flex flex-col justify-between">
      <Navbar />

      <main className="container mx-auto px-4 pt-28 pb-20 max-w-6xl">
        {/* Back Link */}
        <Link
          href="/"
          className="inline-flex items-center gap-2 text-xs uppercase tracking-wider text-brand-text-dim hover:text-brand-accent mb-8 font-bold transition-colors group"
        >
          <ArrowLeft className="w-4 h-4 transition-transform group-hover:-translate-x-1" />
          Back to Homepage
        </Link>

        {/* Top Info Header */}
        <div className="bg-white/5 border border-white/10 rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 backdrop-blur-xl shadow-2xl mb-8 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-64 h-64 bg-brand-accent/5 rounded-full blur-3xl -z-10" />

          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div>
              <div className="flex flex-wrap items-center gap-3 mb-2">
                <span className="text-xs uppercase tracking-widest text-brand-text-dim font-bold">
                  Order Tracker
                </span>
                <span className={`px-3 py-1 rounded-full text-xs font-bold border ${getStatusColor(order.status)} uppercase tracking-wider`}>
                  ● {order.status}
                </span>
                {order.return_status && order.return_status !== "none" && (
                  <span className="px-3 py-1 rounded-full text-xs font-bold border bg-rose-500/10 text-rose-400 border-rose-500/20 uppercase tracking-wider">
                    ↩ Returned ({order.return_status})
                  </span>
                )}
              </div>
              <h1 className="text-2xl sm:text-3xl font-black uppercase tracking-wider text-white">
                {order.order_number}
              </h1>
            </div>

            <div className="flex items-center gap-4 text-sm text-brand-text-dim md:border-l md:border-white/10 md:pl-6">
              <div className="p-3 bg-white/5 rounded-2xl border border-white/5 text-brand-accent shrink-0">
                <Calendar className="w-5 h-5" />
              </div>
              <div>
                <p className="text-xs uppercase tracking-wider font-bold">Placed On</p>
                <p className="font-semibold text-white">{orderDate}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Tracking Timeline */}
        <div className="bg-white/5 border border-white/10 rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 backdrop-blur-xl shadow-2xl mb-8">
          <h3 className="text-lg font-bold uppercase tracking-wider mb-8 text-white flex items-center gap-2">
            <Truck className="w-5 h-5 text-brand-accent" />
            Shipment Timeline
          </h3>

          {/* Desktop Timeline (Horizontal) */}
          <div className="hidden md:flex justify-between items-center relative py-4">
            {/* Connecting line */}
            <div className="absolute top-1/2 left-[10%] right-[10%] h-0.5 bg-white/10 -translate-y-1/2 z-0" />

            {/* Colored Progress Line */}
            <div
              className="absolute top-1/2 left-[10%] h-0.5 bg-brand-accent -translate-y-1/2 z-0 transition-all duration-500 shadow-[0_0_10px_rgba(245,158,11,0.4)]"
              style={{
                width: `${order.timeline.length > 1
                  ? ((order.timeline.filter((t: any) => t.completed).length - 1) / (order.timeline.length - 1)) * 80
                  : 0
                  }%`
              }}
            />

            {order.timeline?.map((step: any) => {
              const isCompleted = step.completed;
              const isActive = step.active;

              return (
                <div key={step.step} className="flex flex-col items-center relative z-10 w-1/5 text-center">
                  <div className={`w-10 h-10 rounded-full border flex items-center justify-center transition-all duration-500
                    ${isCompleted
                      ? "bg-brand-accent border-brand-accent text-white shadow-[0_0_15px_rgba(245,158,11,0.4)]"
                      : isActive
                        ? "bg-brand-surface border-brand-accent text-brand-accent animate-pulse scale-110"
                        : "bg-brand-surface border-white/20 text-brand-text-dim"
                    }`}
                  >
                    {isCompleted ? (
                      <CheckCircle2 className="w-5 h-5" />
                    ) : (
                      <Clock className="w-5 h-5" />
                    )}
                  </div>
                  <p className={`mt-3 text-xs uppercase tracking-wider font-bold max-w-[120px] transition-colors
                    ${isActive ? "text-brand-accent font-black" : isCompleted ? "text-white" : "text-brand-text-dim"}`}
                  >
                    {step.label.replace(/[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF]/g, "").trim()}
                  </p>
                </div>
              );
            })}
          </div>

          {/* Mobile Timeline (Vertical) */}
          <div className="md:hidden space-y-6 relative pl-6">
            {/* Vertical Line */}
            <div className="absolute top-2 bottom-2 left-2 w-0.5 bg-white/10" />

            {order.timeline?.map((step: any) => {
              const isCompleted = step.completed;
              const isActive = step.active;

              return (
                <div key={step.step} className="flex gap-4 relative">
                  <div className={`absolute -left-[26px] w-5 h-5 rounded-full border flex items-center justify-center z-10 bg-white transition-all
                    ${isCompleted
                      ? "bg-brand-accent border-brand-accent text-white shadow-[0_0_10px_rgba(245,158,11,0.4)]"
                      : isActive
                        ? "bg-brand-surface border-brand-accent text-brand-accent animate-pulse scale-105"
                        : "bg-brand-surface border-white/20 text-brand-text-dim"
                    }`}
                  >
                    {isCompleted ? (
                      <CheckCircle2 className="w-3 h-3" />
                    ) : (
                      <Clock className="w-3 h-3" />
                    )}
                  </div>
                  <div>
                    <h4 className={`text-sm uppercase tracking-wider font-bold
                      ${isActive ? "text-brand-accent" : isCompleted ? "text-white" : "text-brand-text-dim"}`}
                    >
                      {step.label}
                    </h4>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Content Layout */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">

          {/* Left Columns - Items & Shipping */}
          <div className="lg:col-span-2 space-y-8">

            {/* Items Card */}
            <div className="bg-white/5 border border-white/10 rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 backdrop-blur-xl shadow-2xl">
              <h3 className="text-lg font-bold uppercase tracking-wider mb-6 text-white flex items-center gap-2 border-b border-white/10 pb-4">
                <ShoppingBag className="w-5 h-5 text-brand-accent" />
                Items Ordered
              </h3>

              <div className="divide-y divide-white/10">
                {order.items?.map((item: any, idx: number) => (
                  <div key={idx} className="py-4 flex justify-between items-start gap-4 first:pt-0 last:pb-0">
                    <div className="flex items-start gap-4 min-w-0 flex-1">
                      <div className="w-12 h-12 rounded-xl bg-white/5 border border-white/10 flex items-center justify-center text-brand-accent shrink-0">
                        <Package className="w-5 h-5" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <h4 className="font-bold text-white text-sm lg:text-base break-words">{item.name || item.product}</h4>
                        <p className="text-xs text-brand-text-dim break-words">Product: {item.product}</p>
                        <p className="text-xs text-brand-text-dim mt-1 lg:hidden">
                          ৳{Math.round(parseFloat(item.price))} × {item.quantity}
                        </p>
                      </div>
                    </div>

                    <div className="text-right shrink-0 pt-1">
                      <p className="text-sm font-bold text-white hidden lg:block">
                        ৳{Math.round(parseFloat(item.price))} × {item.quantity}
                      </p>
                      <p className="font-extrabold text-brand-accent text-sm lg:text-base mt-1">
                        ৳{Math.round(parseFloat(item.total))}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Address & Delivery */}
            <div className="bg-white/5 border border-white/10 rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 backdrop-blur-xl shadow-2xl">
              <h3 className="text-lg font-bold uppercase tracking-wider mb-6 text-white flex items-center gap-2 border-b border-white/10 pb-4">
                <MapPin className="w-5 h-5 text-brand-accent" />
                Delivery Address
              </h3>

              {order.delivery_address ? (
                <div className="space-y-4">
                  <div className="flex items-start gap-4 text-sm">
                    <div className="p-2.5 bg-white/5 rounded-xl border border-white/5 text-brand-text-dim shrink-0">
                      <MapPin className="w-4 h-4" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs uppercase tracking-wider font-bold text-brand-text-dim">Address</p>
                      <p className="text-white font-medium mt-0.5 break-words">{order.delivery_address.address}</p>
                      <p className="text-brand-text-dim text-xs mt-1 break-words">
                        {order.delivery_address.area}, {order.delivery_address.city}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-4 text-sm">
                    <div className="p-2.5 bg-white/5 rounded-xl border border-white/5 text-brand-text-dim shrink-0">
                      <Phone className="w-4 h-4" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs uppercase tracking-wider font-bold text-brand-text-dim">Customer Mobile</p>
                      <p className="text-white font-medium mt-0.5 break-words">{mobile}</p>
                    </div>
                  </div>
                </div>
              ) : (
                <p className="text-brand-text-dim text-sm">No delivery address specified.</p>
              )}
            </div>

          </div>

          {/* Right Column - Summary & Support */}
          <div className="space-y-8">

            {/* Order Summary */}
            <div className="bg-white/5 border border-white/10 rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 backdrop-blur-xl shadow-2xl relative overflow-hidden">
              <div className="absolute top-0 right-0 w-32 h-32 bg-brand-accent/5 rounded-full blur-2xl -z-10" />

              <h3 className="text-lg font-bold uppercase tracking-wider mb-6 text-white flex items-center gap-2 border-b border-white/10 pb-4">
                Summary
              </h3>

              <div className="space-y-4 text-sm">
                <div className="flex justify-between text-brand-text-dim">
                  <span>Subtotal</span>
                  <span className="font-semibold text-white">৳{Math.round(parseFloat(order.subtotal))}</span>
                </div>

                <div className="flex justify-between text-brand-text-dim">
                  <span>Discount</span>
                  <span className="font-semibold text-emerald-400">-৳{Math.round(parseFloat(order.discount_amount))}</span>
                </div>

                <div className="flex justify-between text-brand-text-dim">
                  <span>Delivery Charge</span>
                  <span className="font-semibold text-white">৳{Math.round(parseFloat(order.delivery_charge))}</span>
                </div>

                {parseFloat(order.total_refunded) > 0 && (
                  <div className="flex justify-between text-rose-400">
                    <span>Total Refunded</span>
                    <span className="font-semibold">-৳{Math.round(parseFloat(order.total_refunded))}</span>
                  </div>
                )}

                <div className="border-t border-white/10 pt-4 flex justify-between items-center">
                  <span className="font-black uppercase tracking-wider text-white">Total Amount</span>
                  <span className="text-xl font-black text-brand-accent">
                    ৳{Math.round(parseFloat(order.total_amount) - parseFloat(order.total_refunded || "0"))}
                  </span>
                </div>
              </div>
            </div>

            {/* Need Help Box */}
            <div className="bg-gradient-to-br from-brand-accent/20 to-transparent border border-brand-accent/20 rounded-2xl sm:rounded-3xl p-4 sm:p-6 backdrop-blur-xl shadow-2xl text-center">
              <h4 className="font-black uppercase tracking-wider text-white mb-2">Need Assistance?</h4>
              <p className="text-xs text-brand-text-dim mb-4">
                If you have any questions or issue with your order shipment, please contact our support team.
              </p>
              <a href="tel:01700000000" className="block">
                <Button className="w-full bg-brand-accent hover:bg-brand-accent-hover text-white font-bold py-2.5 uppercase tracking-wider rounded-xl transition-all text-xs">
                  Call Support
                </Button>
              </a>
            </div>

          </div>

        </div>

      </main>

      <Footer />
    </div>
  );
}
