import React from "react";
import styled from "styled-components";
import { ISubmitEvent, IChangeEvent, ErrorSchema } from "react-jsonschema-form";
import { colors } from "@theme/colors";
import Event from "@models/Event";
import Post from "@models/Feed";
import { SignupForm } from "@models/Signup";
import JobAd from "@models/JobAd";
import FormWrapper from "@views/common/FormWrapper";
import AdminPageWrapper from "@views/common/AdminPageWrapper";

const Common = styled.div`
  legend {
    font-weight: bold;
    margin: 0.5rem 0;
  }
`;

const ErrorMsg = styled.p`
  margin-bottom: 0.5rem;
  border: 1px solid ${colors.orange2};
  padding: 8px 16px;
  color: ${colors.orange2};
  display: inline-block;
`;

type FormTypes = Event | SignupForm | Post | JobAd;

type AdminCreateCommonProps = {
  title: string;
  formData?: FormTypes;
  schema: {
    [name: string]: unknown;
  };
  UISchema: {
    [name: string]: unknown;
  };
  onChange?: (e: IChangeEvent<FormTypes>, es?: ErrorSchema) => unknown;
  onFocus?: (id: string, value: string | number | boolean) => void;
  onSubmit: (e: ISubmitEvent<FormTypes>) => unknown;
  error: string;
  widgets: {
    [name: string]: any;
  };
};

const AdminCreateCommon: React.FC<AdminCreateCommonProps> = ({
  title,
  formData,
  schema,
  UISchema,
  onChange,
  onFocus,
  onSubmit,
  error,
  widgets,
}) => {
  const onError = (data: unknown) => {
    console.error("error, data:");
    console.error(data);
  };

  return (
    <AdminPageWrapper requiresAuthentication>
      <Common>
        <h1>{title}</h1>
        <FormWrapper
          schema={schema}
          uiSchema={UISchema}
          formData={formData}
          idPrefix="rjsf"
          widgets={widgets}
          onChange={onChange}
          onSubmit={onSubmit}
          onError={onError}
          onFocus={onFocus}
        />
        {error && (
          <ErrorMsg>{error}</ErrorMsg>
        )}
      </Common>
    </AdminPageWrapper>
  );
};

export default AdminCreateCommon;
