import {
  chakra,
  Checkbox,
  Flex,
  FormControl,
  FormLabel,
  Input,
} from "@chakra-ui/react";
import { UseFormReturn } from "react-hook-form";

import { FormKeyConfig } from "./form-key-config";
import { TData } from "../types";

export interface EditRecordFormProps<T extends TData> {
  form: UseFormReturn<T>;
  formKeys: FormKeyConfig<T>[];
}

export const EditRecordForm = <T extends TData>({
  form,
  formKeys,
}: EditRecordFormProps<T>) => (
  <FormContainer>
    {formKeys.map(({ key, label, type = "text", required, render }) =>
      render ? (
        render(form, { key, label, required })
      ) : (
        <FormControl key={key}>
          <StyledFormLabel>
            {label} {required && " *"}
          </StyledFormLabel>
          {type === "checkbox" ? (
            <Checkbox
              {...form.register(key, { required })}
              defaultChecked={form.getValues(key)}
              size="lg"
            >
              Approved
            </Checkbox>
          ) : (
            <FormInput
              type={type}
              {...form.register(key, { required })}
              size="lg"
            />
          )}
        </FormControl>
      )
    )}
  </FormContainer>
);

const FormContainer = chakra(Flex, {
  baseStyle: {
    flexDirection: "column",
    gap: "5px",
  },
});

export const StyledFormLabel = chakra(FormLabel, {
  baseStyle: {
    fontSize: "sm",
    mt: "8px",
    mb: "4px",
    ml: "0px",
  },
});

const FormInput = chakra(Input, {
  baseStyle: {
    rounded: "lg",
  },
});
