import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useOrders } from "@/hooks/useOrders";
import { Order } from "src/db";
import ErrorMessage from "./ErrorPage";
import LoadingPage from "./Loading";

function StatItem({ title, value }: { title: string; value: string }) {
  return (
    <div className="flex flex-col">
      <p className="text-muted-foreground text-sm">{title}</p>
      <p className="text-lg">{value}</p>
    </div>
  );
}

function sum(...args: number[]) {
  return args.reduce((acc, cur) => acc + cur, 0);
}

function ordersSum(orders: Order[]) {
  return orders.reduce((acc, cur) => acc + cur.price * cur.quantity * 1000, 0);
}

export default function Stat() {
  const { data: orders, status } = useOrders();

  if (status === "pending") {
    return <LoadingPage />;
  }
  if (!orders) {
    return <ErrorMessage>주문을 불러오지 못했습니다.</ErrorMessage>;
  }

  const completed_order = orders.filter(order => order.completed);
  const cash_order = completed_order.filter(order => order.payment === "cash");
  const account_order = completed_order.filter(order => order.payment === "account");
  return (
    <Card className="w-[300px] m-auto">
      <CardHeader>
        <CardTitle>주문통계</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-2">
          <StatItem title="총 주문 수" value={orders.length.toString()} />
          <StatItem title="완료된 주문 수" value={completed_order.length.toString()} />
          <StatItem title="현금 결제 주문 수" value={cash_order.length.toString()} />
          <StatItem title="계좌 이체 주문 수" value={account_order.length.toString()} />
        </div>
        <hr className="my-2" />
        <div className="grid grid-cols-2">
          <StatItem
            title="총 매출"
            value={sum(...completed_order.map(order => ordersSum(order.orders)))
              .toLocaleString("ko-KR", {
                style: "currency",
                currency: "KRW",
              })}
          />
          <StatItem
            title="현금 매출"
            value={sum(...cash_order.map(order => ordersSum(order.orders)))
              .toLocaleString("ko-KR", {
                style: "currency",
                currency: "KRW",
              })}
          />
          <StatItem
            title="계좌 매출"
            value={sum(...account_order.map(order => ordersSum(order.orders)))
              .toLocaleString("ko-KR", {
                style: "currency",
                currency: "KRW",
              })}
          />
        </div>
      </CardContent>
    </Card>
  );
}
