import React, { useState, useEffect } from "react";
import Sidebar from "./sidebar.jsx";
import { API_BASE_URL } from "../../config.js";
import axios from "axios";

const thTd = "p-2 border border-gray-300 text-left";
const th = `${thTd} bg-gray-100`;

function User() {
  const [users, setUsers] = useState([]);
  const [logs, setLogs] = useState([]);
  const [name, setname] = useState("");
  const [email, setEmail] = useState("");
  const [pointsInput, setPointsInput] = useState({});

  const handleAddUser = (e) => {
    e.preventDefault();
    const newUser = {
      id: Date.now(),
      name,
      email,
      accessLevel: "User",
      points: 0,
    };
    setUsers([...users, newUser]);
    logAction(name, "Utilisateur ajouté");
    setname("");
    setEmail("");
  };
  useEffect(() => {
    axios.get(`${API_BASE_URL}/users`).then((response) => {
      setUsers(response.data);
    });
  }, []);
  const handleDeleteUser = (userId) => {
    const user = users.find((u) => u.id === userId);
    if (user) {
      axios
        .post(`${API_BASE_URL}/deleteUser`, {
          id: userId,
        })
        .then((response) => {
          alert("L'utilisateur à bien été supprimé !");
          console.log("L'utilisateur à été supprimé :", response.data);
          window.location.reload();
        })
        .catch((error) => {
          console.error(
            "Erreur lors de la suppression de l'utilisateur :",
            error
          );
        });
      logAction(user.name, "Utilisateur supprimé");
    }
    setUsers(users.filter((u) => u.id !== userId));
  };

  const handleChangeAccessLevel = (userId, newLevel) => {
    setUsers(
      users.map((user) => {
        if (user.id === userId && newLevel!=user.role) {
          const oldLevel = user.role;
          user.role = newLevel;
          /*ToDO*/
          if (user.role === "user") {
            user.points = 0;
          } else if (user.role === "complexe") {
            user.points = 60;
          } else if (user.role === "admin") {
            user.points = 100;
          }
          axios
            .post(`${API_BASE_URL}/setUserPoints`, {
              id: user.id,
              points: user.points,
            })
            .then((response) => {
              alert("Le changement de niveau a bien été enregistré !");
              console.log("Changement de niveau réussit :", response.data);
            })
            .catch((error) => {
              alert("Il y a eu une erreur dans le changement de niveau !");
              console.error("Erreur lors du changement de niveau :", error);
            });
          logAction(
            user.name,
            `Niveau d'accés changé de ${oldLevel} à ${newLevel}`
          );
        }
        return user;
      })
    );
  };

  const handleAdjustPoints = (userId) => {
    const pointsToAdd = parseInt(pointsInput[userId]) || 0;
    setUsers(
      users.map((user) => {
        if (user.id === userId) {
          user.points = pointsToAdd;
          axios
            .post(`${API_BASE_URL}/setUserPoints`, {
              id: user.id,
              points: user.points,
            })
            .then((response) => {
              alert("Les points ont bien été enregistré !");
              console.log("Ajout des points réussit :", response.data);
            })
            .catch((error) => {
              alert("Il y a eu une erreur dans l'ajout des points!");
              console.error("Erreur lors de l'ajout des points :", error);
            });
          logAction(user.name, `Points ajustés par ${pointsToAdd}`);
        }
        return user;
      })
    );
    setPointsInput({ ...pointsInput, [userId]: "" });
  };

  const logAction = (name, action) => {
    /*TODO*/
    /*Ajouter le suivi dans un journal de log*/
    const timestamp = new Date().toLocaleString();
    setLogs([...logs, { id: Date.now(), name, action, timestamp }]);
  };

  return (
    <div className="flex min-h-screen">
      <Sidebar />
      <main className="flex-grow p-5">
        <section className="mt-5">
          <h1 className="text-2xl font-bold text-gray-900 mb-5">
            User Management
          </h1>
          <p>Manage users from this panel.</p>
          {/* Formulaire d'ajout d'utilisateur */}
          <form
            className="gap-3 mb-5 grid grid-cols-[1fr_1fr_auto]"
            onSubmit={handleAddUser}
          >
            <input
              className="p-3 border rounded-md"
              type="text"
              id="name"
              placeholder="name"
              value={name}
              onChange={(e) => setname(e.target.value)}
              required
            />
            <input
              className="p-3 border rounded-md"
              type="email"
              id="email"
              placeholder="Email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <button
              className="p-3 bg-green-600 text-white border-none rounded-md "
              type="submit"
            >
              Ajouter utilisateur
            </button>
          </form>
          {/* Tableau des utilisateurs */}
          <table className="w-full">
            <thead>
              <tr>
                <th className={`${th}`}>Nom</th>
                <th className={`${th}`}>Email</th>
                <th className={`${th}`}>Niveau d'accès</th>
                <th className={`${th}`}>Points</th>
                <th className={`${th}`}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr key={user.id}>
                  <td className={`${thTd}`}>{user.name}</td>
                  <td className={`${thTd}`}>{user.email}</td>
                  <td className={`${thTd}`}>
                    <select
                      value={user.role}
                      onChange={(e) =>
                        handleChangeAccessLevel(user.id, e.target.value)
                      }
                      className="p-2 rounded-md"
                    >
                      <option value="admin">Admin</option>
                      <option value="user">User</option>
                      <option value="complexe">Complexe</option>
                    </select>
                  </td>
                  <td className={`${thTd}`}>
                    <input
                      className="border ml-4 w-16"
                      type="number"
                      min="0"
                      value={pointsInput[user.id] || user.points}
                      onChange={(e) =>
                        setPointsInput({
                          ...pointsInput,
                          [user.id]: e.target.value,
                        })
                      }
                    />
                    <button
                      className="p-2 bg-green-600 text-white border-none rounded-md"
                      onClick={() => handleAdjustPoints(user.id)}
                    >
                      Changer
                    </button>
                  </td>
                  <td className={`${thTd}`}>
                    <button
                      className="p-2 bg-red-600 text-white border-none rounded-md"
                      onClick={() => handleDeleteUser(user.id)}
                    >
                      Supprimer
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
        {/* Tableau des logs */}
        <section className="user-logs mt-10">
          <h2 className="text-2xl font-bold text-gray-900 mb-5">
            Historique des connexions et journal des logs{" "}
          </h2>
          <table className="w-full">
            <thead>
              <tr>
                <th className={`${th}`}>Nom</th>
                <th className={`${th}`}>Action</th>
                <th className={`${th}`}>Timestamp</th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => (
                <tr key={log.id}>
                  <td className={`${thTd}`}>{log.name}</td>
                  <td className={`${thTd}`}>{log.action}</td>
                  <td className={`${thTd}`}>{log.timestamp}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      </main>
    </div>
  );
}

export default User;
