import type { Metadata } from "next";
import Link from "next/link";
import { ChevronLeft, Package, MapPin, CreditCard, Calendar, Truck } from "lucide-react";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect, notFound } from "next/navigation";

export const metadata: Metadata = { title: "Order Details" };

export default async function OrderDetailsPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await auth();
  if (!session?.user?.id) redirect("/login");

  const order = await db.order.findUnique({
    where: { id },
    include: {
      items: {
        include: {
          product: {
            include: {
              images: { take: 1 },
            },
          },
        },
      },
    },
  });

  // Check if order exists and belongs to current user (or is admin)
  if (!order) notFound();
  if (order.userId !== session.user.id && session.user.role !== "admin") {
    redirect("/dashboard");
  }

  const statusConfig = {
    pending: { label: "Pending Payment", color: "bg-yellow-50 text-yellow-700 border-yellow-200" },
    paid: { label: "Paid", color: "bg-purple-50 text-purple-700 border-purple-200" },
    shipped: { label: "Shipped", color: "bg-blue-50 text-blue-700 border-blue-200" },
    completed: { label: "Completed", color: "bg-emerald-50 text-emerald-700 border-emerald-200" },
    refunded: { label: "Refunded", color: "bg-red-50 text-red-700 border-red-200" },
    cancelled: { label: "Cancelled", color: "bg-neutral-100 text-neutral-600 border-neutral-200" },
  };

  const currentStatus = statusConfig[order.status] || statusConfig.pending;

  return (
    <div className="min-h-screen bg-neutral-50">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div className="flex items-center gap-3 mb-8">
          <Link href="/dashboard" className="flex items-center gap-1 text-sm text-neutral-400 hover:text-navy-600">
            <ChevronLeft size={15} /> Back to Dashboard
          </Link>
        </div>

        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-navy-900">Order Details</h1>
            <p className="text-sm text-neutral-500 mt-1">Order #{order.id.slice(-8).toUpperCase()}</p>
          </div>
          <div className={`px-4 py-2 rounded-xl font-semibold text-sm border ${currentStatus.color}`}>
            {currentStatus.label}
          </div>
        </div>

        <div className="grid lg:grid-cols-3 gap-6 mb-6">
          {/* Shipping Info */}
          <div className="bg-white rounded-2xl border border-neutral-200 p-6">
            <div className="flex items-center gap-2 mb-4">
              <MapPin size={18} className="text-navy-600" />
              <h2 className="font-semibold text-navy-800">Shipping Address</h2>
            </div>
            <div className="text-sm text-neutral-700 space-y-1">
              <p className="font-medium">{order.shippingName}</p>
              <p>{order.shippingAddress}</p>
              <p>
                {order.shippingCity}, {order.shippingState} {order.shippingZip}
              </p>
              <p>{order.shippingCountry}</p>
            </div>
          </div>

          {/* Payment Info */}
          <div className="bg-white rounded-2xl border border-neutral-200 p-6">
            <div className="flex items-center gap-2 mb-4">
              <CreditCard size={18} className="text-navy-600" />
              <h2 className="font-semibold text-navy-800">Payment</h2>
            </div>
            <div className="text-sm text-neutral-700 space-y-2">
              <div className="flex justify-between">
                <span className="text-neutral-500">Total</span>
                <span className="font-bold text-navy-700">${Number(order.total).toFixed(2)}</span>
              </div>
              {order.stripePaymentId && (
                <div className="pt-2 border-t border-neutral-100">
                  <span className="text-neutral-400 text-xs">Payment ID</span>
                  <p className="text-xs font-mono text-neutral-600 mt-0.5 truncate">{order.stripePaymentId}</p>
                </div>
              )}
            </div>
          </div>

          {/* Order Info */}
          <div className="bg-white rounded-2xl border border-neutral-200 p-6">
            <div className="flex items-center gap-2 mb-4">
              <Calendar size={18} className="text-navy-600" />
              <h2 className="font-semibold text-navy-800">Order Info</h2>
            </div>
            <div className="text-sm text-neutral-700 space-y-2">
              <div>
                <span className="text-neutral-500 text-xs">Placed on</span>
                <p className="font-medium">
                  {new Date(order.createdAt).toLocaleDateString("en-MY", {
                    day: "numeric",
                    month: "long",
                    year: "numeric",
                  })}
                </p>
              </div>
              <div>
                <span className="text-neutral-500 text-xs">Last updated</span>
                <p className="font-medium">
                  {new Date(order.updatedAt).toLocaleDateString("en-MY", {
                    day: "numeric",
                    month: "short",
                    year: "numeric",
                  })}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Order Items */}
        <div className="bg-white rounded-2xl border border-neutral-200 p-6">
          <div className="flex items-center gap-2 mb-6">
            <Package size={18} className="text-navy-600" />
            <h2 className="font-semibold text-navy-800">Items ({order.items.length})</h2>
          </div>
          <div className="space-y-4">
            {order.items.map((item) => (
              <div key={item.id} className="flex items-start gap-4 pb-4 border-b border-neutral-100 last:border-0">
                <div className="w-20 h-20 rounded-lg bg-neutral-100 shrink-0 overflow-hidden">
                  {item.product.images[0]?.url ? (
                    <img
                      src={item.product.images[0].url}
                      alt={item.product.name}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-neutral-300">
                      <Package size={28} />
                    </div>
                  )}
                </div>
                <div className="flex-1">
                  <Link
                    href={`/shop/${item.product.slug}`}
                    className="font-medium text-neutral-800 hover:text-navy-700 line-clamp-2"
                  >
                    {item.product.name}
                  </Link>
                  <p className="text-sm text-neutral-500 mt-1">Quantity: {item.quantity}</p>
                  <p className="text-sm text-neutral-400 mt-0.5">${Number(item.unitPrice).toFixed(2)} each</p>
                </div>
                <div className="text-right shrink-0">
                  <p className="font-bold text-navy-700">
                    ${(Number(item.unitPrice) * item.quantity).toFixed(2)}
                  </p>
                </div>
              </div>
            ))}
          </div>
          <div className="pt-4 mt-4 border-t-2 border-neutral-200 flex justify-between items-center">
            <span className="font-semibold text-neutral-700">Total</span>
            <span className="text-2xl font-bold text-navy-700">${Number(order.total).toFixed(2)}</span>
          </div>
        </div>

        {/* Order tracking message */}
        {order.status === "shipped" && (
          <div className="mt-6 bg-blue-50 border border-blue-200 rounded-2xl p-6 flex items-start gap-4">
            <Truck size={24} className="text-blue-600 shrink-0 mt-0.5" />
            <div>
              <h3 className="font-semibold text-blue-900 mb-1">Your order is on the way!</h3>
              <p className="text-sm text-blue-700">
                Your order has been shipped and should arrive within 3-5 business days.
              </p>
            </div>
          </div>
        )}

        {order.notes && (
          <div className="mt-6 bg-neutral-50 border border-neutral-200 rounded-2xl p-4">
            <p className="text-xs text-neutral-500 mb-1">Notes</p>
            <p className="text-sm text-neutral-700">{order.notes}</p>
          </div>
        )}
      </div>
    </div>
  );
}
