import React, { useCallback } from "react";
import { MenuItem, Select, SelectChangeEvent } from "@mui/material";
import { useTranslation } from "react-i18next";
import { ProjectWithTasks } from "@/app/api/projects";
import { Task } from "@/app/api/tasks";

interface Props {
  allProjects: ProjectWithTasks[];
  value: number | undefined;
  projectId: number | undefined;
  taskGroupId: number | undefined;
  onTaskSelect: (taskId: number | string) => void;
  error?: boolean;
  miscTasks?: Task[];
}

const TaskSelect: React.FC<Props> = ({
  value,
  allProjects,
  projectId,
  taskGroupId,
  onTaskSelect,
  error,
  miscTasks,
}) => {
  const { t } = useTranslation("home");

  const project = allProjects.find((p) => p.id === projectId);
  const tasks = (project ? project.tasks : miscTasks || []).filter(
    (task) => task.taskGroup.id === taskGroupId,
  );

  const onChange = useCallback(
    (event: SelectChangeEvent<number>) => {
      const newValue = event.target.value;
      onTaskSelect(newValue);
    },
    [onTaskSelect],
  );

  return (
    <Select
      error={error}
      displayEmpty
      disabled={tasks.length === 0}
      value={value || ""}
      onChange={onChange}
      sx={{ width: "100%" }}
      MenuProps={{
        slotProps: {
          paper: {
            sx: { maxHeight: 400 },
          },
        },
        anchorOrigin: {
          vertical: "bottom",
          horizontal: "left",
        },
        transformOrigin: {
          vertical: "top",
          horizontal: "left",
        },
      }}
    >
      {tasks.length === 0 && <MenuItem value={""}>{t("None")}</MenuItem>}
      {tasks.map((task) => (
        <MenuItem key={task.id} value={task.id} sx={{ whiteSpace: "wrap" }}>
          {task.name}
        </MenuItem>
      ))}
    </Select>
  );
};

export default TaskSelect;
