import { useMemo } from "react";
import { Space } from "tdesign-react";

import type { TargetStatus } from "../../shared/api";

import { createTargetTableColumns } from "../constants/target-table-columns";
import { useMeta } from "../hooks/use-queries";
import { TargetGroup } from "./TargetGroup";

const EMPTY_CHECKER_TYPES: string[] = [];

interface TargetBoardProps {
  onTargetClick: (target: TargetStatus) => void;
  targets: TargetStatus[];
}

export function TargetBoard({ onTargetClick, targets }: TargetBoardProps) {
  const { data: meta } = useMeta();
  const checkerTypes = meta?.checkerTypes ?? EMPTY_CHECKER_TYPES;
  const columns = useMemo(() => createTargetTableColumns(checkerTypes), [checkerTypes]);

  const sortedGroups = useMemo(() => {
    const groups = new Map<string, TargetStatus[]>();
    for (const target of targets) {
      const group = target.group;
      const list = groups.get(group);
      if (list) {
        list.push(target);
      } else {
        groups.set(group, [target]);
      }
    }
    return Array.from(groups.entries()).sort(([a]) => {
      if (a === "default") return -1;
      return 0;
    });
  }, [targets]);

  return (
    <Space className="full-width" direction="vertical" size={24}>
      {sortedGroups.map(([name, groupTargets]) => (
        <TargetGroup columns={columns} key={name} name={name} onTargetClick={onTargetClick} targets={groupTargets} />
      ))}
    </Space>
  );
}
