import React, { useState } from "react";
import Sidebar from "./sidebar.jsx";

const styles = {
  mainContent: {
    flexGrow: 1,
    padding: "20px",
  },
  header: {
    marginBottom: "20px",
  },
  userManagement: {
    marginTop: "20px",
  },
  userForm: {
    display: "grid",
    gridTemplateColumns: "1fr 1fr auto",
    gap: "10px",
    marginBottom: "20px",
  },
  input: {
    padding: "10px",
    border: "1px solid #ccc",
    borderRadius: "5px",
  },
  button: {
    padding: "10px",
    backgroundColor: "#28a745",
    color: "white",
    border: "none",
    borderRadius: "5px",
    cursor: "pointer",
  },
  userTable: {
    width: "100%",
    borderCollapse: "collapse",
  },
  thTd: {
    padding: "10px",
    border: "1px solid #ccc",
    textAlign: "left",
  },
  th: {
    backgroundColor: "#f4f4f4",
  },
};

function User() {
  // États pour la gestion des utilisateurs, des logs, des champs du formulaire et des ajustements de points
  const [users, setUsers] = useState([]);
  const [logs, setLogs] = useState([]);
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [pointsInput, setPointsInput] = useState({});

  // Ajout d'un utilisateur
  const handleAddUser = (e) => {
    e.preventDefault();
    const newUser = {
      id: Date.now(),
      username,
      email,
      accessLevel: "User", // Niveau d'accès par défaut
      points: 0,
    };
    setUsers([...users, newUser]);
    logAction(username, "User added");
    setUsername("");
    setEmail("");
  };

  // Suppression d'un utilisateur (fonction présente dans script.js)
  const handleDeleteUser = (userId) => {
    const user = users.find((u) => u.id === userId);
    if (user) {
      logAction(user.username, "User deleted");
    }
    setUsers(users.filter((u) => u.id !== userId));
  };

  // Changement du niveau d'accès via le menu déroulant (fonction issue de script.js)
  const handleChangeAccessLevel = (userId, newLevel) => {
    setUsers(
      users.map((user) => {
        if (user.id === userId) {
          const oldLevel = user.accessLevel;
          user.accessLevel = newLevel;
          logAction(
            user.username,
            `Access level changed from ${oldLevel} to ${newLevel}`
          );
        }
        return user;
      })
    );
  };

  // Ajustement des points d'un utilisateur (fonction issue de script.js)
  const handleAdjustPoints = (userId) => {
    const pointsToAdd = parseInt(pointsInput[userId]) || 0;
    setUsers(
      users.map((user) => {
        if (user.id === userId) {
          user.points += pointsToAdd;
          logAction(user.username, `Points adjusted by ${pointsToAdd}`);
        }
        return user;
      })
    );
    // Réinitialiser la valeur de l'input pour cet utilisateur
    setPointsInput({ ...pointsInput, [userId]: "" });
  };

  // Fonction de journalisation des actions (définie dans script.js)
  const logAction = (username, action) => {
    const timestamp = new Date().toLocaleString();
    setLogs([...logs, { id: Date.now(), username, action, timestamp }]);
  };

  return (
    <div style={{ display: "flex", minHeight: "100vh" }}>
      <Sidebar />
      <main style={styles.mainContent}>
        <section style={styles.userManagement}>
          <h1>User Management</h1>
          <p>Manage users from this panel.</p>
          {/* Formulaire d'ajout d'utilisateur */}
          <form style={styles.userForm} onSubmit={handleAddUser}>
            <input
              style={styles.input}
              type="text"
              id="username"
              placeholder="Username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
            <input
              style={styles.input}
              type="email"
              id="email"
              placeholder="Email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <button style={styles.button} type="submit">
              Add User
            </button>
          </form>
          {/* Tableau des utilisateurs */}
          <table style={styles.userTable}>
            <thead>
              <tr>
                <th style={{ ...styles.thTd, ...styles.th }}>Username</th>
                <th style={{ ...styles.thTd, ...styles.th }}>Email</th>
                <th style={{ ...styles.thTd, ...styles.th }}>Access Level</th>
                <th style={{ ...styles.thTd, ...styles.th }}>Points</th>
                <th style={{ ...styles.thTd, ...styles.th }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr key={user.id}>
                  <td style={styles.thTd}>{user.username}</td>
                  <td style={styles.thTd}>{user.email}</td>
                  <td style={styles.thTd}>
                    {/* Menu déroulant pour changer le niveau d'accès */}
                    <select
                      value={user.accessLevel}
                      onChange={(e) =>
                        handleChangeAccessLevel(user.id, e.target.value)
                      }
                      style={{ padding: "5px", borderRadius: "5px" }}
                    >
                      <option value="Admin">Admin</option>
                      <option value="User">User</option>
                      <option value="Guest">Guest</option>
                    </select>
                  </td>
                  <td style={styles.thTd}>
                    <span>{user.points}</span>
                    {/* Input et bouton pour ajuster les points */}
                    <input
                      type="number"
                      min="0"
                      style={{ width: "60px", marginLeft: "10px" }}
                      placeholder="Adjust"
                      value={pointsInput[user.id] || ""}
                      onChange={(e) =>
                        setPointsInput({
                          ...pointsInput,
                          [user.id]: e.target.value,
                        })
                      }
                    />
                    <button
                      style={{
                        ...styles.button,
                        padding: "5px 10px",
                        marginLeft: "5px",
                      }}
                      onClick={() => handleAdjustPoints(user.id)}
                    >
                      Adjust
                    </button>
                  </td>
                  <td style={styles.thTd}>
                    {/* Bouton de suppression */}
                    <button
                      style={{
                        ...styles.button,
                        backgroundColor: "#dc3545",
                        padding: "5px 10px",
                      }}
                      onClick={() => handleDeleteUser(user.id)}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
        {/* Tableau des logs */}
        <section className="user-logs" style={{ marginTop: "40px" }}>
          <h2>Login History and Action Logs</h2>
          <table style={styles.userTable}>
            <thead>
              <tr>
                <th style={{ ...styles.thTd, ...styles.th }}>Username</th>
                <th style={{ ...styles.thTd, ...styles.th }}>Action</th>
                <th style={{ ...styles.thTd, ...styles.th }}>Timestamp</th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => (
                <tr key={log.id}>
                  <td style={styles.thTd}>{log.username}</td>
                  <td style={styles.thTd}>{log.action}</td>
                  <td style={styles.thTd}>{log.timestamp}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      </main>
    </div>
  );
}

export default User;
