"use client";

import { useRouter } from "next/navigation";
import type { Order } from "@/lib/api/orders";
import {
  formatOrderDateTime,
  formatOrderNumber,
  formatOrderStatus,
  formatOrderType,
  formatRupiah,
  getOrderStatusClassName,
} from "@/lib/orders/format";
import { ActionIconButton } from "../ui/button";
import { IconMoreVert } from "../ui/icons";

export type OrderTableRow = Order & {
  branchName: string;
  tableNumber: string;
  tableCategoryName: string;
  orderAdminName: string;
  cashierName: string;
};

type DaftarPesananTableProps = {
  items: OrderTableRow[];
  startIndex: number;
};

function CellStack({
  primary,
  secondary,
}: {
  primary: string;
  secondary?: string | string[] | null;
}) {
  const secondaryLines = Array.isArray(secondary)
    ? secondary.filter(Boolean)
    : secondary
      ? [secondary]
      : [];

  return (
    <div className="flex flex-col gap-0.5">
      <span className="text-m-regular text-neutral-100">{primary}</span>
      {secondaryLines.map((line) => (
        <span key={line} className="text-s-regular text-neutral-80">
          {line}
        </span>
      ))}
    </div>
  );
}

export function DaftarPesananTable({
  items,
  startIndex,
}: DaftarPesananTableProps) {
  const router = useRouter();

  return (
    <table className="min-w-[1100px] w-full border-collapse">
      <thead>
        <tr className="overflow-hidden rounded-md">
          <th className="text-m-medium w-10 bg-neutral-20 px-3 py-2 text-center text-neutral-100">
            #
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            No Pesanan
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            Waktu Pesanan
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            Tipe
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            Meja
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            Nama Customer
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            Tagihan
          </th>
          <th className="text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100">
            Status
          </th>
          <th className="w-[52px] bg-neutral-20" />
        </tr>
      </thead>
      <tbody>
        {items.length === 0 ? (
          <tr>
            <td
              colSpan={9}
              className="text-m-regular px-3 py-8 text-center text-neutral-80"
            >
              Belum ada data pesanan.
            </td>
          </tr>
        ) : (
          items.map((item, index) => {
            const tablePrimary =
              item.tableNumber !== "-" ? `Meja ${item.tableNumber}` : "-";
            const tableSecondary = [
              item.tableCategoryName !== "-"
                ? `Kategori: ${item.tableCategoryName}`
                : null,
              item.customerCount != null
                ? `Jumlah Cust: ${item.customerCount}`
                : "Jumlah Cust: -",
            ].filter((line): line is string => Boolean(line));

            return (
              <tr
                key={item.id}
                className="border-b border-neutral-20 last:border-0"
              >
                <td className="text-m-regular px-3 py-3 text-center align-top text-neutral-100">
                  {startIndex + index + 1}
                </td>
                <td className="px-3 py-3 align-top">
                  <CellStack
                    primary={formatOrderNumber(item.orderNumber)}
                    secondary={`Cabang: ${item.branchName}`}
                  />
                </td>
                <td className="px-3 py-3 align-top">
                  <CellStack
                    primary={formatOrderDateTime(item.createdAt)}
                    secondary={`Admin Pesanan: ${item.orderAdminName}`}
                  />
                </td>
                <td className="text-m-regular px-3 py-3 align-top text-neutral-100">
                  {formatOrderType(item.type)}
                </td>
                <td className="px-3 py-3 align-top">
                  <CellStack
                    primary={tablePrimary}
                    secondary={tableSecondary}
                  />
                </td>
                <td className="text-m-regular px-3 py-3 align-top text-neutral-100">
                  {item.customerName}
                </td>
                <td className="px-3 py-3 align-top">
                  <CellStack
                    primary={formatRupiah(item.grandTotal)}
                    secondary={`Item: ${item.itemCount}`}
                  />
                </td>
                <td className="px-3 py-3 align-top">
                  <div className="flex flex-col items-start gap-1">
                    <span
                      className={`text-s-medium inline-flex rounded-md px-2.5 py-0.5 ${getOrderStatusClassName(item.status)}`}
                    >
                      {formatOrderStatus(item.status)}
                    </span>
                    <span className="text-s-regular text-neutral-80">
                      Kasir: {item.cashierName}
                    </span>
                  </div>
                </td>
                <td className="px-3 py-3 align-top">
                  <div className="flex items-center justify-center">
                    <ActionIconButton
                      icon={<IconMoreVert className="size-4" />}
                      onClick={() =>
                        router.push(`/daftar-pesanan/${item.id}`)
                      }
                      aria-label={`Lihat detail pesanan ${formatOrderNumber(item.orderNumber)}`}
                    />
                  </div>
                </td>
              </tr>
            );
          })
        )}
      </tbody>
    </table>
  );
}
