"use client";

import { ProjectCategory, ProjectResult } from "@/app/api/projects";
import React, { useCallback, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import EditNote from "@mui/icons-material/EditNote";
import uniq from "lodash/uniq";
import { useRouter } from "next/navigation";

interface Props {
  projects: ProjectResult[];
  projectCategories: ProjectCategory[];
}

type SearchQuery = Partial<Omit<ProjectResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const ProjectSearch: React.FC<Props> = ({ projects, projectCategories }) => {
  const router = useRouter();
  const { t } = useTranslation("projects");

  const [filteredProjects, setFilteredProjects] = useState(projects);

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Project code"), paramName: "code", type: "text" },
      { label: t("Project name"), paramName: "name", type: "text" },
      {
        label: t("Client name"),
        paramName: "client",
        type: "select",
        options: uniq(projects.map((project) => project.client)),
      },
      {
        label: t("Project category"),
        paramName: "category",
        type: "select",
        options: projectCategories.map((category) => category.name),
      },
      {
        label: t("Team"),
        paramName: "team",
        type: "select",
        options: uniq(projects.map((project) => project.team)),
      },
      {
        label: t("Status"),
        paramName: "status",
        type: "select",
        options: uniq(projects.map((project) => project.status)),
      },
    ],
    [t, projectCategories, projects],
  );

  const onReset = useCallback(() => {
    setFilteredProjects(projects);
  }, [projects]);

  const onProjectClick = useCallback(
    (project: ProjectResult) => {
      if (Boolean(project.mainProject)) {
        router.push(`/projects/editSub?id=${project.id}`);
      } else router.push(`/projects/edit?id=${project.id}`);
    },
    [router],
  );

  const columns = useMemo<Column<ProjectResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onProjectClick,
        buttonIcon: <EditNote />,
      },
      { name: "code", label: t("Project Code") },
      { name: "name", label: t("Project Name") },
      { name: "category", label: t("Project Category") },
      { name: "team", label: t("Team") },
      { name: "client", label: t("Client") },
      { name: "status", label: t("Status") },
    ],
    [t, onProjectClick],
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredProjects(
            projects.filter(
              (p) =>
                p.code.toLowerCase().includes(query.code.toLowerCase()) &&
                p.name.toLowerCase().includes(query.name.toLowerCase()) &&
                (query.client === "All" || p.client === query.client) &&
                (query.category === "All" || p.category === query.category) &&
                (query.team === "All" || p.team === query.team) &&
                (query.status === "All" || p.status === query.status),
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<ProjectResult>
        items={filteredProjects}
        columns={columns}
      />
    </>
  );
};

export default ProjectSearch;
