import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";

type Stats = {
  total: number;
  pending: number;
  completed: number;
  returned: number;
  cancelled: number;
  total_amount: number;
  total_due: number;
};

export function CustomerOrderStats({ customerId, isBn }: { customerId: string; isBn: boolean }) {
  const { data } = useQuery({
    queryKey: ["customer-order-stats", customerId],
    queryFn: async () => {
      const { data, error } = await supabase.rpc("get_customer_order_stats" as any, { _customer_id: customerId });
      if (error) throw error;
      return (data as Stats) || null;
    },
  });

  if (!data) return null;

  const items = [
    { label: isBn ? "মোট অর্ডার" : "Total Orders", value: data.total, cls: "bg-primary/10 text-primary" },
    { label: isBn ? "অপেক্ষমাণ" : "Pending", value: data.pending, cls: "bg-yellow-500/10 text-yellow-700 dark:text-yellow-400" },
    { label: isBn ? "সম্পন্ন/ডেলিভার্ড" : "Completed", value: data.completed, cls: "bg-green-500/10 text-green-700 dark:text-green-400" },
    { label: isBn ? "ফেরত" : "Returned", value: data.returned, cls: "bg-orange-500/10 text-orange-700 dark:text-orange-400" },
    { label: isBn ? "বাতিল" : "Cancelled", value: data.cancelled, cls: "bg-red-500/10 text-red-700 dark:text-red-400" },
  ];

  return (
    <div className="mt-6 rounded-xl border border-border bg-card p-5">
      <h2 className="mb-3 text-base font-bold text-foreground">📦 {isBn ? "অর্ডার স্ট্যাটাস" : "Order Status"}</h2>
      <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
        {items.map((it) => (
          <div key={it.label} className={`rounded-lg p-3 text-center ${it.cls}`}>
            <p className="text-xs opacity-80">{it.label}</p>
            <p className="text-2xl font-bold mt-0.5">{it.value}</p>
          </div>
        ))}
      </div>
    </div>
  );
}
