import { useMemo } from "react";
import {
  RiBox3Line,
  RiCheckboxCircleLine,
  RiCloseCircleLine,
  RiIndeterminateCircleLine,
  RiTimeLine,
  RiTruckLine,
} from "@remixicon/react";
import { StatCard } from "./stat-card";
import { formatNumber, formatCurrency } from "../lib/format-utils";
import type { Order, OrderStatus } from "../types";

interface OrderSummaryCardsProps {
  orders: Order[];
}

/**
 * KPI row for the orders page. Each card reflects the currently
 * filtered order set so the numbers stay in sync with the table.
 */
export function OrderSummaryCards({ orders }: OrderSummaryCardsProps) {
  const stats = useMemo(() => {
    const byStatus = (status: OrderStatus) =>
      orders.filter((o) => o.status === status);

    return {
      total: orders.length,
      totalRevenue: orders
        .filter((o) => o.status !== "cancelled")
        .reduce((sum, o) => sum + o.grandTotal, 0),
      pending: byStatus("pending").length,
      processing: byStatus("processing").length,
      shipped: byStatus("shipped").length,
      delivered: byStatus("delivered").length,
      cancelled: byStatus("cancelled").length,
    };
  }, [orders]);

  return (
    <div className="grid gap-4 grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
      <StatCard
        title="Total Orders"
        value={formatNumber(stats.total)}
        change={`${formatCurrency(stats.totalRevenue)}`}
        changeType="neutral"
        icon={RiIndeterminateCircleLine}
        subLabel="total revenue"
      />
      <StatCard
        title="Pending"
        value={formatNumber(stats.pending)}
        changeType="neutral"
        icon={RiTimeLine}
      />
      <StatCard
        title="Processing"
        value={formatNumber(stats.processing)}
        changeType="neutral"
        icon={RiBox3Line}
      />
      <StatCard
        title="Shipped"
        value={formatNumber(stats.shipped)}
        changeType="neutral"
        icon={RiTruckLine}
      />
      <StatCard
        title="Delivered"
        value={formatNumber(stats.delivered)}
        changeType="neutral"
        icon={RiCheckboxCircleLine}
      />
      <StatCard
        title="Cancelled"
        value={formatNumber(stats.cancelled)}
        changeType="neutral"
        icon={RiCloseCircleLine}
      />
    </div>
  );
}