"use client";

import { productLabel } from "@/lib/product-unit";

import { cn } from "@/lib/utils";
import type { OrdersByProductDto } from "../dtos/dashboard.dto";

interface OrdersByProductProps {
  data: OrdersByProductDto[];
  isLoading?: boolean;
}

function SkeletonBar() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 4 }).map((_, i) => (
        <div key={i} className="space-y-1.5">
          <div className="flex justify-between">
            <div className="h-4 w-28 animate-pulse rounded bg-gray-200" />
            <div className="h-4 w-12 animate-pulse rounded bg-gray-200" />
          </div>
          <div className="h-2 w-full animate-pulse rounded-full bg-gray-200" />
        </div>
      ))}
    </div>
  );
}

const barColors = [
  "bg-emerald-500",
  "bg-green-500",
  "bg-lime-500",
  "bg-yellow-500",
  "bg-orange-500",
];

export function OrdersByProduct({ data, isLoading = false }: OrdersByProductProps) {
  const maxQuantity = Math.max(1, ...data.map((item) => item.totalQuantity));
  const products = [...data].sort((a, b) => b.totalQuantity - a.totalQuantity);
  return (
    <div className="rounded-xl border border-gray-200/80 bg-white p-6 shadow-sm">
      <h2 className="mb-6 text-base font-semibold text-navy-900">Orders by Product</h2>

      {isLoading ? (
        <SkeletonBar />
      ) : (
        <div className="space-y-4">
          {products.map((item, index) => (
            <div key={item.productId} className="space-y-1.5">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-gray-700">
                  {productLabel(item.productName, item.defaultUnit)}
                </span>
                <span className="text-sm text-gray-500">
                  {item.totalQuantity.toLocaleString()} pcs
                </span>
              </div>
              <div className="h-2 w-full overflow-hidden rounded-full bg-gray-100">
                <div
                  className={cn(
                    "h-full rounded-full transition-all duration-500",
                    barColors[index % barColors.length]
                  )}
                  style={{ width: `${(item.totalQuantity / maxQuantity) * 100}%` }}
                />
              </div>
            </div>
          ))}
          {data.length === 0 && <p className="py-8 text-center text-sm text-gray-500">No products ordered in this date range.</p>}
        </div>
      )}
    </div>
  );
}
