import { useEffect, useMemo, useState } from "react";
import { ClipboardList, Search, ChevronDown, ChevronUp } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import CmsLayout from "./CmsLayout";
import { PageHeader } from "./ui";
import LoadingSpinner from "@/components/LoadingSpinner";
import { toast } from "sonner";

const client = createClient();

interface Order {
  id: number;
  order_number: string;
  status: string;
  payment_status: string;
  subtotal: number;
  shipping_cost: number;
  tax: number;
  total: number;
  currency: string;
  items_json?: string | null;
  shipping_address_json?: string | null;
  billing_email?: string | null;
  tracking_number?: string | null;
  notes?: string | null;
  created_at?: string | null;
}

interface OrderItemSnapshot {
  product_name: string;
  product_type: string;
  variant_label?: string;
  unit_price: number;
  quantity: number;
  line_total: number;
}

const STATUS_OPTIONS = [
  "pending",
  "processing",
  "shipped",
  "delivered",
  "cancelled",
  "refunded",
];

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 CmsShopOrders() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [expanded, setExpanded] = useState<number | null>(null);
  const [savingId, setSavingId] = useState<number | null>(null);

  const load = async () => {
    setLoading(true);
    try {
      const res = await client.entities.orders.queryAll({
        query: {},
        sort: "-id",
        limit: 500,
      });
      setOrders((res?.data?.items || []) as Order[]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const filtered = useMemo(() => {
    return orders.filter((o) => {
      if (statusFilter !== "all" && o.status !== statusFilter) return false;
      if (!search.trim()) return true;
      const q = search.trim().toLowerCase();
      return (
        o.order_number.toLowerCase().includes(q) ||
        (o.billing_email || "").toLowerCase().includes(q)
      );
    });
  }, [orders, search, statusFilter]);

  const updateOrder = async (o: Order, patch: Partial<Order>) => {
    setSavingId(o.id);
    try {
      await client.entities.orders.update({
        id: String(o.id),
        data: patch,
      });
      toast.success("Order updated.");
      setOrders((list) => list.map((x) => (x.id === o.id ? { ...x, ...patch } : x)));
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Update failed.";
      toast.error(msg);
    } finally {
      setSavingId(null);
    }
  };

  const parseItems = (o: Order): OrderItemSnapshot[] => {
    try {
      const v = JSON.parse(o.items_json || "[]");
      return Array.isArray(v) ? v : [];
    } catch {
      return [];
    }
  };

  const parseAddress = (o: Order): Record<string, string> | null => {
    if (!o.shipping_address_json) return null;
    try {
      const v = JSON.parse(o.shipping_address_json);
      return v && typeof v === "object" ? v : null;
    } catch {
      return null;
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<ClipboardList className="w-6 h-6" />}
        title="Shop Orders"
        description="Track orders, update fulfillment status, and add tracking numbers."
      />

      <div className="mb-4 flex flex-col md:flex-row gap-3 md:items-center">
        <div className="relative max-w-md flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search order # or email…"
            className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg bg-white"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white font-semibold"
        >
          <option value="all">All statuses</option>
          {STATUS_OPTIONS.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
      </div>

      {loading ? (
        <div className="py-16 flex justify-center">
          <LoadingSpinner />
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-2xl p-10 text-center text-slate-500">
              No orders found.
            </div>
          ) : (
            filtered.map((o) => {
              const isOpen = expanded === o.id;
              const items = parseItems(o);
              const addr = parseAddress(o);
              return (
                <div
                  key={o.id}
                  className="bg-white border border-slate-200 rounded-2xl overflow-hidden"
                >
                  <div className="p-4 flex flex-wrap items-center gap-3">
                    <div className="flex-1 min-w-[200px]">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="font-bold text-slate-900">
                          {o.order_number}
                        </span>
                        <span
                          className={`text-[10px] uppercase tracking-wider font-bold px-2 py-0.5 rounded-full ${
                            STATUS_COLORS[o.status] || "bg-slate-100 text-slate-700"
                          }`}
                        >
                          {o.status}
                        </span>
                        <span className="text-[10px] 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.billing_email || "—"} ·{" "}
                        {o.created_at ? o.created_at.slice(0, 10) : ""}
                      </div>
                    </div>
                    <div className="font-extrabold text-[#0b6e3e] text-lg">
                      SAR {Number(o.total || 0).toFixed(2)}
                    </div>
                    <select
                      value={o.status}
                      disabled={savingId === o.id}
                      onChange={(e) => updateOrder(o, { status: e.target.value })}
                      className="text-xs border border-slate-200 rounded-lg px-2 py-1.5 bg-white font-semibold"
                    >
                      {STATUS_OPTIONS.map((s) => (
                        <option key={s} value={s}>
                          {s}
                        </option>
                      ))}
                    </select>
                    <button
                      onClick={() => setExpanded(isOpen ? null : o.id)}
                      className="p-2 rounded-lg hover:bg-slate-100"
                      aria-label="Toggle details"
                    >
                      {isOpen ? (
                        <ChevronUp className="w-4 h-4" />
                      ) : (
                        <ChevronDown className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                  {isOpen && (
                    <div className="border-t border-slate-200 p-4 bg-slate-50 grid md:grid-cols-2 gap-5">
                      <div>
                        <h3 className="font-bold text-slate-900 text-sm mb-2">
                          Items
                        </h3>
                        <div className="space-y-2">
                          {items.map((it, idx) => (
                            <div
                              key={idx}
                              className="bg-white border border-slate-200 rounded-xl p-3 text-sm"
                            >
                              <div className="flex justify-between gap-2 flex-wrap">
                                <div>
                                  <div className="font-semibold text-slate-900">
                                    {it.product_name} × {it.quantity}
                                  </div>
                                  {it.variant_label && (
                                    <div className="text-xs text-slate-500">
                                      {it.variant_label}
                                    </div>
                                  )}
                                  <div className="text-xs text-slate-500 capitalize">
                                    {it.product_type}
                                  </div>
                                </div>
                                <div className="font-bold text-slate-900">
                                  SAR {Number(it.line_total || 0).toFixed(2)}
                                </div>
                              </div>
                            </div>
                          ))}
                          {items.length === 0 && (
                            <p className="text-xs text-slate-500">No items snapshot.</p>
                          )}
                        </div>
                      </div>

                      <div>
                        <h3 className="font-bold text-slate-900 text-sm mb-2">
                          Fulfillment
                        </h3>
                        <div className="space-y-3 bg-white border border-slate-200 rounded-xl p-3">
                          {addr ? (
                            <div className="text-xs text-slate-700 leading-relaxed">
                              <div className="font-semibold text-slate-900">
                                {addr.full_name}
                              </div>
                              <div>{addr.line1}</div>
                              {addr.line2 && <div>{addr.line2}</div>}
                              <div>
                                {addr.city}
                                {addr.state ? `, ${addr.state}` : ""}{" "}
                                {addr.postal_code}
                              </div>
                              <div>{addr.country}</div>
                              {addr.phone && <div>📞 {addr.phone}</div>}
                            </div>
                          ) : (
                            <div className="text-xs text-slate-500 italic">
                              No shipping address (digital/hosting order).
                            </div>
                          )}
                          <div>
                            <div className="text-xs uppercase tracking-wider font-semibold text-slate-600 mb-1">
                              Tracking number
                            </div>
                            <input
                              defaultValue={o.tracking_number || ""}
                              onBlur={(e) => {
                                if ((e.target.value || "") !== (o.tracking_number || "")) {
                                  updateOrder(o, { tracking_number: e.target.value });
                                }
                              }}
                              placeholder="Add tracking number"
                              className="w-full border border-slate-200 rounded-lg px-3 py-1.5 text-sm"
                            />
                          </div>
                          {o.notes && (
                            <div className="text-xs text-slate-600">
                              <span className="uppercase tracking-wider text-slate-400 font-semibold">
                                Notes:
                              </span>{" "}
                              {o.notes}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>
      )}
    </CmsLayout>
  );
}