'use client';
import { useState } from "react";

export enum FieldType {
  number = 'number',
  text = 'text'
}

export type FormFields = {
  type: FieldType,
  name: string,
  label: string,
  required: boolean
}

const Form = <T,>({ fields, onSubmit }) => {
  const [formData, setFormData] = useState({});
  
    const handleChange = (event) => {
      const { name, value } = event.target;
      setFormData( (prevData) => ({
        ...prevData,
        [name]: value
      }));
    }

  const handleSubmit = (event) => {
    event.preventDefault();
    onSubmit( formData );
  }

  return ( 
    <form onSubmit={handleSubmit}>
      {fields.map( (field) => {
            return (
              <div key={field.name}>
                <label>{field.label}</label>
                <input 
                  type={field.type}
                  name={field.name}
                  value={formData[field.name] || ''}
                  onChange={handleChange}
                  required={field.required}
                />
              </div>
      )})}
      <button type="submit">Submit</button>
    </form>
  );
}

export default Form;

