"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";
import Typography from "@mui/material/Typography";

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

const ProgressByClientSearch: React.FC<Props> = ({ projects }) => {
  const { t } = useTranslation("dashboard");
  const router = useRouter();
  // If project searching is done on the server-side, then no need for this.
  // const [filteredProjects, setFilteredProjects] = useState(projects);

  const projectCombo = projects.map(project => ({
    value: project.teamLeadId,
    label: `${project.teamCode} ${project.teamName ? '- ' + project.teamName : ''} (${project.projectNo})`
  }))

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { 
        label: t("Team"), 
        paramName: "teamLeadId",
        type: "autocomplete",
        options: projectCombo,
        needAll: false 
      },
    ],
    [t],
  );

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

  return (
    <>
      <Typography variant="h4" marginInlineEnd={2}>
        {t("Project Status by Team")}
      </Typography>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          console.log(query)
          onTaskClick({
            ...query,
            teamLeadId: Number(query.teamLeadId),
            teamId: Number(query.teamId),
            id: Number(query.teamId),
            projectNo: Number(query.projectNo)
          })
        }}
      />
    </>
  );
};

export default ProgressByClientSearch;
