import { Breadcrumb, Button } from "antd";
import { ArrowLeftOutlined, HomeOutlined } from "@ant-design/icons";
import { Link, matchPath, useLocation, useNavigate } from "react-router-dom";
import type { ReactNode } from "react";
import { readScoreListQuery, scoresListPath } from "../scoreQueryParams";

type Crumb = { title: ReactNode; key: string };

function buildCrumbs(pathname: string, search: string): Crumb[] {
  const home: Crumb = {
    key: "home",
    title: (
      <Link to="/scores">
        <HomeOutlined style={{ marginRight: 4 }} />
        首页
      </Link>
    ),
  };

  if (matchPath("/scores", pathname)) {
    return [home, { key: "scores", title: "成绩查询" }];
  }

  if (matchPath("/attempts/:attemptId", pathname)) {
    const scoresTo = scoresListPath(readScoreListQuery(search));
    return [
      home,
      { key: "scores", title: <Link to={scoresTo}>成绩查询</Link> },
      { key: "attempt", title: "答卷详情" },
    ];
  }

  if (matchPath("/admin/import", pathname)) {
    return [home, { key: "admin-import", title: "数据导入" }];
  }

  if (matchPath("/admin/graders", pathname)) {
    return [home, { key: "admin-graders", title: "考评员管理" }];
  }

  if (matchPath("/admin/settings", pathname)) {
    return [home, { key: "admin-settings", title: "系统设置" }];
  }

  return [home];
}

export default function AppBreadcrumb() {
  const { pathname, search } = useLocation();
  const navigate = useNavigate();
  const crumbs = buildCrumbs(pathname, search);
  const onAttempt = Boolean(matchPath("/attempts/:attemptId", pathname));

  return (
    <div className="app-breadcrumb-row">
      {onAttempt && (
        <Button
          type="link"
          className="app-breadcrumb__back"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(scoresListPath(readScoreListQuery(search)))}
        >
          返回
        </Button>
      )}
      <Breadcrumb
        className="app-breadcrumb"
        items={crumbs.map((c) => ({ key: c.key, title: c.title }))}
      />
    </div>
  );
}
