"use client";
import React, { useState, useEffect } from "react";
import {
  Package,
  Truck,
  CheckCircle,
  Loader2,
  User,
  X,
  Calendar,
} from "lucide-react";
import toast from "react-hot-toast";
import { EmptyState } from "@/components/marketplace/common/EmptyState";
import { formatDate } from "@/utils/marketplace";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import {
  orderService,
  orderStatusMeta,
  paymentStatusMeta,
  ORDER_STATUS,
  type MarketplaceOrder,
  type OrderStatusCode,
} from "@/services/orderService";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchMySales } from "@/store/slices/marketplaceOrdersSlice";

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

function ShipModal({
  order,
  onClose,
  onShipped,
}: {
  order: MarketplaceOrder;
  onClose: () => void;
  onShipped: () => void;
}) {
  const [trackingNumber, setTrackingNumber] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const submit = async () => {
    setSubmitting(true);
    try {
      await orderService.updateOrderStatus(
        order.id,
        2,
        trackingNumber.trim() || undefined,
      );
      toast.success("Order marked as shipped.");
      onShipped();
    } catch (err) {
      toast.error(
        err instanceof Error && err.message
          ? err.message
          : "Could not update the order.",
      );
      setSubmitting(false);
    }
  };

  return (
    <>
      <div
        className="fixed inset-0 z-[120]"
        style={{ background: "rgba(0,0,0,0.7)", backdropFilter: "blur(6px)" }}
        onClick={submitting ? undefined : onClose}
      />
      <div
        className="fixed z-[121] p-5"
        style={{
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: "min(400px, 92vw)",
          background: "var(--card)",
          borderRadius: 18,
          border: "1px solid var(--border)",
          boxShadow: "0 24px 72px rgba(0,0,0,0.5)",
        }}
      >
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Truck size={15} color="var(--accent)" />
            <span
              className="text-sm font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              Mark as Shipped
            </span>
          </div>
          <button
            onClick={submitting ? undefined : onClose}
            className="w-7 h-7 rounded-full flex items-center justify-center"
            style={{ background: "var(--bg)" }}
          >
            <X size={13} className="text-[var(--text-muted)]" />
          </button>
        </div>
        <p className="text-xs mb-3" style={{ color: "var(--text-muted)" }}>
          Order #{order.id} · {order.listingName}
        </p>
        <input
          value={trackingNumber}
          onChange={(e) => setTrackingNumber(e.target.value)}
          placeholder="Tracking number (optional)"
          className="w-full rounded-xl px-3.5 py-2.5 text-[13px] outline-none mb-4"
          style={{
            background: "var(--bg)",
            border: "1px solid var(--border)",
            color: "var(--text-primary)",
          }}
        />
        <button
          onClick={submit}
          disabled={submitting}
          className="w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-bold text-white disabled:opacity-50"
          style={{ background: "var(--accent)" }}
        >
          {submitting && <Loader2 size={14} className="animate-spin" />}
          Confirm Shipment
        </button>
      </div>
    </>
  );
}

function SaleCard({
  order,
  onShip,
  onDeliver,
  delivering,
}: {
  order: MarketplaceOrder;
  onShip: () => void;
  onDeliver: () => void;
  delivering: boolean;
}) {
  const formatPrice = useFormatPrice();
  const status = orderStatusMeta(order.status);
  const payment = paymentStatusMeta(order.paymentStatus);
  const address = [order.address, order.city, order.state, order.country]
    .filter(Boolean)
    .join(", ");

  return (
    <div
      className="rounded-2xl p-4"
      style={{ background: "var(--card)", border: "1px solid var(--border)" }}
    >
      <div className="flex items-center justify-between mb-3">
        <div>
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            Order #{order.id}
          </p>
          <p
            className="text-xs mt-0.5 flex items-center gap-1"
            style={{ color: "var(--text-muted)" }}
          >
            <Calendar size={10} />
            {order.createdAt ? formatDate(order.createdAt) : "—"}
          </p>
        </div>
        <div className="flex items-center gap-1.5">
          <span
            className="text-xs px-2 py-1 rounded-full font-medium"
            style={{ background: `${payment.color}18`, color: payment.color }}
          >
            {payment.label}
          </span>
          <span
            className="text-xs px-2 py-1 rounded-full font-medium"
            style={{ background: `${status.color}18`, color: status.color }}
          >
            {status.label}
          </span>
        </div>
      </div>

      {/* Item */}
      <div className="flex items-center gap-3">
        {order.listingImage ? (
          <img
            src={order.listingImage}
            alt={order.listingName}
            className="w-12 h-12 rounded-lg object-cover shrink-0"
          />
        ) : (
          <div
            className="w-12 h-12 rounded-lg flex items-center justify-center shrink-0"
            style={{ background: "var(--bg)" }}
          >
            <Package size={18} className="text-[var(--text-muted)]" />
          </div>
        )}
        <div className="flex-1 min-w-0">
          <p
            className="text-sm truncate"
            style={{ color: "var(--text-primary)" }}
          >
            {order.listingName || `Listing #${order.listingId}`}
          </p>
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            Qty: {order.quantity}
          </p>
        </div>
        <p
          className="text-sm font-semibold shrink-0"
          style={{ color: "var(--text-primary)" }}
        >
          {formatPrice(order.price)}
        </p>
      </div>

      {/* Buyer + delivery address */}
      <div
        className="mt-3 pt-3 space-y-1.5"
        style={{ borderTop: "1px solid var(--border)" }}
      >
        {(order.buyerName || order.buyerChannelName) && (
          <div className="flex items-center gap-2">
            {order.buyerImage ? (
              <img
                src={order.buyerImage}
                alt=""
                className="w-4 h-4 rounded-full object-cover"
              />
            ) : (
              <User size={12} className="text-[var(--text-muted)]" />
            )}
            <span className="text-xs" style={{ color: "var(--text-muted)" }}>
              {order.buyerName || order.buyerChannelName}
            </span>
          </div>
        )}
        {address && (
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            Ship to: {address}
            {order.pincode ? ` — ${order.pincode}` : ""}
          </p>
        )}
        {order.trackingNumber && (
          <p
            className="text-xs flex items-center gap-1.5"
            style={{ color: "var(--accent)" }}
          >
            <Truck size={11} />
            <span className="font-mono">{order.trackingNumber}</span>
          </p>
        )}
      </div>

      {/* Footer */}
      <div
        className="flex items-center justify-between mt-3 pt-3"
        style={{ borderTop: "1px solid var(--border)" }}
      >
        <div>
          <p
            className="text-sm font-bold"
            style={{ color: "var(--text-primary)" }}
          >
            Total: {formatPrice(order.price)}
          </p>
          {order.sellerEarning > 0 && (
            <p className="text-xs" style={{ color: "#22c55e" }}>
              Your earning: {formatPrice(order.sellerEarning)}
            </p>
          )}
        </div>
        {order.status === ORDER_STATUS.CONFIRMED && (
          <button
            onClick={onShip}
            className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg font-medium text-white"
            style={{ background: "var(--accent)" }}
          >
            <Truck size={12} />
            Mark Shipped
          </button>
        )}
        {order.status === ORDER_STATUS.SHIPPED && (
          <button
            onClick={onDeliver}
            disabled={delivering}
            className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg font-medium text-white disabled:opacity-50"
            style={{ background: "#22c55e" }}
          >
            {delivering ? (
              <Loader2 size={12} className="animate-spin" />
            ) : (
              <CheckCircle size={12} />
            )}
            Mark Delivered
          </button>
        )}
      </div>
    </div>
  );
}

export function SellerOrdersDashboard() {
  const dispatch = useAppDispatch();
  const { orders, totalRows, isLoading, error } = useAppSelector(
    (s) => s.marketplaceOrders.mySales,
  );
  const [activeTab, setActiveTab] = useState<OrderStatusCode | "all">("all");
  const [shipOrder, setShipOrder] = useState<MarketplaceOrder | null>(null);
  const [deliveringId, setDeliveringId] = useState<number | null>(null);

  useEffect(() => {
    dispatch(fetchMySales({ status: activeTab }));
  }, [dispatch, activeTab]);

  const refresh = () => dispatch(fetchMySales({ status: activeTab }));

  const handleDeliver = async (order: MarketplaceOrder) => {
    setDeliveringId(order.id);
    try {
      await orderService.updateOrderStatus(order.id, 3);
      toast.success("Order marked as delivered.");
      refresh();
    } catch (err) {
      toast.error(
        err instanceof Error && err.message
          ? err.message
          : "Could not update the order.",
      );
    } finally {
      setDeliveringId(null);
    }
  };

  return (
    <div className="p-4 md:p-6 max-w-6xl mx-auto">
      <div className="mb-6">
        <h1
          className="text-xl font-bold"
          style={{ color: "var(--text-primary)" }}
        >
          Orders Received
        </h1>
        <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>
          Manage orders from your buyers
          {!isLoading
            ? ` · ${totalRows} order${totalRows === 1 ? "" : "s"}`
            : ""}
        </p>
      </div>

      {/* Status tabs */}
      <div className="flex gap-2 overflow-x-auto no-scrollbar mb-5">
        {STATUS_TABS.map((tab) => (
          <button
            key={String(tab.key)}
            onClick={() => setActiveTab(tab.key)}
            className="px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap"
            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 && !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>
      )}

      {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" style={{ color: "var(--text-muted)" }}>
            Loading orders…
          </p>
        </div>
      ) : orders.length === 0 ? (
        <EmptyState
          icon={Package}
          title="No orders yet"
          description="When buyers purchase your listings, orders will appear here."
        />
      ) : (
        <div className="space-y-3">
          {orders.map((order) => (
            <SaleCard
              key={order.id}
              order={order}
              onShip={() => setShipOrder(order)}
              onDeliver={() => handleDeliver(order)}
              delivering={deliveringId === order.id}
            />
          ))}
        </div>
      )}

      {shipOrder && (
        <ShipModal
          order={shipOrder}
          onClose={() => setShipOrder(null)}
          onShipped={() => {
            setShipOrder(null);
            refresh();
          }}
        />
      )}
    </div>
  );
}
