import type { DiningTable } from "@/lib/api/dining-tables";
import type { DiningTableStatusTogglePayload } from "@/lib/query/hooks/dining-tables";
import { formatTableNumberForDisplay } from "./semua-meja-form-modal";
import { MaterialIcon } from "../icons/nav-icons";
import { ActionIconButton } from "../ui/button";

export type SemuaMejaTableRow = {
  item: DiningTable;
  categoryName: string;
  branchName: string;
};

type SemuaMejaTableProps = {
  items: SemuaMejaTableRow[];
  startIndex: number;
  onEdit: (id: number) => void;
  onDelete: (item: SemuaMejaTableRow) => void;
  onToggleVisible: (payload: DiningTableStatusTogglePayload) => void;
};

const headerCellClass =
  "text-m-medium bg-neutral-20 px-3 py-2 text-left text-neutral-100";

const bodyCellClass = "text-m-regular px-3 py-2 align-middle text-neutral-100";

function ActiveSwitch({
  active,
  onChange,
}: {
  active: boolean;
  onChange: (value: boolean) => void;
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={active}
      onClick={() => onChange(!active)}
      className={`relative h-[21px] w-[38px] shrink-0 rounded-full transition-colors ${
        active ? "bg-primary-500" : "bg-neutral-40"
      }`}
    >
      <span
        className={`absolute top-[2px] size-[17px] rounded-full bg-neutral-10 transition-transform ${
          active ? "left-[19px]" : "left-[2px]"
        }`}
      />
    </button>
  );
}

export function isTableVisible(status: string) {
  const normalized = status.toLowerCase();
  return normalized !== "inactive" && normalized !== "nonaktif";
}

export function SemuaMejaTable({
  items,
  startIndex,
  onEdit,
  onDelete,
  onToggleVisible,
}: SemuaMejaTableProps) {
  const columnCount = 6;

  return (
    <table className="min-w-[977px] w-full border-collapse">
      <thead>
        <tr className="overflow-hidden rounded-md">
          <th className={`${headerCellClass} w-10 text-center`}>#</th>
          <th className={headerCellClass}>No Meja</th>
          <th className={headerCellClass}>Kategori</th>
          <th className={headerCellClass}>Tersedia di Cabang</th>
          <th className={headerCellClass}>Tampilkan Meja</th>
          <th className="w-[84px] bg-neutral-20" />
        </tr>
      </thead>
      <tbody>
        {items.length === 0 ? (
          <tr>
            <td
              colSpan={columnCount}
              className="text-m-regular px-3 py-8 text-center text-neutral-80"
            >
              Belum ada data meja.
            </td>
          </tr>
        ) : (
          items.map((row, index) => {
            const active = isTableVisible(row.item.status);
            const branchId = row.item.branchId;

            return (
              <tr
                key={row.item.id}
                className="border-b border-neutral-20 last:border-0"
              >
                <td className={`${bodyCellClass} text-center`}>
                  {startIndex + index + 1}
                </td>
                <td className={bodyCellClass}>
                  {formatTableNumberForDisplay(row.item.tableNumber)}
                </td>
                <td className={`${bodyCellClass} uppercase`}>
                  {row.categoryName}
                </td>
                <td className={bodyCellClass}>
                  {row.branchName !== "-" ? (
                    <p className="text-m-medium uppercase text-neutral-100">
                      {row.branchName}
                    </p>
                  ) : (
                    <span className="text-m-regular text-neutral-70">-</span>
                  )}
                </td>
                <td className={bodyCellClass}>
                  <div className="flex items-center gap-2">
                    <ActiveSwitch
                      active={active}
                      onChange={(isVisible) =>
                        onToggleVisible({
                          id: row.item.id,
                          branchId: branchId ?? 0,
                          status: isVisible ? "active" : "inactive",
                        })
                      }
                    />
                    <span className="text-m-regular text-neutral-100">
                      {active ? "Aktif" : "Nonaktif"}
                    </span>
                  </div>
                </td>
                <td className="px-3 py-2">
                  <div className="flex items-center justify-center gap-1">
                    <ActionIconButton
                      variant="danger"
                      onClick={() => onDelete(row)}
                      aria-label={`Hapus meja ${formatTableNumberForDisplay(row.item.tableNumber)}`}
                      icon={<MaterialIcon name="delete" size={16} />}
                    />
                    <ActionIconButton
                      onClick={() => onEdit(row.item.id)}
                      aria-label={`Edit meja ${formatTableNumberForDisplay(row.item.tableNumber)}`}
                      icon={<MaterialIcon name="edit" size={16} />}
                    />
                  </div>
                </td>
              </tr>
            );
          })
        )}
      </tbody>
    </table>
  );
}
