import { useState } from "react";
import Button from "../Button";
import Dropdown from "../Dropdown";

const Form = () => {
  const [formData, setFormData] = useState({ name: "", email: "" });
  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const validate = () => {
    let newErrors = {};
    if (!formData.name) newErrors.name = "Name is required";
    if (!formData.email) {
      newErrors.email = "Email is required";
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = "Email is invalid";
    }
    return newErrors;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const validationErrors = validate();
    if (Object.keys(validationErrors).length === 0) {
      <p>Form Filled Successfully</p>
    }
    setErrors(validationErrors);
  };

  const approveText = () => {
    setTimeout(() => {
      <p>Form Filled Successfully</p>
    },1000)
  
  };

  return (
    <>
      <form
        onSubmit={handleSubmit}
        className="max-w-md mx-auto p-4 border rounded shadow"
        data-test="form"
      >
        <div className="mb-4">
          <label htmlFor="name" className="block mb-2" data-test="label-name">
            Name
          </label>
          <input
            id="name"
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded"
            data-test="input-name"
          />
          {errors.name && <p className="text-red-500 text-sm">{errors.name}</p>}
        </div>

        <div className="mb-4">
          <label htmlFor="email" className="block mb-2" data-test="label-email">
            Email
          </label>
          <input
            id="email"
            type="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded"
            data-test="input-email"
          />
          {errors.email && (
            <p className="text-red-500 text-sm">{errors.email}</p>
          )}
        </div>

        <Dropdown />

        <div className="mt-4">
          <Button
            label="Submit"
            data-test="submit-button"
            onClick={() => {
              approveText();
              setFormData({ name: "", email: "" });
            }}

          />
        </div>
      </form>
    </>
  );
};

export default Form;
