import { useApiCreateRecipe, useApiGetDataServiceList } from "@/api/cubicweb";
import { DataService, Recipe } from "@/types";
import { LoadingButton } from "@mui/lab";
import {
  Autocomplete,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Stack,
  TextField,
} from "@mui/material";
import { useEffect, useState } from "react";
import { Controller, SubmitHandler, useForm } from "react-hook-form";

interface RecipeModalProps {
  projectEid: number;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export function RecipeModal({
  projectEid,
  open,
  onClose,
  onSuccess,
}: RecipeModalProps) {
  const [data, setData] = useState<Array<DataService> | undefined>();
  const [loading, setLoading] = useState<boolean>(true);
  const [saving, setSaving] = useState(false);
  const getDataServiceList = useApiGetDataServiceList();
  const createRecipe = useApiCreateRecipe();

  const { handleSubmit, control, reset } = useForm<Recipe>({
    defaultValues: {
      name: "",
      process_type: "default",
    },
  });

  useEffect(() => {
    if (open) {
      setLoading(true);
      setTimeout(() => {
        setLoading(false);
        getDataServiceList().then((d) => setData(d));
      }, 1000);
    } else {
      reset();
      setData(undefined);
    }
  }, [open, reset]);

  const onSubmit: SubmitHandler<Recipe> = async (data) => {
    setSaving(true);
    await createRecipe(projectEid, data);
    onSuccess();
    onClose();
    setSaving(false);
  };

  return (
    <Dialog
      open={open}
      onClose={() => {
        if (!saving) {
          onClose();
        }
      }}
      PaperProps={{
        component: "form",
        onSubmit: handleSubmit(onSubmit),
      }}
      aria-labelledby="form-dialog-title"
      aria-describedby="form-dialog-description"
      fullWidth
    >
      <DialogTitle id="form-dialog-title">Création recette</DialogTitle>
      <DialogContent>
        <Stack paddingTop={1} spacing={2}>
          <Controller
            name="name"
            control={control}
            rules={{ required: true }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                label="Nom"
                disabled={saving}
                {...field}
                error={error !== undefined}
                helperText={
                  error?.type === "required" ? "Champ requis" : error?.message
                }
              />
            )}
          />
          <Controller
            name="dataservice"
            control={control}
            rules={{ required: true }}
            render={({ field, fieldState: { error } }) => (
              <Autocomplete
                disabled={saving}
                value={field.value}
                onChange={(_, newValue) => field.onChange(newValue)}
                options={data ? data : []}
                loading={loading}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Data service"
                    error={error !== undefined}
                    helperText={
                      error?.type === "required"
                        ? "Champ requis"
                        : error?.message
                    }
                  />
                )}
                getOptionLabel={
                  data
                    ? (option) => data.find((d) => d === option)?.name ?? ""
                    : () => ""
                }
              />
            )}
          />
          <Controller
            name="graph_uri"
            control={control}
            rules={{ required: true }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                label="Graph Uri"
                disabled={saving}
                {...field}
                error={error !== undefined}
                helperText={
                  error?.type === "required" ? "Champ requis" : error?.message
                }
              />
            )}
          />
          <Controller
            name="process_type"
            control={control}
            rules={{ required: true }}
            render={({ field, fieldState: { error } }) => (
              <Autocomplete
                disabled={saving}
                {...field}
                inputValue={field.value}
                onChange={(_, newValue) => field.onChange(newValue)}
                options={["default", "default-dryrun"]}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Process type"
                    error={error !== undefined}
                    helperText={
                      error?.type === "required"
                        ? "Champ requis"
                        : error?.message
                    }
                  />
                )}
              />
            )}
          />
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={saving}>
          Annuler
        </Button>
        <LoadingButton type="submit" loading={saving}>
          Valider
        </LoadingButton>
      </DialogActions>
    </Dialog>
  );
}