"use client";

import { ProjectResult } from "@/app/api/projects";
import React, { useMemo, useState, useCallback } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import { TeamProjectResult } from "@/app/api/teamprojects";
import VisibilityIcon from '@mui/icons-material/Visibility';
import { useRouter, useSearchParams } from "next/navigation";

interface Props {
  projects: TeamProjectResult[];
}
type SearchQuery = Partial<Omit<TeamProjectResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const ProgressByClientSearch: React.FC<Props> = ({ projects }) => {
  const { t } = useTranslation("projects");
  const router = useRouter();
  // 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: "Team Code", paramName: "teamCode", type: "text" },
      { label: "Team Name", paramName: "teamName", type: "text" },
    ],
    [t],
  );

  const onTaskClick = useCallback(async (teamProjectResult: TeamProjectResult) => {
    try {
      console.log(teamProjectResult)
      router.push(
        `/dashboard/ProjectStatusByTeam?teamLeadId=${teamProjectResult.teamLeadId}`
      );
    } catch (error) {
        console.error('Error fetching team projects:', error);
    }
  }, []);


  const columns = useMemo<Column<TeamProjectResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onTaskClick,
        buttonIcon: <VisibilityIcon />,
      },
      { name: "teamCode", label: t("Team Code") },
      { name: "teamName", label: t("Team Name") },
      { name: "projectNo", label: t("No. of Projects") },
    ],
    [onTaskClick, t],
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredProjects(
            projects.filter(
              (cp) =>
                cp.teamCode.toLowerCase().includes(query.teamCode.toLowerCase()) &&
                cp.teamName.toLowerCase().includes(query.teamName.toLowerCase()) 
            ),
          );
        }}
      />
      <SearchResults<TeamProjectResult>
        items={filteredProjects}
        columns={columns}
      />
    </>
  );
};

export default ProgressByClientSearch;
