"use client";

import Check from "@mui/icons-material/Check";
import Close from "@mui/icons-material/Close";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import Tab from "@mui/material/Tab";
import Tabs, { TabsProps } from "@mui/material/Tabs";
import { useRouter } from "next/navigation";
import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import ProjectClientDetails from "./ProjectClientDetails";
import TaskSetup from "./TaskSetup";
import StaffAllocation from "./StaffAllocation";
import ResourceMilestone from "./ResourceMilestone";
import { Task } from "@/app/api/tasks";
import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { CreateProjectInputs } from "@/app/api/projects/actions";
import { Error } from "@mui/icons-material";

export interface Props {
  allTasks: Task[];
}

const hasErrorsInTab = (
  tabIndex: number,
  errors: FieldErrors<CreateProjectInputs>,
) => {
  switch (tabIndex) {
    case 0:
      return errors.projectName;
    default:
      false;
  }
};

const CreateProject: React.FC<Props> = ({ allTasks }) => {
  const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation();
  const router = useRouter();

  const handleCancel = () => {
    router.back();
  };

  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );

  const onSubmit = useCallback<SubmitHandler<CreateProjectInputs>>((data) => {
    console.log(data);
  }, []);

  const onSubmitError = useCallback<SubmitErrorHandler<CreateProjectInputs>>(
    (errors) => {
      // Set the tab so that the focus will go there
      if (errors.projectName) {
        setTabIndex(0);
      }
    },
    [],
  );

  const formProps = useForm<CreateProjectInputs>({
    defaultValues: {
      tasks: {},
      allocatedStaffIds: [],
      milestones: {},
    },
  });

  const errors = formProps.formState.errors;

  return (
    <FormProvider {...formProps}>
      <Stack
        spacing={2}
        component="form"
        onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
      >
        <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
          <Tab
            label={t("Project and Client Details")}
            icon={
              hasErrorsInTab(0, errors) ? (
                <Error sx={{ marginInlineEnd: 1 }} color="error" />
              ) : undefined
            }
            iconPosition="end"
          />
          <Tab label={t("Project Task Setup")} iconPosition="end" />
          <Tab label={t("Staff Allocation")} iconPosition="end" />
          <Tab label={t("Resource and Milestone")} iconPosition="end" />
        </Tabs>
        {<ProjectClientDetails isActive={tabIndex === 0} />}
        {<TaskSetup allTasks={allTasks} isActive={tabIndex === 1} />}
        {<StaffAllocation isActive={tabIndex === 2} />}
        {<ResourceMilestone allTasks={allTasks} isActive={tabIndex === 3} />}
        <Stack direction="row" justifyContent="flex-end" gap={1}>
          <Button
            variant="outlined"
            startIcon={<Close />}
            onClick={handleCancel}
          >
            {t("Cancel")}
          </Button>
          <Button variant="contained" startIcon={<Check />} type="submit">
            {t("Confirm")}
          </Button>
        </Stack>
      </Stack>
    </FormProvider>
  );
};

export default CreateProject;
