import { MARKETPLACE_CURRENCY, MARKETPLACE_PLATFORM_FEE } from "@/constants/marketplace";
import type { ListingCondition, OrderStatus, ApiListing, ApiListingDetail } from "@/types/marketplace";
import type { BuyerListing } from "@/components/marketplace/buyer/mockData";

export function formatPrice(amount: number, currency = MARKETPLACE_CURRENCY): string {
  return `${currency}${amount.toLocaleString("en-IN")}`;
}

export function formatDiscount(original: number, current: number): string {
  const pct = Math.round(((original - current) / original) * 100);
  return `${pct}% off`;
}

export function platformFee(amount: number): number {
  return Math.round(amount * MARKETPLACE_PLATFORM_FEE);
}

export function netEarning(amount: number): number {
  return amount - platformFee(amount);
}

export function getConditionLabel(condition: ListingCondition): string {
  const labels: Record<ListingCondition, string> = {
    new: "Brand New",
    like_new: "Like New",
    good: "Good",
    fair: "Fair",
    poor: "Poor",
  };
  return labels[condition] ?? condition;
}

export function getConditionColor(condition: ListingCondition): string {
  const colors: Record<ListingCondition, string> = {
    new: "#22c55e",
    like_new: "#84cc16",
    good: "#f59e0b",
    fair: "#f97316",
    poor: "#ef4444",
  };
  return colors[condition] ?? "#6b7280";
}

export function getOrderStatusColor(status: OrderStatus): string {
  const colors: Record<OrderStatus, string> = {
    placed: "#6366f1",
    confirmed: "#3b82f6",
    shipped: "#f59e0b",
    out_for_delivery: "#f97316",
    delivered: "#22c55e",
    cancelled: "#ef4444",
    refunded: "#8b5cf6",
  };
  return colors[status] ?? "#6b7280";
}

export function getOrderStatusLabel(status: OrderStatus): string {
  const labels: Record<OrderStatus, string> = {
    placed: "Order Placed",
    confirmed: "Confirmed",
    shipped: "Shipped",
    out_for_delivery: "Out for Delivery",
    delivered: "Delivered",
    cancelled: "Cancelled",
    refunded: "Refunded",
  };
  return labels[status] ?? status;
}

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^\w\s-]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .trim();
}

export function timeAgo(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (seconds < 60) return "just now";
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `${days}d ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months}mo ago`;
  return `${Math.floor(months / 12)}y ago`;
}

export function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString("en-IN", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}

export function truncate(text: string, maxLen: number): string {
  if (text.length <= maxLen) return text;
  return text.slice(0, maxLen - 1) + "…";
}

const NO_IMG = "no_img.png";

export function mapApiToListing(api: ApiListing): BuyerListing {
  return {
    id: String(api.id),
    slug: `${slugify(api.title)}-${api.id}`,
    title: api.title,
    price: api.price,
    quantity: api.quantity ?? 1,
    originalPrice: undefined,
    isNegotiable: false,
    images: [api.image],
    category: api.category_name,
    subCategory: api.category_name,
    condition: api.listing_condition === 1 ? "new" : "used",
    city: api.city,
    area: api.area,
    pincode: "",
    postedAt: api.created_at,
    views: api.total_view,
    savedCount: api.total_wishlist,
    shareCount: 0,
    isFeatured: api.is_featured === 1,
    listingStatus: api.status === 2 ? "sold" : "available",
    sellerId: api.channel_id,
    sellerFirebaseId: api.user_firebase_id,
    sellerName: api.user_full_name,
    sellerAvatar: api.user_image,
    sellerVerified: false,
    sellerJoinedDate: api.created_at,
    sellerTotalListings: 0,
    sellerResponseRate: 0,
    description: api.description,
    specs: {},
    tags: [],
  };
}

export function mapApiDetailToListing(api: ApiListingDetail): BuyerListing {
  const galleryImages = (api.gallery ?? [])
    .map((g) => g.image)
    .filter((img) => img && !img.includes(NO_IMG));
  const mainImage = api.image && !api.image.includes(NO_IMG) ? api.image : null;
  const allImages = [
    ...(mainImage ? [mainImage] : []),
    ...galleryImages,
  ];
  const images = allImages.length > 0 ? allImages : [api.image];

  return {
    id: String(api.id),
    slug: `${slugify(api.title)}-${api.id}`,
    title: api.title,
    price: api.price,
    quantity: api.quantity ?? 1,
    originalPrice: undefined,
    isNegotiable: false,
    images,
    category: api.category_name,
    subCategory: api.category_name,
    condition: api.listing_condition === 1 ? "new" : "used",
    city: api.city,
    area: api.area,
    pincode: "",
    postedAt: api.created_at,
    views: api.total_view,
    savedCount: api.total_wishlist,
    shareCount: 0,
    isFeatured: api.is_featured === 1,
    listingStatus: api.status === 2 ? "sold" : "available",
    sellerId: api.channel_id,
    sellerFirebaseId: api.user_firebase_id,
    sellerName: api.user_full_name,
    sellerAvatar: api.user_image,
    sellerVerified: false,
    sellerJoinedDate: api.created_at,
    sellerTotalListings: 0,
    sellerResponseRate: 0,
    description: api.description,
    specs: {},
    tags: [],
  };
}

export function isNoImg(url: string): boolean {
  return url.includes(NO_IMG);
}

export function buildSearchParams(filters: Record<string, unknown>): URLSearchParams {
  const params = new URLSearchParams();
  for (const [key, val] of Object.entries(filters)) {
    if (val === undefined || val === null || val === "") continue;
    if (Array.isArray(val)) {
      val.forEach((v) => params.append(key, String(v)));
    } else {
      params.set(key, String(val));
    }
  }
  return params;
}
