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

const UserDetails = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();

  const [users, setUsers] = useState(location.state?.users || []);
  const [user, setUser] = useState(null);

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

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

  if (!user) {
    return (
      <div>
        <p>User not found.</p>
        <button onClick={() => navigate("/")}>Return to Home</button>
      </div>
    );
  }

  return (
    <div className="container">
      <h1>User Details</h1>
      <div className="user-detail">
        <p>
          <strong>Name:</strong> {user.name}
        </p>
        <p>
          <strong>Email:</strong> {user.email}
        </p>
        <p>
          <strong>Phone:</strong> {user.phone}
        </p>
        <p>
          <strong>Website:</strong> {user.website}
        </p>
      </div>
      <div className="button-container">
        <button className="home-button" onClick={() => navigate("/")}>
          Return to Home
        </button>
        <button className="delete-button" onClick={handleDelete}>
          Delete User
        </button>
      </div>
    </div>
  );
};

export default UserDetails;
