import React, { useState } from "react";
import axios from "axios";
import "./EmpProfile.css";
import showToast from "../../services/toastService";

const defaultImageSrc = "/img/avatars/00.jpg";
const initialObj = {
  employeeId: 0,
  employeeName: "",
  occupation: "",
  imageName: "",
  imageSrc: defaultImageSrc,
  imageFile: null,
};
function EmpProfile({ addOrEdit }) {
  const [values, setValues] = useState(initialObj);
  const [errors, setErrors] = useState({});

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    images: [],
  });
  const handleValueChange = (e) => {
    const { name, value } = e.target;
    setValues((prev) => ({
      ...prev,
      [name]: value,
    }));
    validate();
  };

  const showPreview = (e) => {
    if (e.target.files && e.target.files[0]) {
      let imageFile = e.target.files[0];
      const reader = new FileReader();
      reader.onload = (x) => {
        setValues({
          ...values,
          imageFile,
          imageSrc: x.target.result,
        });
      };
      reader.readAsDataURL(imageFile);
    } else {
      setValues({
        ...values,
        imageFile: null,
        imageSrc: defaultImageSrc,
      });
    }
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    const token = localStorage.getItem("jwtToken");
    const data = new FormData();
    data.append("firstName", formData.firstName);
    data.append("lastName", formData.lastName);

    // Append multiple files
    for (let i = 0; i < formData.images.length; i++) {
      data.append("images", formData.images[i]);
    }

    try {
      const response = await axios.post("/api/employee/uploadtest", data, {
        headers: {
          validateStatus: false,
          Authorization: `Bearer ${token}`,
          "Content-Type": "multipart/form-data",
        },
      });
      if (response.status === 200) {
        alert("Form submitted successfully!");
      }
    } catch (error) {
      alert("Failed to submit form.");
    }
  };

  const resetForm = () => {
    setValues(initialObj);
    document.getElementById("image-uploader").value = null;
    setErrors({});
  };
  const handleFormSubmit = (e) => {
    e.preventDefault();
    if (validate()) {
      const formData = new FormData();
      formData.append("employeeId", values.employeeId);
      formData.append("employeeName", values.employeeName);
      formData.append("occupation", values.occupation);
      formData.append("imageName", values.imageName);
      formData.append("imageSrc", values.imageSrc);
      formData.append("imageFile", values.imageFile);

      addOrEdit(formData, resetForm);
    }
  };

  const validate = () => {
    let temp = {};
    temp.employeeName = values.employeeName == "" ? false : true;
    temp.occupation = values.occupation == "" ? false : true;

    temp.imageSrc = values.imageSrc == defaultImageSrc ? false : true;

    setErrors(temp);
    return Object.values(temp).every((x) => x == true);
  };

  const applyErrorClass = (field) =>
    field in errors && errors[field] == false ? "invalid-field" : "";

  const showToasts = () => {
    showToast("Server is unreachable. Try again later.!", "error");
    showToast("Server is unreachable. Try again later.!", "success");
  };
  return (
    <>
      <form onSubmit={handleFormSubmit}>
        <div className="card text-center">
          <img src={values.imageSrc} style={{ width: "200px" }}></img>
          <div className="card-body">
            <div>
              <label>Employee Name:</label>
              <input
                className={"form-control " + applyErrorClass("employeeName")}
                type="text"
                name="employeeName"
                value={values.employeeName}
                onChange={handleValueChange}
              />
            </div>
            <div>
              <label>Occupation:</label>
              <input
                type="text"
                className={"form-control " + applyErrorClass("occupation")}
                name="occupation"
                value={values.occupation}
                onChange={handleValueChange}
              />
            </div>{" "}
            <div>
              <label>Image:</label>
              <input
                className={"form-control " + applyErrorClass("imageSrc")}
                type="file"
                name="images"
                id="image-uploader"
                accept="image/*"
                onChange={showPreview}
              />
            </div>
          </div>
          <button type="submit" className="btn btn-primary">
            Submit
          </button>
        </div>
      </form>

      <button type="button" onClick={showToasts} className="btn btn-primary">
        Show toast
      </button>
    </>
  );
}

export default EmpProfile;
