"use client";

import { FC, useEffect, useState } from "react";
import { useFormState } from "react-dom";
import { Grid } from "@mui/material";
import { useRouter } from "next/navigation";
import { Button, Dialog, TextField, Select, MultiValueField } from "ui";
import { generateCreateAction } from "../lib/actions";
import { FieldDescription } from "../lib/service";
import { serviceConfig } from "../config/config";
import { getBasePath } from "../lib/frontendUtils";

type CreateProps = {
  service: string;
};

export const Create: FC<CreateProps> = ({ service }) => {
  const {
    [service]: { entity, table, displayName, createFields },
  } = serviceConfig;
  const fields = createFields.map((field: any) => {
    const copy = { ...field };
    Object.keys(copy).forEach((key: any) => {
      if (typeof copy[key] === "function") {
        delete copy[key];
      }
    });
    return copy;
  });

  const createAction = generateCreateAction({ entity, table, fields });
  const initialState = {
    message: null,
    errors: {},
    values: fields.reduce(
      (acc: Record<string, any>, field: FieldDescription) => {
        acc[field.name] = field.defaultValue;
        return acc;
      },
      {},
    ),
  };
  const [formState, formAction] = useFormState(createAction, initialState);
  const [liveFormState, setLiveFormState] = useState(formState);
  const updateFormState = (field: string, value: any) => {
    const newState = { ...liveFormState };
    newState.values[field] = value;
    setLiveFormState(newState);
  };

  const router = useRouter();

  useEffect(() => {
    if (formState.success) {
      router.push(`${getBasePath()}${entity}/${formState.values.id}`);
    }
  }, [formState.success, router, entity, formState.values.id]);

  return (
    <Dialog
      open
      title={`Create ${displayName}`}
      formAction={formAction}
      onClose={() => router.push(`${getBasePath()}${entity}`)}
      buttons={
        <Grid container justifyContent="space-between">
          <Grid item>
            <Button
              text="Cancel"
              kind="secondary"
              onClick={() => router.push(`${getBasePath()}${entity}`)}
            />
          </Grid>
          <Grid item>
            <Button text="Save" kind="primary" type="submit" />
          </Grid>
        </Grid>
      }
    >
      <Grid container direction="row" rowSpacing={3} columnSpacing={2}>
        {createFields.map(
          (field: FieldDescription) =>
            !field.hidden && (
              <Grid key={field.name} item xs={field.size ?? 6}>
                {field.kind === "select" && (
                  <Select
                    name={field.name}
                    label={field.label}
                    required={field.required ?? false}
                    formState={liveFormState}
                    getOptions={field.getOptions}
                    updateFormState={updateFormState}
                  />
                )}
                {field.kind === "multi" && (
                  <MultiValueField
                    name={field.name}
                    label={field.label}
                    formState={formState}
                    helperText={field.helperText}
                  />
                )}
                {(!field.kind || field.kind === "text") && (
                  <TextField
                    name={field.name}
                    label={field.label}
                    lines={field.lines ?? 1}
                    required={field.required ?? false}
                    formState={formState}
                    helperText={field.helperText}
                  />
                )}
              </Grid>
            ),
        )}
      </Grid>
    </Dialog>
  );
};
