"use client";

import { 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";

interface Props {
  projects: ProjectResult[];
}

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

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

  // If project searching is done on the server-side, then no need for this.
  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: ["Client A", "Client B", "Client C"],
      },
      {
        label: t("Project category"),
        paramName: "category",
        type: "select",
        options: ["Confirmed Project", "Project to be bidded"],
      },
      {
        label: t("Team"),
        paramName: "team",
        type: "select",
        options: ["TW", "WY"],
      },
    ],
    [t],
  );

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

  const onProjectClick = useCallback((project: ProjectResult) => {
    console.log(project);
  }, []);

  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") },
    ],
    [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),
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<ProjectResult>
        items={filteredProjects}
        columns={columns}
      />
    </>
  );
};

export default ProjectSearch;
