"use client";
import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { motion } from "framer-motion";
import {
  ArrowLeft,
  Package,
  Truck,
  CheckCircle,
  XCircle,
  MapPin,
  MessageCircle,
  Loader2,
  Star,
  User,
  CreditCard,
  Copy,
} from "lucide-react";
import toast from "react-hot-toast";
import {
  orderService,
  orderStatusMeta,
  paymentStatusMeta,
  ORDER_STATUS,
  type MarketplaceOrder,
  type OrderReview,
} from "@/services/orderService";
import { formatDate } from "@/utils/marketplace";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchOrderDetail,
  setMyReview,
  clearOrderDetail,
} from "@/store/slices/marketplaceOrdersSlice";

const TIMELINE_STEPS = [
  { status: ORDER_STATUS.PLACED, label: "Placed", icon: Package },
  { status: ORDER_STATUS.CONFIRMED, label: "Confirmed", icon: CheckCircle },
  { status: ORDER_STATUS.SHIPPED, label: "Shipped", icon: Truck },
  { status: ORDER_STATUS.DELIVERED, label: "Delivered", icon: CheckCircle },
];

function SectionCard({
  title,
  children,
}: {
  title?: string;
  children: React.ReactNode;
}) {
  return (
    <div
      className="rounded-2xl p-4"
      style={{ background: "var(--card)", border: "1px solid var(--border)" }}
    >
      {title && (
        <p className="text-xs font-bold mb-3 text-[var(--text-muted)] uppercase tracking-wide">
          {title}
        </p>
      )}
      {children}
    </div>
  );
}

function StatusTimeline({ order }: { order: MarketplaceOrder }) {
  if (order.status === ORDER_STATUS.CANCELLED) {
    return (
      <div
        className="flex items-center gap-3 rounded-xl px-4 py-3"
        style={{
          background: "rgba(239,68,68,0.08)",
          border: "1px solid rgba(239,68,68,0.2)",
        }}
      >
        <XCircle size={18} color="#ef4444" />
        <div>
          <p className="text-sm font-bold" style={{ color: "#ef4444" }}>
            Order Cancelled
          </p>
          <p className="text-[11px] text-[var(--text-muted)]">
            {order.updatedAt ? formatDate(order.updatedAt) : ""}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex items-center">
      {TIMELINE_STEPS.map((step, i) => {
        const reached = order.status >= step.status;
        const Icon = step.icon;
        return (
          <div
            key={step.label}
            className="flex items-center flex-1 last:flex-none"
          >
            <div className="flex flex-col items-center gap-1.5">
              <div
                className="w-8 h-8 rounded-full flex items-center justify-center transition-colors"
                style={{
                  background: reached ? "var(--accent)" : "var(--bg)",
                  border: `1px solid ${reached ? "var(--accent)" : "var(--border)"}`,
                }}
              >
                <Icon
                  size={14}
                  color={reached ? "#fff" : "var(--text-muted)"}
                />
              </div>
              <span
                className="text-[9px] font-semibold whitespace-nowrap"
                style={{
                  color: reached ? "var(--text-primary)" : "var(--text-muted)",
                }}
              >
                {step.label}
              </span>
            </div>
            {i < TIMELINE_STEPS.length - 1 && (
              <div
                className="flex-1 h-0.5 mx-1.5 mb-5 rounded"
                style={{
                  background:
                    order.status > step.status
                      ? "var(--accent)"
                      : "var(--border)",
                }}
              />
            )}
          </div>
        );
      })}
    </div>
  );
}

function ReviewSection({
  order,
  existingReview,
  onSubmitted,
}: {
  order: MarketplaceOrder;
  existingReview: OrderReview | null;
  onSubmitted: (review: OrderReview) => void;
}) {
  const [rating, setRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);
  const [review, setReview] = useState("");
  const [submitting, setSubmitting] = useState(false);

  if (existingReview) {
    return (
      <SectionCard title="Your Review">
        <div className="flex items-center gap-1 mb-2">
          {[1, 2, 3, 4, 5].map((n) => (
            <Star
              key={n}
              size={16}
              fill={n <= existingReview.rating ? "#f0c040" : "none"}
              color={
                n <= existingReview.rating ? "#f0c040" : "var(--text-muted)"
              }
            />
          ))}
        </div>
        {existingReview.review && (
          <p className="text-sm text-[var(--text-primary)] leading-relaxed">
            {existingReview.review}
          </p>
        )}
      </SectionCard>
    );
  }

  const handleSubmit = async () => {
    if (rating < 1) {
      toast.error("Please select a rating.");
      return;
    }
    setSubmitting(true);
    try {
      await orderService.addOrderReview({
        orderId: order.id,
        sellerId: order.sellerId,
        review: review.trim(),
        rating,
      });
      toast.success("Thanks for your review!");
      onSubmitted({
        id: 0,
        classifiedOrderId: order.id,
        sellerId: order.sellerId,
        userId: order.buyerId,
        review: review.trim(),
        rating,
        createdAt: new Date().toISOString(),
      });
    } catch (err) {
      toast.error(
        err instanceof Error && err.message
          ? err.message
          : "Could not submit review.",
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SectionCard title="Rate this order">
      <div className="flex items-center gap-1.5 mb-3">
        {[1, 2, 3, 4, 5].map((n) => (
          <button
            key={n}
            onClick={() => setRating(n)}
            onMouseEnter={() => setHoverRating(n)}
            onMouseLeave={() => setHoverRating(0)}
            className="transition-transform hover:scale-110"
          >
            <Star
              size={22}
              fill={n <= (hoverRating || rating) ? "#f0c040" : "none"}
              color={
                n <= (hoverRating || rating) ? "#f0c040" : "var(--text-muted)"
              }
            />
          </button>
        ))}
      </div>
      <textarea
        value={review}
        onChange={(e) => setReview(e.target.value)}
        placeholder="Share your experience with this seller… (optional)"
        rows={3}
        className="w-full rounded-xl px-3.5 py-2.5 text-[13px] outline-none resize-none mb-3"
        style={{
          background: "var(--bg)",
          border: "1px solid var(--border)",
          color: "var(--text-primary)",
        }}
      />
      <button
        onClick={handleSubmit}
        disabled={submitting}
        className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold text-white disabled:opacity-50"
        style={{ background: "var(--accent)" }}
      >
        {submitting && <Loader2 size={12} className="animate-spin" />}
        Submit Review
      </button>
    </SectionCard>
  );
}

export function OrderDetail() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const params = useParams<{ id: string }>();
  const orderId = params?.id;
  const formatPrice = useFormatPrice();

  const { order, myReview, isLoading, error } = useAppSelector(
    (s) => s.marketplaceOrders.detail,
  );
  const [invoiceLoading, setInvoiceLoading] = useState(false);

  useEffect(() => {
    if (orderId) dispatch(fetchOrderDetail(orderId));
    return () => {
      dispatch(clearOrderDetail());
    };
  }, [dispatch, orderId]);

  const handleInvoice = async () => {
    if (!order) return;
    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);
    }
  };

  const copyTracking = () => {
    if (!order?.trackingNumber) return;
    navigator.clipboard.writeText(order.trackingNumber);
    toast.success("Tracking number copied.");
  };

  if (isLoading) {
    return (
      <div
        className="min-h-full flex flex-col items-center justify-center py-32 gap-3"
        style={{ background: "var(--bg)" }}
      >
        <Loader2 size={28} className="animate-spin" color="var(--accent)" />
        <p className="text-xs text-[var(--text-muted)]">Loading order…</p>
      </div>
    );
  }

  if (error || !order) {
    return (
      <div
        className="min-h-full flex flex-col items-center justify-center py-32 gap-4"
        style={{ background: "var(--bg)" }}
      >
        <Package size={32} className="text-[var(--text-muted)]" />
        <p className="text-sm font-semibold text-[var(--text-primary)]">
          {error || "Order not found"}
        </p>
        <button
          onClick={() => router.push("/marketplace/orders")}
          className="px-5 py-2.5 rounded-xl text-sm font-semibold text-white"
          style={{ background: "var(--accent)" }}
        >
          Back to My Orders
        </button>
      </div>
    );
  }

  const status = orderStatusMeta(order.status);
  const payment = paymentStatusMeta(order.paymentStatus);

  return (
    <div className="min-h-full pb-24" style={{ background: "var(--bg)" }}>
      <div className="max-w-3xl mx-auto px-4 py-6">
        {/* Header */}
        <div className="flex items-center gap-3 mb-5">
          <button
            onClick={() => router.back()}
            className="w-9 h-9 rounded-xl flex items-center justify-center"
            style={{
              background: "var(--card)",
              border: "1px solid var(--border)",
            }}
          >
            <ArrowLeft size={16} className="text-[var(--text-primary)]" />
          </button>
          <div className="flex-1 min-w-0">
            <h1 className="text-lg font-black text-[var(--text-primary)]">
              Order #{order.id}
            </h1>
            <p className="text-[11px] text-[var(--text-muted)]">
              Placed {order.createdAt ? formatDate(order.createdAt) : "—"}
            </p>
          </div>
          <span
            className="text-[11px] px-2.5 py-1 rounded-full font-bold shrink-0"
            style={{ background: `${status.color}18`, color: status.color }}
          >
            {status.label}
          </span>
        </div>

        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="space-y-4"
        >
          {/* Timeline */}
          <SectionCard>
            <StatusTimeline order={order} />
          </SectionCard>

          {/* Product */}
          <SectionCard title="Item">
            <div className="flex gap-3">
              {order.listingImage ? (
                <img
                  src={order.listingImage}
                  alt={order.listingName}
                  className="w-16 h-16 rounded-xl object-cover shrink-0"
                />
              ) : (
                <div
                  className="w-16 h-16 rounded-xl flex items-center justify-center shrink-0"
                  style={{ background: "var(--bg)" }}
                >
                  <Package size={22} className="text-[var(--text-muted)]" />
                </div>
              )}
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-[var(--text-primary)] line-clamp-2">
                  {order.listingName || `Listing #${order.listingId}`}
                </p>
                <p className="text-xs text-[var(--text-muted)] mt-1">
                  Qty: {order.quantity}
                </p>
              </div>
              <p className="text-sm font-black text-[var(--accent)] shrink-0">
                {formatPrice(order.price)}
              </p>
            </div>
          </SectionCard>

          {/* Tracking */}
          {order.trackingNumber && (
            <SectionCard title="Tracking">
              <div className="flex items-center gap-3 mb-3">
                <Truck size={16} color="var(--accent)" />
                <span className="text-sm font-mono font-semibold text-[var(--text-primary)] flex-1">
                  {order.trackingNumber}
                </span>
                <button
                  onClick={copyTracking}
                  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)" }}
                >
                  <Copy size={11} />
                  Copy
                </button>
              </div>
              <button
                onClick={() => router.push(`/marketplace/orders/${order.id}/tracking`)}
                className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-xs font-bold text-white transition-all hover:brightness-110"
                style={{ background: "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)" }}
              >
                <Truck size={13} />
                Track Live Shipment
              </button>
            </SectionCard>
          )}

          {/* Seller */}
          <SectionCard title="Seller">
            <div className="flex items-center gap-3">
              {order.sellerImage ? (
                <img
                  src={order.sellerImage}
                  alt=""
                  className="w-10 h-10 rounded-full object-cover"
                />
              ) : (
                <div
                  className="w-10 h-10 rounded-full flex items-center justify-center"
                  style={{ background: "var(--bg)" }}
                >
                  <User size={16} className="text-[var(--text-muted)]" />
                </div>
              )}
              <div className="flex-1 min-w-0">
                <p className="text-sm font-bold text-[var(--text-primary)] truncate">
                  {order.sellerName || "Seller"}
                </p>
                {order.sellerChannelName && (
                  <p className="text-[11px] text-[var(--text-muted)] truncate">
                    {order.sellerChannelName}
                  </p>
                )}
              </div>
              <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} />
                Chat
              </button>
            </div>
          </SectionCard>

          {/* Delivery address */}
          <SectionCard title="Delivery Address">
            <div className="flex items-start gap-2.5">
              <MapPin
                size={14}
                color="var(--accent)"
                className="mt-0.5 shrink-0"
              />
              <p className="text-sm text-[var(--text-primary)] leading-relaxed">
                {[order.address, order.city, order.state, order.country]
                  .filter(Boolean)
                  .join(", ")}
                {order.pincode ? ` — ${order.pincode}` : ""}
              </p>
            </div>
          </SectionCard>

          {/* Payment */}
          <SectionCard title="Payment">
            <div className="space-y-2.5">
              <div className="flex items-center justify-between">
                <span className="text-xs text-[var(--text-muted)]">Status</span>
                <span
                  className="text-[11px] px-2 py-0.5 rounded-full font-bold"
                  style={{
                    background: `${payment.color}18`,
                    color: payment.color,
                  }}
                >
                  {payment.label}
                </span>
              </div>
              {order.transactionId && (
                <div className="flex items-center justify-between gap-3">
                  <span className="text-xs text-[var(--text-muted)]">
                    Transaction ID
                  </span>
                  <span className="text-xs font-mono text-[var(--text-primary)] truncate">
                    {order.transactionId}
                  </span>
                </div>
              )}
              <div
                className="flex items-center justify-between pt-2.5"
                style={{ borderTop: "1px solid var(--border)" }}
              >
                <span className="text-sm font-bold text-[var(--text-primary)]">
                  Total
                </span>
                <span className="text-sm font-black text-[var(--accent)]">
                  {formatPrice(order.price)}
                </span>
              </div>
            </div>
            {order.paymentStatus === 1 && (
              <button
                onClick={handleInvoice}
                disabled={invoiceLoading}
                className="mt-3 flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold border border-[var(--border)] text-[var(--text-primary)] disabled:opacity-50"
                style={{ background: "var(--bg)" }}
              >
                {invoiceLoading ? (
                  <Loader2 size={12} className="animate-spin" />
                ) : (
                  <CreditCard size={12} />
                )}
                Download Invoice
              </button>
            )}
          </SectionCard>

          {/* Review (delivered orders only) */}
          {order.status === ORDER_STATUS.DELIVERED && (
            <ReviewSection
              order={order}
              existingReview={myReview}
              onSubmitted={(review) => dispatch(setMyReview(review))}
            />
          )}
        </motion.div>
      </div>
    </div>
  );
}
