"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,
  Grid,
  InputLabel,
  MenuItem,
  Select,
  SelectChangeEvent,
  Stack,
} from "@mui/material";
import { Task, TaskGroup } from "@/app/api/tasks";
import uniqBy from "lodash/uniqBy";
import { moneyFormatter } from "@/app/utils/formatUtil";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";

interface Props {
  tasks: Task[];
}

const ResourceMilestone: React.FC<Props> = ({ tasks }) => {
  const { t } = useTranslation();

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

  return (
    <>
      <Card>
        <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
          <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>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {t("Resource")}
          </Typography>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {t("Milestone")}
          </Typography>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
              <Grid item xs>
                <FormControl fullWidth>
                  <DatePicker
                    label={t("Stage Start Date")}
                    defaultValue={dayjs()}
                  />
                </FormControl>
              </Grid>
              <Grid item xs>
                <FormControl fullWidth>
                  <DatePicker
                    label={t("Stage End Date")}
                    defaultValue={dayjs()}
                  />
                </FormControl>
              </Grid>
            </Grid>
          </LocalizationProvider>
          <CardActions sx={{ justifyContent: "flex-end" }}>
            <Button variant="text" startIcon={<RestartAlt />}>
              {t("Reset")}
            </Button>
          </CardActions>
        </CardContent>
      </Card>
      <Card>
        <CardContent>
          <Stack direction="row" justifyContent="space-between">
            <Typography variant="h6">{t("Project Total Fee")}</Typography>
            <Typography>{moneyFormatter.format(80000)}</Typography>
          </Stack>
        </CardContent>
      </Card>
    </>
  );
};

const NoTaskState: React.FC = () => {
  const { t } = useTranslation();
  return (
    <Card>
      <CardContent>
        <Alert severity="error">
          {t('Please add some tasks in "Project Task Setup" first!')}
        </Alert>
      </CardContent>
    </Card>
  );
};

const ResourceMilestoneWrapper: React.FC<Props> = (props) => {
  if (props.tasks.length === 0) {
    return <NoTaskState />;
  }

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

export default ResourceMilestoneWrapper;
