import React, { useEffect, useState } from "react";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { useForm, Controller } from "react-hook-form";

const EditUser = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const [users, setUsers] = useState(location.state?.users || []);

  const { control, handleSubmit, reset, formState: { errors } } = useForm({
    defaultValues: {
      name: "",
      email: "",
      phone: "",
      website: "",
    },
  });

  useEffect(() => {
    if (users.length === 0) {
      const fetchUsers = async () => {
        const response = await fetch("https://jsonplaceholder.typicode.com/users");
        const data = await response.json();
        setUsers(data);
      };
      fetchUsers();
    }
  }, [users]);

  const user = users.find((user) => user.id === parseInt(id));

  useEffect(() => {
    if (user) {
      reset(user);
    }
  }, [user, reset]);

  const onSubmit = (data) => {
    let updatedUsers;
    if (id === "new") {
      const newUser = { ...data, id: users.length + 1 };
      updatedUsers = [...users, newUser];
      alert("User added successfully!");
    } else {
      updatedUsers = users.map((u) =>
        u.id === parseInt(id) ? { ...data, id: u.id } : u
      );
      alert("User updated successfully!");
    }

    setUsers(updatedUsers);
    navigate("/", { state: { users: updatedUsers } });
  };

  const handleDelete = () => {
    const updatedUsers = users.filter((user) => user.id !== parseInt(id));
    setUsers(updatedUsers);
    alert(`User with ID ${id} deleted.`);
    navigate("/", { state: { users: updatedUsers } });
  };

  return (
    <div className="form-container">
      <h1>{id === "new" ? "Add" : "Edit"} User</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label>Name</label>
          <Controller
            name="name"
            control={control}
            rules={{ required: "Name is required" }}
            render={({ field }) => <input {...field} />}
          />
          {errors.name && <p>{errors.name.message}</p>}
        </div>
        <div>
          <label>Email</label>
          <Controller
            name="email"
            control={control}
            rules={{ required: "Email is required" }}
            render={({ field }) => <input {...field} />}
          />
          {errors.email && <p>{errors.email.message}</p>}
        </div>
        <div>
          <label>Phone</label>
          <Controller
            name="phone"
            control={control}
            render={({ field }) => <input {...field} />}
          />
        </div>
        <div>
          <label>Website</label>
          <Controller
            name="website"
            control={control}
            render={({ field }) => <input {...field} />}
          />
        </div>
        <button type="submit" className="submit-button">
          Save
        </button>
      </form>
      <div className="button-container">
        <button className="home-button" onClick={() => navigate("/")}>
          Return to Home
        </button>
        {id !== "new" && (
          <button className="delete-button" onClick={handleDelete}>
            Delete User
          </button>
        )}
      </div>
    </div>
  );
};

export default EditUser;
