"use client";

import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import { useTranslation } from "react-i18next";
import Button from "@mui/material/Button";
import React, { SyntheticEvent, useCallback, useEffect, useMemo, useState } from "react";
import CardActions from "@mui/material/CardActions";
import RestartAlt from "@mui/icons-material/RestartAlt";
import {
  Alert,
  Autocomplete,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  SelectChangeEvent,
  TextField,
} 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 ProjectTotalFee from "./ProjectTotalFee";
import { sumMoney } from "@/app/utils/formatUtil";

export interface Props {
  allTasks: Task[];
  isActive: boolean;
}

const Milestone: React.FC<Props> = ({ allTasks, isActive }) => {
  const { t } = useTranslation();
  const { watch, setError, clearErrors } = useFormContext<CreateProjectInputs>();
  const currentTaskGroups = watch("taskGroups");
  const taskGroups = useMemo(
    () =>
      uniqBy(
        allTasks.reduce<TaskGroup[]>((acc, task) => {
          if (currentTaskGroups[task.taskGroup.id]) {
            return [...acc, task.taskGroup];
          }
          return acc;
        }, []),
        "id",
      ),
    [allTasks, currentTaskGroups],
  );

  const [currentTaskGroupId, setCurrentTaskGroupId] = useState(
    taskGroups[0].id
  );

  useEffect(() => {
    if (taskGroups.length >= 0 && !taskGroups.map(taskGroup => taskGroup.id).includes(currentTaskGroupId)) setCurrentTaskGroupId(taskGroups[0].id)
  }, [taskGroups])

  /*const onSelectTaskGroup = useCallback(
    (event: SelectChangeEvent<TaskGroup["id"]>) => {
      const id = event.target.value;
      const newTaksGroupId = typeof id === "string" ? parseInt(id) : id;
      setCurrentTaskGroupId(newTaksGroupId);
    },
    [],
  );*/

  const onSelectTaskGroup = useCallback(
    (event: SyntheticEvent<Element, Event>, value: NonNullable<TaskGroup>) => {
      const id = value.id;
      const newTaksGroupId = typeof id === "string" ? parseInt(id) : id;
      setCurrentTaskGroupId(newTaksGroupId);
    },
    [],
  );

  // handle error checking
  const milestones = watch("milestones")
  const expectedTotalFee = watch("expectedProjectFee");
  useEffect(() => {
    const taskGroupsIds = taskGroups.map(taskGroup => taskGroup.id.toString())
    const milestonesKeys = Object.keys(milestones).filter(key => taskGroupsIds.includes(key))
    let hasError = false
    let projectTotal = 0

    milestonesKeys.forEach(key => {
      const { startDate, endDate, payments } = milestones[parseFloat(key)]

      // if (new Date(startDate) > new Date(endDate) || !Boolean(startDate) || !Boolean(endDate)) {
      //   hasError = true
      // }

      // projectTotal += payments.reduce((acc, payment) => acc + payment.amount, 0)
      projectTotal += payments.reduce(
        (acc, p) => sumMoney(acc, p.amount),
        0,
      );

    })
    console.log(milestonesKeys)

    // if (projectTotal !== expectedTotalFee || milestonesKeys.length !== taskGroupsIds.length) {
    if (projectTotal !== expectedTotalFee) {
      hasError = true
    }
    // console.log(Object.keys(milestones).reduce((acc, key) => acc + milestones[parseFloat(key)].payments.reduce((acc2, value) => acc2 + value.amount, 0), 0))
    if (hasError) {
      setError("milestones", { message: "milestones is not valid", type: "invalid" })
    } else {
      clearErrors("milestones")
    }
  }, [milestones])

  return (
    <>
      <Card sx={{ display: isActive ? "block" : "none" }}>
        <CardContent sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
          <FormControl>
            <Autocomplete
              disableClearable
              // disablePortal
              noOptionsText={t("No Task Stage")}
              value={taskGroups.find(taskGroup => taskGroup.id === currentTaskGroupId)}
              options={taskGroups}
              getOptionLabel={(taskGroup) => taskGroup.name}
              isOptionEqualToValue={(option, value) => option.id === value?.id}
              renderOption={(params, option) => {
                return (
                  <MenuItem {...params} key={option.id} value={option.id}>
                    {option.name}
                  </MenuItem>
                );
              }}
              onChange={onSelectTaskGroup}
              renderInput={(params) => <TextField {...params} variant="outlined" label={t("Task Stage")} />}
            />
          </FormControl>
          {/* MUI X-Grid will throw an error if it is rendered without any dimensions; so not rendering when not active */}
          {isActive && <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 MilestoneWrapper: React.FC<Props> = (props) => {
  const { getValues } = useFormContext<CreateProjectInputs>();

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

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

export default MilestoneWrapper;
