"use client";

import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import { useTranslation } from "react-i18next";
import Button from "@mui/material/Button";
import React, { useCallback, useMemo, useState } from "react";
import CardActions from "@mui/material/CardActions";
import RestartAlt from "@mui/icons-material/RestartAlt";
import {
  Alert,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  SelectChangeEvent,
} from "@mui/material";
import { Task, TaskGroup } from "@/app/api/tasks";
import uniqBy from "lodash/uniqBy";
import { useFormContext } from "react-hook-form";
import { CreateProjectInputs } from "@/app/api/projects/actions";
import MilestoneSection from "./MilestoneSection";
import ResourceSection from "./ResourceSection";
import ProjectTotalFee from "./ProjectTotalFee";

export interface Props {
  allTasks: Task[];
  defaultManhourBreakdownByGrade?: { [gradeId: number]: number };
  isActive: boolean;
}

const ResourceMilestone: React.FC<Props> = ({
  allTasks,
  defaultManhourBreakdownByGrade,
  isActive,
}) => {
  const { t } = useTranslation();
  const { getValues } = useFormContext<CreateProjectInputs>();
  const tasks = useMemo(() => {
    return allTasks.filter((task) => getValues("tasks")[task.id]);
  }, [allTasks, getValues]);

  const taskGroups = useMemo(() => {
    return uniqBy(
      tasks.map((task) => task.taskGroup),
      "id",
    );
  }, [tasks]);
  const [currentTaskGroupId, setCurrentTaskGroupId] = useState(
    taskGroups[0].id,
  );
  const [currentTasks, setCurrentTasks] = useState<typeof tasks>(
    tasks.filter((t) => t.taskGroup.id === currentTaskGroupId),
  );
  const onSelectTaskGroup = useCallback(
    (event: SelectChangeEvent<TaskGroup["id"]>) => {
      const id = event.target.value;
      const newTaksGroupId = typeof id === "string" ? parseInt(id) : id;
      setCurrentTaskGroupId(newTaksGroupId);
      setCurrentTasks(tasks.filter((t) => t.taskGroup.id === newTaksGroupId));
    },
    [tasks],
  );

  return (
    <>
      <Card sx={{ display: isActive ? "block" : "none" }}>
        <CardContent sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
          <FormControl>
            <InputLabel>{t("Task Stage")}</InputLabel>
            <Select
              label={t("Task Stage")}
              onChange={onSelectTaskGroup}
              value={currentTaskGroupId}
            >
              {taskGroups.map((taskGroup) => (
                <MenuItem key={taskGroup.id} value={taskGroup.id}>
                  {taskGroup.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <ResourceSection
            tasks={currentTasks}
            manhourBreakdownByGrade={defaultManhourBreakdownByGrade}
          />
          <MilestoneSection taskGroupId={currentTaskGroupId} />
          <CardActions sx={{ justifyContent: "flex-end" }}>
            <Button variant="text" startIcon={<RestartAlt />}>
              {t("Reset")}
            </Button>
          </CardActions>
        </CardContent>
      </Card>
      <Card sx={{ display: isActive ? "block" : "none" }}>
        <CardContent>
          <ProjectTotalFee taskGroups={taskGroups} />
        </CardContent>
      </Card>
    </>
  );
};

const NoTaskState: React.FC<Pick<Props, "isActive">> = ({ isActive }) => {
  const { t } = useTranslation();
  return (
    <Card sx={{ display: isActive ? "block" : "none" }}>
      <CardContent>
        <Alert severity="warning">
          {t('Please add some tasks in "Project Task Setup" first!')}
        </Alert>
      </CardContent>
    </Card>
  );
};

const ResourceMilestoneWrapper: React.FC<Props> = (props) => {
  const { getValues } = useFormContext<CreateProjectInputs>();

  if (Object.keys(getValues("tasks")).length === 0) {
    return <NoTaskState isActive={props.isActive} />;
  }

  return <ResourceMilestone {...props} />;
};

export default ResourceMilestoneWrapper;
