"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Package,
  Truck,
  CheckCircle,
  Search,
  X,
  MessageCircle,
  Download,
  ChevronRight,
  Calendar,
  Loader2,
  User,
  CreditCard,
  type LucideProps,
} from "lucide-react";
import toast from "react-hot-toast";
import { PayOrderModal } from "./PayOrderModal";
import {
  orderService,
  orderStatusMeta,
  paymentStatusMeta,
  type MarketplaceOrder,
  type OrderStatusCode,
} from "@/services/orderService";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchMyOrders } from "@/store/slices/marketplaceOrdersSlice";
import { formatDate } from "@/utils/marketplace";
import { useFormatPrice } from "@/hooks/useFormatPrice";

const TABS: { key: OrderStatusCode | "all"; label: string }[] = [
  { key: "all", label: "All" },
  { key: 0, label: "Placed" },
  { key: 1, label: "Confirmed" },
  { key: 2, label: "Shipped" },
  { key: 3, label: "Delivered" },
  { key: 4, label: "Cancelled" },
];

function StatCard({
  icon: Icon,
  label,
  value,
  color,
  delay,
}: {
  icon: React.ForwardRefExoticComponent<
    Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>
  >;
  label: string;
  value: number;
  color: string;
  delay: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay }}
      className="flex-1 min-w-[100px] rounded-2xl p-4 border border-[var(--border)] flex flex-col gap-2"
      style={{ background: "var(--card)" }}
    >
      <div
        className="w-8 h-8 rounded-xl flex items-center justify-center"
        style={{ background: `${color}18` }}
      >
        <Icon size={16} color={color} />
      </div>
      <div>
        <p className="text-xl font-black text-[var(--text-primary)]">{value}</p>
        <p className="text-[10px] text-[var(--text-muted)]">{label}</p>
      </div>
    </motion.div>
  );
}

function OrderCard({
  order,
  idx,
  onPayNow,
}: {
  order: MarketplaceOrder;
  idx: number;
  onPayNow: (order: MarketplaceOrder) => void;
}) {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const [invoiceLoading, setInvoiceLoading] = useState(false);
  const status = orderStatusMeta(order.status);
  const payment = paymentStatusMeta(order.paymentStatus);
  const isActive = order.status < 3;

  const handleInvoice = async (e: React.MouseEvent) => {
    e.stopPropagation();
    setInvoiceLoading(true);
    try {
      const url = await orderService.getInvoicePdfUrl(order.id);
      window.open(url, "_blank", "noopener");
    } catch {
      toast.error("Invoice is not available yet.");
    } finally {
      setInvoiceLoading(false);
    }
  };

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.96 }}
      transition={{
        delay: idx * 0.04,
        type: "spring",
        stiffness: 300,
        damping: 28,
      }}
      className="rounded-2xl overflow-hidden border border-[var(--border)] cursor-pointer group"
      style={{ background: "var(--card)" }}
      onClick={() => router.push(`/marketplace/orders/${order.id}`)}
    >
      {/* Product info */}
      <div className="flex gap-3 p-4 border-b border-[var(--border)]">
        <div className="relative shrink-0">
          {order.listingImage ? (
            <img
              src={order.listingImage}
              alt={order.listingName}
              className="w-16 h-16 rounded-xl object-cover"
            />
          ) : (
            <div
              className="w-16 h-16 rounded-xl flex items-center justify-center"
              style={{ background: "var(--bg)" }}
            >
              <Package size={22} className="text-[var(--text-muted)]" />
            </div>
          )}
          {isActive && order.status !== 4 && (
            <div
              className="absolute -top-1 -right-1 w-4 h-4 rounded-full flex items-center justify-center"
              style={{ background: "var(--accent)" }}
            >
              <div className="w-1.5 h-1.5 rounded-full bg-white" />
            </div>
          )}
        </div>

        <div className="flex-1 min-w-0">
          <p className="text-sm font-bold text-[var(--text-primary)] line-clamp-1 mb-1 group-hover:text-[var(--accent)] transition-colors">
            {order.listingName || `Order #${order.id}`}
          </p>
          <div className="flex items-center gap-2 mb-2">
            {order.sellerImage ? (
              <img
                src={order.sellerImage}
                alt=""
                className="w-4 h-4 rounded-full object-cover"
              />
            ) : (
              <User size={12} className="text-[var(--text-muted)]" />
            )}
            <span className="text-xs text-[var(--text-muted)] truncate">
              {order.sellerName || order.sellerChannelName}
            </span>
          </div>
          <div className="flex items-center gap-1.5 flex-wrap">
            <span
              className="text-[10px] px-2 py-0.5 rounded-full font-semibold"
              style={{ background: `${status.color}18`, color: status.color }}
            >
              {status.label}
            </span>
            <span
              className="text-[10px] px-2 py-0.5 rounded-full font-semibold"
              style={{ background: `${payment.color}18`, color: payment.color }}
            >
              {payment.label}
            </span>
          </div>
        </div>

        <div className="text-right shrink-0">
          <p className="text-sm font-black text-[var(--accent)]">
            {formatPrice(order.price)}
          </p>
          <p className="text-[10px] text-[var(--text-muted)] mt-1">
            Qty: {order.quantity}
          </p>
        </div>
      </div>

      {/* Meta */}
      <div className="flex items-center gap-4 px-4 py-3">
        <div className="flex items-center gap-1.5 text-[10px] text-[var(--text-muted)]">
          <Calendar size={10} />
          {order.createdAt ? formatDate(order.createdAt) : "—"}
        </div>
        <div className="flex items-center gap-1.5 text-[10px] text-[var(--text-muted)]">
          <Package size={10} />#{order.id}
        </div>
        {order.trackingNumber && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              router.push(`/marketplace/orders/${order.id}/tracking`);
            }}
            className="flex items-center gap-1.5 text-[10px] hover:underline"
            style={{ color: "var(--accent)" }}
          >
            <Truck size={10} />
            <span className="font-mono">{order.trackingNumber}</span>
          </button>
        )}
        <div className="ml-auto">
          <ChevronRight
            size={14}
            className="text-[var(--text-muted)] group-hover:text-[var(--text-primary)] transition-colors"
          />
        </div>
      </div>

      {/* Quick actions */}
      <div
        className="flex items-center gap-2 px-4 py-3 border-t border-[var(--border)]"
        onClick={(e) => e.stopPropagation()}
      >
        {order.paymentStatus !== 1 && order.status !== 4 && (
          <button
            onClick={() => onPayNow(order)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold text-white transition-all hover:brightness-110"
            style={{ background: "var(--accent)" }}
          >
            <CreditCard size={11} />
            Pay Now
          </button>
        )}
        <button
          onClick={() => router.push(`/marketplace/messages`)}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
          style={{ background: "var(--bg)" }}
        >
          <MessageCircle size={11} />
          Seller
        </button>
        {order.paymentStatus === 1 && (
          <button
            onClick={handleInvoice}
            disabled={invoiceLoading}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors disabled:opacity-50"
            style={{ background: "var(--bg)" }}
          >
            {invoiceLoading ? (
              <Loader2 size={11} className="animate-spin" />
            ) : (
              <Download size={11} />
            )}
            Invoice
          </button>
        )}
        <button
          onClick={() => router.push(`/marketplace/orders/${order.id}`)}
          className="ml-auto flex items-center gap-1 text-xs font-semibold text-[var(--accent)]"
        >
          Details <ChevronRight size={12} />
        </button>
      </div>
    </motion.div>
  );
}

export function BuyerOrdersDashboard() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const {
    orders,
    counts,
    currentPage,
    hasMore,
    isLoading,
    isLoadingMore,
    error,
  } = useAppSelector((s) => s.marketplaceOrders.myOrders);
  const [activeTab, setActiveTab] = useState<OrderStatusCode | "all">("all");
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [payOrder, setPayOrder] = useState<MarketplaceOrder | null>(null);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search.trim()), 400);
    return () => clearTimeout(timer);
  }, [search]);

  useEffect(() => {
    dispatch(fetchMyOrders({ status: activeTab, search: debouncedSearch }));
  }, [dispatch, activeTab, debouncedSearch]);

  const refresh = () =>
    dispatch(fetchMyOrders({ status: activeTab, search: debouncedSearch }));

  const loadMore = () =>
    dispatch(
      fetchMyOrders({
        status: activeTab,
        search: debouncedSearch,
        page: currentPage + 1,
        append: true,
      }),
    );

  return (
    <div className="min-h-full pb-20" style={{ background: "var(--bg)" }}>
      <div className="max-w-6xl mx-auto px-4 py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-5">
          <div>
            <h1 className="text-xl font-black text-[var(--text-primary)]">
              My Orders
            </h1>
            <p className="text-xs text-[var(--text-muted)] mt-0.5">
              Track and manage your purchases
            </p>
          </div>
          <button
            onClick={() => router.push("/marketplace/seller/orders")}
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold"
            style={{
              background: "rgba(240,192,64,0.1)",
              color: "#f0c040",
              border: "1px solid rgba(240,192,64,0.3)",
            }}
          >
            Seller View →
          </button>
        </div>

        {/* Stats */}
        <div className="flex gap-3 mb-6 overflow-x-auto no-scrollbar pb-1">
          <StatCard
            icon={Package}
            label="Total"
            value={counts.total}
            color="#60a5fa"
            delay={0}
          />
          <StatCard
            icon={Truck}
            label="Shipped"
            value={counts.shipped}
            color="#f0c040"
            delay={0.1}
          />
          <StatCard
            icon={CheckCircle}
            label="Delivered"
            value={counts.delivered}
            color="#22c55e"
            delay={0.2}
          />
        </div>

        {/* Search */}
        <div
          className="flex items-center gap-2 rounded-xl px-4 py-2.5 mb-4"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border)",
          }}
        >
          <Search size={14} className="text-[var(--text-muted)]" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by product or price…"
            className="flex-1 bg-transparent outline-none text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)]"
          />
          {search && (
            <button onClick={() => setSearch("")}>
              <X size={13} className="text-[var(--text-muted)]" />
            </button>
          )}
        </div>

        {/* Tabs */}
        <div className="flex gap-1.5 overflow-x-auto no-scrollbar mb-5 pb-1">
          {TABS.map((tab) => (
            <button
              key={String(tab.key)}
              onClick={() => setActiveTab(tab.key)}
              className="shrink-0 px-3 py-1.5 rounded-full text-xs font-semibold transition-colors"
              style={{
                background:
                  activeTab === tab.key ? "var(--accent)" : "var(--card)",
                color: activeTab === tab.key ? "#fff" : "var(--text-muted)",
                border: `1px solid ${activeTab === tab.key ? "var(--accent)" : "var(--border)"}`,
              }}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Error */}
        {error && !isLoading && (
          <div
            className="text-xs px-4 py-3 rounded-xl mb-4"
            style={{
              background: "rgba(244,63,94,0.08)",
              color: "#f43f5e",
              border: "1px solid rgba(244,63,94,0.15)",
            }}
          >
            {error}
          </div>
        )}

        {/* Order list */}
        {isLoading ? (
          <div className="flex flex-col items-center py-20 gap-3">
            <Loader2
              size={28}
              className="animate-spin"
              color="var(--accent)"
            />
            <p className="text-xs text-[var(--text-muted)]">Loading orders…</p>
          </div>
        ) : (
          <AnimatePresence mode="popLayout">
            {orders.length === 0 ? (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="flex flex-col items-center py-20 gap-4"
              >
                <div
                  className="w-16 h-16 rounded-2xl flex items-center justify-center"
                  style={{ background: "var(--card)" }}
                >
                  <Package size={28} className="text-[var(--text-muted)]" />
                </div>
                <p className="font-semibold text-[var(--text-primary)]">
                  No orders found
                </p>
                <p className="text-sm text-[var(--text-muted)] text-center">
                  {debouncedSearch
                    ? "Try a different search."
                    : "You haven't placed any orders yet."}
                </p>
                <button
                  onClick={() => router.push("/marketplace")}
                  className="px-5 py-2.5 rounded-xl text-sm font-semibold text-white"
                  style={{ background: "var(--accent)" }}
                >
                  Browse Marketplace
                </button>
              </motion.div>
            ) : (
              <div className="space-y-4">
                {orders.map((order, i) => (
                  <OrderCard
                    key={order.id}
                    order={order}
                    idx={i}
                    onPayNow={setPayOrder}
                  />
                ))}
                {hasMore && (
                  <div className="flex justify-center pt-2">
                    <button
                      onClick={loadMore}
                      disabled={isLoadingMore}
                      className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold border border-[var(--border)] text-[var(--text-primary)] disabled:opacity-50"
                      style={{ background: "var(--card)" }}
                    >
                      {isLoadingMore && (
                        <Loader2 size={13} className="animate-spin" />
                      )}
                      Load more
                    </button>
                  </div>
                )}
              </div>
            )}
          </AnimatePresence>
        )}
      </div>

      <PayOrderModal
        order={payOrder}
        onClose={() => setPayOrder(null)}
        onPaid={() => {
          setPayOrder(null);
          toast.success("Payment completed successfully!");
          refresh();
        }}
        onError={(message) => {
          setPayOrder(null);
          toast.error(
            message === "Payment cancelled"
              ? "Payment was cancelled."
              : "Payment failed. Please try again.",
          );
        }}
      />
    </div>
  );
}
