|
- "use client";
- import { useRouter, useSearchParams } from "next/navigation";
- import { useCallback, useEffect, useMemo, useState } from "react";
- import SearchResults, { Column } from "../SearchResults";
- // import { TeamResult } from "@/app/api/team";
- import { useTranslation } from "react-i18next";
- import { Button, Stack, Tab, Tabs, TabsProps, Typography } from "@mui/material";
- import { CreateTeamInputs, saveTeam } from "@/app/api/team/actions";
- import {
- FieldErrors,
- FormProvider,
- SubmitHandler,
- useForm,
- useFormContext,
- } from "react-hook-form";
- import { Check, Close, Error } from "@mui/icons-material";
- import TeamInfo from "../EditTeam/TeamInfo";
- import Allocation from "./Allocation";
- import { StaffResult } from "@/app/api/staff";
-
- interface desc {
- id: number;
- name: string;
- description: string;
- teamLead: number;
- }
-
- interface Props {
- staff: StaffResult[];
- desc: desc[];
- // teamLead: StaffResult[]
- }
-
- const EditTeam: React.FC<Props> = async ({ staff, desc }) => {
- // console.log(desc)
- const { t } = useTranslation();
- const formProps = useForm<CreateTeamInputs>();
- const searchParams = useSearchParams();
- const idString = searchParams.get("id");
- const [filteredItems, setFilteredItems] = useState<StaffResult[]>();
- const [allStaffs, setAllStaffs] = useState<StaffResult[]>();
- const [filteredDesc, setFilteredDesc] = useState<string>();
- const [filteredName, setFilteredName] = useState<string>();
- const [teamLead, setTeamLead] = useState<number>();
- const [tabIndex, setTabIndex] = useState(0);
- const router = useRouter();
- // const [selectedStaff, setSelectedStaff] = useState<typeof filteredItems>(
- // initialStaffs.filter((s) => getValues("addStaffIds")?.includes(s.id))
- // );
-
- const errors = formProps.formState.errors;
-
- const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
- (_e, newValue) => {
- setTabIndex(newValue);
- },
- []
- );
-
- const [serverError, setServerError] = useState("");
- const cols = useMemo<Column<StaffResult>[]>(
- () => [
- { label: t("Staff Id"), name: "staffId" },
- { label: t("Name"), name: "staffName" },
- // { label: t("Current Position"), name: "posCode" },
- ],
- [t]
- );
- useEffect(() => {
- let idList: number[] = []
- console.log(desc)
- if (idString) {
- const filteredTeam = staff.filter(
- (item) => {
- console.log(item)
- console.log(parseInt(idString))
- return (item.teamId === parseInt(idString))}
- );
- console.log(filteredTeam)
- const tempDesc = desc.filter(
- (item) => item.id === parseInt(idString)
- )
- // const leader = teamLead.filter(
- // (staff) => staff.teamId === parseInt(idString)
- // )
- // console.log(leader)
- console.log(tempDesc[0].teamLead)
- setTeamLead(tempDesc[0].teamLead)
- if (filteredTeam.length > 0) {
- const filteredIds: number[] = filteredTeam.map((i) => (
- i.id
- ))
-
- // const teamLead = tempDesc[0].teamLead
- // const index = filteredIds.indexOf(teamLead);
-
- // if (index !== -1) {
- // filteredIds.splice(index, 1);
- // filteredIds.unshift(teamLead);
- // }
-
- idList = filteredIds
- console.log(filteredIds)
- }
- console.log(idList)
- setFilteredItems(filteredTeam);
- formProps.reset({description: tempDesc[0].description, addStaffIds: idList})
- setFilteredDesc(tempDesc[0].description)
- setFilteredName(tempDesc[0].name)
- }
- console.log(staff)
-
- setAllStaffs(staff)
-
- }, [searchParams]);
-
- // useEffect(() => {
- // console.log(allStaffs)
- // }, [allStaffs]);
-
- const hasErrorsInTab = (
- tabIndex: number,
- errors: FieldErrors<CreateTeamInputs>
- ) => {
- switch (tabIndex) {
- case 0:
- return Object.keys(errors).length > 0;
- default:
- false;
- }
- };
-
- const onSubmit = useCallback<SubmitHandler<CreateTeamInputs>>(
- async (data) => {
- try {
- console.log(data);
- const tempData = {
- description: data.description,
- addStaffIds: data.addStaffIds,
- deleteStaffIds: data.deleteStaffIds,
- id: parseInt(idString!!)
- }
- console.log(tempData)
- await saveTeam(tempData);
- router.replace("/settings/team");
- } catch (e) {
- console.log(e);
- setServerError(t("An error has occurred. Please try again later."));
- }
- },
- [router]
- );
-
- return (
- <>
- {serverError && (
- <Typography variant="body2" color="error" alignSelf="flex-end">
- {serverError}
- </Typography>
- )}
- <FormProvider {...formProps}>
- <Stack
- spacing={2}
- component="form"
- onSubmit={formProps.handleSubmit(onSubmit)}
- >
-
- <Typography variant="h4" marginInlineEnd={2}>
- {t("Edit Team")} - {filteredName}
- </Typography>
- <Stack
- direction="row"
- justifyContent="space-between"
- flexWrap="wrap"
- rowGap={2}
- >
- <Tabs
- value={tabIndex}
- onChange={handleTabChange}
- variant="scrollable"
- >
- <Tab
- label={t("Team Info")}
- icon={
- hasErrorsInTab(0, errors) ? (
- <Error sx={{ marginInlineEnd: 1 }} color="error" />
- ) : undefined
- }
- iconPosition="end"
- />
- <Tab label={t("Staff Allocation")} iconPosition="end" />
- </Tabs>
- </Stack>
- {tabIndex === 0 && <TeamInfo value={filteredDesc!!} />}
- {tabIndex === 1 && <Allocation allStaffs={allStaffs!!} teamLead={teamLead!!}/>}
- <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"
- // disabled={Boolean(formProps.watch("isGridEditing"))}
- >
- {t("Confirm")}
- </Button>
- </Stack>
- </Stack>
- </FormProvider>
- </>
- );
- };
- export default EditTeam;
|