"use client";
import { useState, useMemo, useCallback } from "react";
import { useAppSelector } from "@/store/hooks";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Package,
  Truck,
  CheckCircle,
  XCircle,
  Clock,
  TrendingUp,
  Check,
  X,
  ChevronRight,
  ArrowUpRight,
} from "lucide-react";
import { useOrders } from "@/lib/OrderContext";
import { OrderStatusBadge } from "./OrderStatusBadge";
import { OrderTimeline } from "./OrderTimeline";
import { formatOrderDate, formatOrderDateTime, STATUS_CONFIG } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import type { Order, OrderStatus, ShippingInfo } from "./types";
import { animate } from "framer-motion";
import { useEffect, useRef } from "react";

// ─── Animated number ──────────────────────────────────────────────────────────
function AnimCounter({ value, prefix = "" }: { value: number; prefix?: string }) {
  const ref = useRef<HTMLSpanElement>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const controls = animate(0, value, {
      duration: 1.2,
      ease: [0.16, 1, 0.3, 1],
      onUpdate: (v) => { if (el) el.textContent = prefix + Math.round(v).toLocaleString("en-IN"); },
    });
    return controls.stop;
  }, [value, prefix]);
  return <span ref={ref}>{prefix}0</span>;
}

// ─── Shipment modal ───────────────────────────────────────────────────────────
function ShipmentModal({ orderId, onClose }: { orderId: string; onClose: () => void }) {
  const { addTrackingInfo } = useOrders();
  const [courier, setCourier] = useState("");
  const [tracking, setTracking] = useState("");
  const [estDate, setEstDate] = useState("");
  const [notes, setNotes] = useState("");
  const [done, setDone] = useState(false);

  const COURIERS = ["Blue Dart Express", "Delhivery", "DTDC", "Ekart Logistics", "XpressBees", "FedEx", "Other"];

  const submit = () => {
    if (!courier || !tracking) return;
    addTrackingInfo(orderId, {
      courierName: courier,
      trackingNumber: tracking,
      estimatedDelivery: estDate ? new Date(estDate).toISOString() : undefined,
    });
    setDone(true);
    setTimeout(onClose, 1400);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center sm:p-4"
      style={{ background: "rgba(0,0,0,0.7)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ y: "100%" }}
        animate={{ y: 0 }}
        exit={{ y: "100%" }}
        transition={{ type: "spring", stiffness: 300, damping: 30 }}
        className="w-full sm:max-w-md rounded-t-3xl sm:rounded-2xl overflow-hidden"
        style={{ background: "var(--card)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b border-[var(--border)]">
          <h3 className="font-bold text-[var(--text-primary)] flex items-center gap-2">
            <Truck size={15} className="text-yellow-400" /> Update Shipment
          </h3>
          <button onClick={onClose} className="p-1 rounded-full hover:bg-[var(--bg)]">
            <X size={15} className="text-[var(--text-muted)]" />
          </button>
        </div>

        {done ? (
          <div className="flex flex-col items-center py-12 gap-3">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ type: "spring", stiffness: 300, damping: 18 }}
              className="w-16 h-16 rounded-full flex items-center justify-center"
              style={{ background: "rgba(240,192,64,0.15)" }}
            >
              <Truck size={32} className="text-yellow-400" />
            </motion.div>
            <p className="font-bold text-[var(--text-primary)]">Shipment Updated!</p>
            <p className="text-xs text-[var(--text-muted)] text-center">Buyer has been notified.</p>
          </div>
        ) : (
          <div className="p-5 space-y-4 max-h-[75vh] overflow-y-auto">
            <div>
              <label className="text-xs text-[var(--text-muted)] font-medium mb-2 block">Courier Company *</label>
              <div className="grid grid-cols-2 gap-2">
                {COURIERS.map((c) => (
                  <button
                    key={c}
                    onClick={() => setCourier(c)}
                    className="px-3 py-2 rounded-xl text-xs text-left border transition-colors"
                    style={{
                      background: courier === c ? "rgba(240,192,64,0.1)" : "var(--bg)",
                      borderColor: courier === c ? "#f0c040" : "var(--border)",
                      color: courier === c ? "#f0c040" : "var(--text-muted)",
                    }}
                  >
                    {c}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="text-xs text-[var(--text-muted)] font-medium mb-1.5 block">Tracking Number *</label>
              <input
                value={tracking}
                onChange={(e) => setTracking(e.target.value)}
                placeholder="e.g. BD123456789IN"
                className="w-full px-4 py-2.5 rounded-xl text-sm font-mono outline-none text-[var(--text-primary)] placeholder:text-[var(--text-muted)]"
                style={{ background: "var(--bg)", border: "1.5px solid var(--border)" }}
              />
            </div>

            <div>
              <label className="text-xs text-[var(--text-muted)] font-medium mb-1.5 block">Estimated Delivery Date</label>
              <input
                type="date"
                value={estDate}
                onChange={(e) => setEstDate(e.target.value)}
                className="w-full px-4 py-2.5 rounded-xl text-sm outline-none text-[var(--text-primary)]"
                style={{ background: "var(--bg)", border: "1px solid var(--border)" }}
              />
            </div>

            <div>
              <label className="text-xs text-[var(--text-muted)] font-medium mb-1.5 block">Notes (optional)</label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={2}
                placeholder="Any additional notes for the buyer…"
                className="w-full px-4 py-2.5 rounded-xl text-sm outline-none resize-none text-[var(--text-primary)] placeholder:text-[var(--text-muted)]"
                style={{ background: "var(--bg)", border: "1px solid var(--border)" }}
              />
            </div>

            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={submit}
              disabled={!courier || !tracking}
              className="w-full py-3 rounded-xl text-sm font-bold text-white disabled:opacity-40"
              style={{ background: "#f0c040", color: "#1a1a2e" }}
            >
              Update Shipment
            </motion.button>
          </div>
        )}
      </motion.div>
    </motion.div>
  );
}

// ─── Confirm action modal ─────────────────────────────────────────────────────
function ConfirmActionModal({
  title,
  description,
  confirmLabel,
  confirmColor,
  onConfirm,
  onClose,
}: {
  title: string;
  description: string;
  confirmLabel: string;
  confirmColor: string;
  onConfirm: () => void;
  onClose: () => void;
}) {
  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.7)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.9, y: 16 }}
        animate={{ scale: 1, y: 0 }}
        exit={{ scale: 0.9 }}
        className="rounded-2xl overflow-hidden max-w-xs w-full p-6"
        style={{ background: "var(--card)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <h3 className="font-bold text-[var(--text-primary)] mb-2">{title}</h3>
        <p className="text-sm text-[var(--text-muted)] mb-5 leading-relaxed">{description}</p>
        <div className="flex gap-3">
          <button
            onClick={onClose}
            className="flex-1 py-2.5 rounded-xl text-sm border border-[var(--border)] text-[var(--text-muted)]"
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            className="flex-1 py-2.5 rounded-xl text-sm font-bold text-white"
            style={{ background: confirmColor }}
          >
            {confirmLabel}
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}

// ─── Seller order row ─────────────────────────────────────────────────────────
function SellerOrderRow({ order }: { order: Order }) {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const { updateOrderStatus, cancelOrder } = useOrders();
  const [showShipment, setShowShipment] = useState(false);
  const [confirmAction, setConfirmAction] = useState<null | {
    title: string;
    description: string;
    confirmLabel: string;
    confirmColor: string;
    onConfirm: () => void;
  }>(null);

  const nextAction = useMemo(() => {
    switch (order.status) {
      case "placed": return {
        label: "Confirm Order",
        color: "#22c55e",
        action: () => setConfirmAction({
          title: "Confirm Order?",
          description: "This will notify the buyer that you've confirmed their order.",
          confirmLabel: "Confirm",
          confirmColor: "#22c55e",
          onConfirm: () => {
            updateOrderStatus(order.id, "confirmed", "Seller confirmed the order and is preparing to ship.");
            setConfirmAction(null);
          },
        }),
      };
      case "confirmed": return {
        label: "Mark Packed",
        color: "#a78bfa",
        action: () => setConfirmAction({
          title: "Mark as Packed?",
          description: "Confirm the item has been securely packed.",
          confirmLabel: "Mark Packed",
          confirmColor: "#a78bfa",
          onConfirm: () => {
            updateOrderStatus(order.id, "packed", "Item has been packed and is ready for shipping.");
            setConfirmAction(null);
          },
        }),
      };
      case "packed": return {
        label: "Mark Shipped",
        color: "#f0c040",
        action: () => setShowShipment(true),
      };
      case "shipped": return {
        label: "Mark Delivered",
        color: "#22c55e",
        action: () => setConfirmAction({
          title: "Mark as Delivered?",
          description: "Confirm the buyer has received the package.",
          confirmLabel: "Mark Delivered",
          confirmColor: "#22c55e",
          onConfirm: () => {
            updateOrderStatus(order.id, "delivered", "Item delivered to the buyer.");
            setConfirmAction(null);
          },
        }),
      };
      default: return null;
    }
  }, [order.status, order.id, updateOrderStatus]);

  const canCancel = ["placed", "confirmed", "packed"].includes(order.status);

  return (
    <>
      <motion.tr
        layout
        className="border-t border-[var(--border)] hover:bg-[var(--bg)] transition-colors cursor-pointer"
        onClick={() => router.push(`/orders/${order.id}`)}
      >
        <td className="px-4 py-4">
          <div className="flex items-center gap-3">
            <img src={order.listingImage} alt="" className="w-10 h-10 rounded-xl object-cover shrink-0" />
            <div>
              <p className="text-xs font-semibold text-[var(--text-primary)] line-clamp-1 max-w-[140px]">
                {order.listingTitle}
              </p>
              <p className="text-[10px] text-[var(--text-muted)] font-mono">{order.id}</p>
            </div>
          </div>
        </td>
        <td className="px-4 py-4">
          <div className="flex items-center gap-2">
            <img src={order.buyerAvatar} alt="" className="w-6 h-6 rounded-full object-cover" />
            <p className="text-xs text-[var(--text-primary)]">{order.buyerName}</p>
          </div>
        </td>
        <td className="px-4 py-4">
          <span className="text-sm font-bold text-[var(--accent)]">{formatPrice(order.totalAmount)}</span>
          <p className="text-[9px] text-[var(--text-muted)]">{order.paymentMethod === "paypal" ? "PayPal" : "COD"}</p>
        </td>
        <td className="px-4 py-4">
          <OrderStatusBadge status={order.status} size="xs" pulse={order.status === "placed"} />
        </td>
        <td className="px-4 py-4">
          <p className="text-[10px] text-[var(--text-muted)]">{formatOrderDate(order.createdAt)}</p>
        </td>
        <td className="px-4 py-4" onClick={(e) => e.stopPropagation()}>
          <div className="flex items-center gap-2">
            {nextAction && (
              <button
                onClick={nextAction.action}
                className="text-[10px] px-2.5 py-1.5 rounded-lg font-semibold text-white whitespace-nowrap"
                style={{ background: nextAction.color }}
              >
                {nextAction.label}
              </button>
            )}
            {canCancel && (
              <button
                onClick={() => setConfirmAction({
                  title: "Cancel Order?",
                  description: "This will cancel the order. The buyer will be notified.",
                  confirmLabel: "Cancel Order",
                  confirmColor: "#ef4444",
                  onConfirm: () => {
                    cancelOrder(order.id, "Cancelled by seller");
                    setConfirmAction(null);
                  },
                })}
                className="p-1.5 rounded-lg border border-red-500/30 text-red-400 hover:bg-red-500/10 transition-colors"
              >
                <XCircle size={12} />
              </button>
            )}
          </div>
        </td>
      </motion.tr>

      <AnimatePresence>
        {showShipment && (
          <ShipmentModal orderId={order.id} onClose={() => setShowShipment(false)} />
        )}
        {confirmAction && (
          <ConfirmActionModal {...confirmAction} onClose={() => setConfirmAction(null)} />
        )}
      </AnimatePresence>
    </>
  );
}

// ─── Main SellerOrdersDashboard ───────────────────────────────────────────────
export function SellerOrdersDashboard() {
  const router = useRouter();
  const { sellerOrders } = useOrders();
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);

  const stats = useMemo(() => ({
    total: sellerOrders.length,
    pending: sellerOrders.filter((o) => o.status === "placed").length,
    confirmed: sellerOrders.filter((o) => o.status === "confirmed").length,
    packed: sellerOrders.filter((o) => o.status === "packed").length,
    shipped: sellerOrders.filter((o) => o.status === "shipped").length,
    delivered: sellerOrders.filter((o) => ["delivered", "completed"].includes(o.status)).length,
    cancelled: sellerOrders.filter((o) => o.status === "cancelled").length,
    revenue: sellerOrders
      .filter((o) => ["delivered", "completed"].includes(o.status))
      .reduce((sum, o) => sum + o.totalAmount, 0),
  }), [sellerOrders]);

  const statCards = [
    { label: "Total Orders", value: stats.total, icon: Package, color: "#60a5fa" },
    { label: "Pending", value: stats.pending, icon: Clock, color: "#f0c040" },
    { label: "Shipped", value: stats.shipped, icon: Truck, color: "#a78bfa" },
    { label: "Delivered", value: stats.delivered, icon: CheckCircle, color: "#22c55e" },
  ];

  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-6">
          <div>
            <h1 className="text-xl font-black text-[var(--text-primary)]">Seller Orders</h1>
            <p className="text-xs text-[var(--text-muted)] mt-0.5">Manage and fulfill your orders</p>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => router.push("/seller/earnings")}
              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)" }}
            >
              Earnings →
            </button>
          </div>
        </div>

        {/* Revenue highlight */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="rounded-2xl p-5 mb-5 border border-[var(--border)]"
          style={{ background: "linear-gradient(135deg, rgba(252,0,0,0.08) 0%, rgba(240,192,64,0.06) 100%)", borderColor: "rgba(252,0,0,0.2)" }}
        >
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-[var(--text-muted)] mb-1">Total Revenue Earned</p>
              <p className="text-3xl font-black text-[var(--accent)]">
                <AnimCounter value={stats.revenue} prefix={currencyCode} />
              </p>
            </div>
            <div className="w-12 h-12 rounded-2xl flex items-center justify-center" style={{ background: "rgba(252,0,0,0.12)" }}>
              <TrendingUp size={22} className="text-[var(--accent)]" />
            </div>
          </div>
        </motion.div>

        {/* Stats grid */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
          {statCards.map(({ label, value, icon: Icon, color }, i) => (
            <motion.div
              key={label}
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.07 }}
              className="rounded-2xl p-4 border border-[var(--border)]"
              style={{ background: "var(--card)" }}
            >
              <div className="w-8 h-8 rounded-xl flex items-center justify-center mb-3" style={{ background: `${color}18` }}>
                <Icon size={16} color={color} />
              </div>
              <p className="text-xl font-black text-[var(--text-primary)]">
                <AnimCounter value={value} />
              </p>
              <p className="text-[11px] text-[var(--text-muted)] mt-0.5">{label}</p>
            </motion.div>
          ))}
        </div>

        {/* Orders table */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.35 }}
          className="rounded-2xl overflow-hidden border border-[var(--border)]"
          style={{ background: "var(--card)" }}
        >
          <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
            <h2 className="text-sm font-bold text-[var(--text-primary)]">Orders</h2>
            <span className="text-xs text-[var(--text-muted)]">{sellerOrders.length} total</span>
          </div>

          {sellerOrders.length === 0 ? (
            <div className="flex flex-col items-center py-16 gap-3">
              <Package size={36} className="text-[var(--text-muted)] opacity-40" />
              <p className="font-semibold text-[var(--text-primary)]">No orders yet</p>
              <p className="text-sm text-[var(--text-muted)]">Your orders will appear here once buyers purchase your listings.</p>
              <button
                onClick={() => router.push("/marketplace/create")}
                className="px-5 py-2.5 rounded-xl text-sm font-semibold text-white mt-2"
                style={{ background: "var(--accent)" }}
              >
                Create a Listing
              </button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left min-w-[640px]">
                <thead>
                  <tr style={{ background: "rgba(255,255,255,0.02)" }}>
                    {["Product", "Buyer", "Amount", "Status", "Date", "Actions"].map((h) => (
                      <th key={h} className="px-4 py-3 text-[10px] uppercase tracking-wider font-semibold text-[var(--text-muted)]">
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  <AnimatePresence initial={false}>
                    {sellerOrders
                      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
                      .map((order) => (
                        <SellerOrderRow key={order.id} order={order} />
                      ))}
                  </AnimatePresence>
                </tbody>
              </table>
            </div>
          )}
        </motion.div>
      </div>
    </div>
  );
}
