import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Package, Download, KeyRound, ChevronRight, ShoppingBag } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import SiteLayout from "@/components/SiteLayout";
import LoadingSpinner from "@/components/LoadingSpinner";
import { formatPrice, PRIMARY_CURRENCY } from "@/lib/currency";
import { Price } from "@/components/ui/Price";

const client = createClient();

interface OrderItem {
  product_id: number;
  product_name: string;
  product_type: string;
  variant_label: string;
  unit_price: number;
  quantity: number;
  line_total: number;
  download_url: string;
  license_key: string;
}

interface OrderDto {
  id: number;
  order_number: string;
  status: string;
  payment_status: string;
  subtotal: number;
  shipping_cost: number;
  tax: number;
  total: number;
  currency: string;
  billing_email: string;
  tracking_number: string;
  notes: string;
  created_at: string;
  items: OrderItem[];
}

const STATUS_COLORS: Record<string, string> = {
  pending: "bg-amber-100 text-amber-700",
  processing: "bg-blue-100 text-blue-700",
  shipped: "bg-indigo-100 text-indigo-700",
  delivered: "bg-emerald-100 text-emerald-700",
  cancelled: "bg-rose-100 text-rose-700",
  refunded: "bg-slate-100 text-slate-700",
};

export default function Orders() {
  const [loading, setLoading] = useState(true);
  const [authed, setAuthed] = useState(false);
  const [orders, setOrders] = useState<OrderDto[]>([]);
  const [expanded, setExpanded] = useState<number | null>(null);

  useEffect(() => {
    const run = async () => {
      try {
        const me = await client.auth.me();
        if (!me?.data) {
          setAuthed(false);
          return;
        }
        setAuthed(true);
        const res = await client.apiCall.invoke({
          url: "/api/v1/ecom/my_orders_with_items",
          method: "GET",
          data: {},
        });
        setOrders(((res?.data as any)?.items || []) as OrderDto[]);
      } catch {
        setAuthed(false);
      } finally {
        setLoading(false);
      }
    };
    run();
  }, []);

  if (loading) {
    return (
      <SiteLayout>
        <div className="py-24 flex justify-center">
          <LoadingSpinner />
        </div>
      </SiteLayout>
    );
  }

  if (!authed) {
    return (
      <SiteLayout>
        <div className="max-w-3xl mx-auto px-4 py-24 text-center">
          <h1 className="text-2xl font-bold text-slate-900">Please log in</h1>
          <p className="text-slate-500 mt-2">You need to be logged in to view your orders.</p>
          <button
            onClick={() => client.auth.toLogin()}
            className="mt-5 px-5 py-2.5 rounded-xl bg-[#0b6e3e] text-white font-semibold"
          >
            Log in
          </button>
        </div>
      </SiteLayout>
    );
  }

  return (
    <SiteLayout>
      <div className="max-w-4xl mx-auto px-4 md:px-6 py-10">
        <h1 className="text-3xl md:text-4xl font-extrabold text-slate-900 mb-2">
          My Orders
        </h1>
        <p className="text-slate-500 mb-8">
          Track your purchases, download digital items and retrieve license keys.
        </p>

        {orders.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-2xl p-12 text-center">
            <ShoppingBag className="w-12 h-12 text-slate-300 mx-auto mb-3" />
            <h2 className="font-bold text-slate-900">No orders yet</h2>
            <p className="text-slate-500 mt-1">Your future purchases will appear here.</p>
            <Link
              to="/shop"
              className="mt-5 inline-block px-5 py-2.5 rounded-xl bg-[#0b6e3e] text-white font-semibold"
            >
              Start shopping
            </Link>
          </div>
        ) : (
          <div className="space-y-3">
            {orders.map((o) => {
              const isOpen = expanded === o.id;
              const statusColor = STATUS_COLORS[o.status] || STATUS_COLORS.pending;
              return (
                <div
                  key={o.id}
                  className="bg-white border border-slate-200 rounded-2xl overflow-hidden"
                >
                  <button
                    onClick={() => setExpanded(isOpen ? null : o.id)}
                    className="w-full p-5 flex flex-wrap items-center gap-4 text-left hover:bg-slate-50"
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="font-bold text-slate-900">{o.order_number}</span>
                        <span
                          className={`text-[11px] uppercase tracking-wider font-bold px-2 py-0.5 rounded-full ${statusColor}`}
                        >
                          {o.status}
                        </span>
                        <span className="text-[11px] uppercase tracking-wider font-bold px-2 py-0.5 rounded-full bg-slate-100 text-slate-700">
                          {o.payment_status}
                        </span>
                      </div>
                      <div className="text-xs text-slate-500 mt-1">
                        {o.created_at?.slice(0, 10) || ""} · {o.items.length} item
                        {o.items.length === 1 ? "" : "s"}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="font-extrabold text-[#0b6e3e]">
                        <Price amount={o.total} />
                      </div>
                      <div className="text-[11px] uppercase tracking-wider text-slate-400">
                        {PRIMARY_CURRENCY}
                      </div>
                    </div>
                    <ChevronRight
                      className={`w-5 h-5 text-slate-400 transition-transform ${
                        isOpen ? "rotate-90" : ""
                      }`}
                    />
                  </button>

                  {isOpen && (
                    <div className="border-t border-slate-200 p-5 bg-slate-50">
                      <h3 className="font-semibold text-slate-900 mb-3 inline-flex items-center gap-2">
                        <Package className="w-4 h-4 text-[#0b6e3e]" /> Items
                      </h3>
                      <div className="space-y-2">
                        {o.items.map((it, idx) => (
                          <div
                            key={idx}
                            className="bg-white border border-slate-200 rounded-xl p-3 flex flex-col gap-2"
                          >
                            <div className="flex justify-between items-start gap-3 flex-wrap">
                              <div>
                                <div className="font-semibold text-slate-900 text-sm">
                                  {it.product_name} × {it.quantity}
                                </div>
                                {it.variant_label && (
                                  <div className="text-xs text-slate-500">
                                    {it.variant_label}
                                  </div>
                                )}
                              </div>
                              <div className="font-bold text-slate-900 text-sm">
                                <Price amount={it.line_total} />
                              </div>
                            </div>
                            {it.product_type === "digital" && (
                              <div className="flex flex-wrap items-center gap-2">
                                {it.download_url && (
                                  <a
                                    href={it.download_url}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="inline-flex items-center gap-1 text-xs bg-[#0b6e3e] text-white px-3 py-1.5 rounded-lg hover:bg-[#0a8048]"
                                  >
                                    <Download className="w-3.5 h-3.5" /> Download
                                  </a>
                                )}
                                {it.license_key && (
                                  <div className="inline-flex items-center gap-1 text-xs bg-slate-100 px-3 py-1.5 rounded-lg text-slate-700 font-mono">
                                    <KeyRound className="w-3.5 h-3.5 text-[#0b6e3e]" />
                                    {it.license_key}
                                  </div>
                                )}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                      <div className="mt-4 grid grid-cols-2 md:grid-cols-4 gap-3 text-xs text-slate-600">
                        <div>
                          <div className="uppercase tracking-wider text-slate-400">
                            Subtotal
                          </div>
                          <div className="font-bold text-slate-900">
                            <Price amount={o.subtotal} />
                          </div>
                        </div>
                        <div>
                          <div className="uppercase tracking-wider text-slate-400">
                            Shipping
                          </div>
                          <div className="font-bold text-slate-900">
                            <Price amount={o.shipping_cost} />
                          </div>
                        </div>
                        <div>
                          <div className="uppercase tracking-wider text-slate-400">
                            Tax
                          </div>
                          <div className="font-bold text-slate-900">
                            <Price amount={o.tax} />
                          </div>
                        </div>
                        <div>
                          <div className="uppercase tracking-wider text-slate-400">
                            Total
                          </div>
                          <div className="font-extrabold text-[#0b6e3e]">
                            <Price amount={o.total} />
                          </div>
                        </div>
                      </div>
                      {o.tracking_number && (
                        <div className="mt-3 text-xs text-slate-600">
                          Tracking:{" "}
                          <span className="font-mono font-semibold text-slate-900">
                            {o.tracking_number}
                          </span>
                        </div>
                      )}
                      {o.notes && (
                        <div className="mt-3 text-xs text-slate-600">
                          <span className="uppercase tracking-wider text-slate-400">Notes:</span>{" "}
                          {o.notes}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </SiteLayout>
  );
}