/* eslint-disable react-hooks/exhaustive-deps */
import clsx from "clsx";
import { useEffect, useState } from "react";
import Project from "../types/Project";
import Select from "./ui/Select";

function ProjectSelect<T extends boolean = false>({
  projects,
  onSelect,
  defaultProject,
  withAll,
}: {
  projects: Project[];
  onSelect: (project: Project | null) => void;
  defaultProject: T extends false ? Project : null;
  withAll?: T;
}) {
  const [selectedProject, setSelectedProject] = useState<Project | null>(
    defaultProject
  );

  useEffect(() => setSelectedProject(defaultProject), [defaultProject]);

  useEffect(() => onSelect(selectedProject), [selectedProject]);

  return (
    <>
      <div className="flex 2xl:gap-[0.556vw] gap-2 max-md:hidden">
        {withAll && (
          <div
            className={clsx(
              "2xl:rounded-[2.778vw] rounded-[40px] 2xl:py-[0.972vw] 2xl:px-[1.389vw] md:max-2xl:px-5 md:max-2xl:py-3.5 text-s 2xl:ring-[0.069vw] ring transition-[box-shadow] cursor-pointer",
              !selectedProject ? "ring-[#00BED7]" : "ring-[#E2E2DC]"
            )}
            onClick={() => setSelectedProject(null)}
          >
            All Projects
          </div>
        )}
        {projects.map((project) => (
          <div
            key={project.title}
            className={clsx(
              "2xl:rounded-[2.778vw] rounded-[40px] 2xl:p-[0.278vw] p-1 flex items-center 2xl:gap-[0.556vw] gap-2 text-s 2xl:ring-[0.069vw] ring transition-[box-shadow] cursor-pointer",
              selectedProject && project.title === selectedProject.title
                ? "ring-[#00BED7]"
                : "ring-[#E2E2DC]"
            )}
            onClick={() => setSelectedProject(project)}
          >
            <img
              src={project.img}
              alt={project.title}
              className="object-cover 2xl:w-[2.778vw] w-10 aspect-square rounded-full"
            />
            <p
              className={clsx(
                "2xl:mr-[1.111vw] mr-6",
                selectedProject &&
                  selectedProject.title !== project.title &&
                  "text-[#0D1922]/70"
              )}
            >
              {project.title}
            </p>
          </div>
        ))}
      </div>
      <Select
        options={[
          ...(withAll ? ["All"] : []),
          ...projects.map((project) => project.title),
        ]}
        onSelect={(option) =>
          setSelectedProject(
            projects.find((project) => project.title === option) ||
              defaultProject
          )
        }
        defaultOption={defaultProject ? defaultProject.title : "All"}
        className="md:hidden"
      />
    </>
  );
}

export default ProjectSelect;
