"use client";

import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Grid from "@mui/material/Grid";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useTranslation } from "react-i18next";
import TransferList from "../TransferList";
import Button from "@mui/material/Button";
import Check from "@mui/icons-material/Check";
import Close from "@mui/icons-material/Close";
import { useRouter } from "next/navigation";
import React from "react";
import Stack from "@mui/material/Stack";
import { Task } from "@/app/api/tasks";
import {
  NewTaskTemplateFormInputs,
  saveTaskTemplate,
} from "@/app/api/tasks/actions";
import { SubmitHandler, useForm } from "react-hook-form";

interface Props {
  tasks: Task[];
}

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

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

  const items = React.useMemo(
    () =>
      tasks.map((task) => ({
        id: task.id,
        label: task.name,
        group: task.taskGroup || undefined,
      })),
    [tasks],
  );

  const [serverError, setServerError] = React.useState("");

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors, isSubmitting },
  } = useForm<NewTaskTemplateFormInputs>();

  const onSubmit: SubmitHandler<NewTaskTemplateFormInputs> = React.useCallback(
    async (data) => {
      try {
        setServerError("");
        await saveTaskTemplate(data);
        router.replace("/tasks");
      } catch (e) {
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router, t],
  );

  return (
    <Stack component="form" onSubmit={handleSubmit(onSubmit)} gap={2}>
      <Card>
        <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
          <Typography variant="overline">{t("Task List Setup")}</Typography>
          <Grid
            container
            spacing={2}
            columns={{ xs: 6, sm: 12 }}
            marginBlockEnd={1}
          >
            <Grid item xs={6}>
              <TextField
                label={t("Task Template Code")}
                fullWidth
                {...register("code", {
                  required: t("Task template code is required"),
                })}
                error={Boolean(errors.code?.message)}
                helperText={errors.code?.message}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label={t("Task Template Name")}
                fullWidth
                {...register("name", {
                  required: t("Task template name is required"),
                })}
                error={Boolean(errors.name?.message)}
                helperText={errors.name?.message}
              />
            </Grid>
          </Grid>
          <TransferList
            allItems={items}
            initiallySelectedItems={[]}
            onChange={(selectedItems) => {
              setValue(
                "taskIds",
                selectedItems.map((item) => item.id),
              );
            }}
            allItemsLabel={t("Task Pool")}
            selectedItemsLabel={t("Task List Template")}
          />
        </CardContent>
      </Card>
      {serverError && (
        <Typography variant="body2" color="error" alignSelf="flex-end">
          {serverError}
        </Typography>
      )}
      <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={isSubmitting}
        >
          {t("Confirm")}
        </Button>
      </Stack>
    </Stack>
  );
};

export default CreateTaskTemplate;
