"use client";

import { getUsers, updateUser } from "../../../../../lib/api"; // ✅ adjust if your API file path is different
import { useEffect, useState } from "react";

interface User {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  role: "user" | "admin" | "superadmin";
  approved: boolean;
  createdAt: string;
}

export default function UserManagement() {
  const [users, setUsers] = useState<User[]>([]);
  const [currentRole, setCurrentRole] = useState("user");

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const res = await getUsers();
        setUsers(res);
        const localRole = localStorage.getItem("role") || "user";
        setCurrentRole(localRole);
      } catch (err) {
        console.error("Error fetching users:", err);
      }
    };
    fetchUsers();
  }, []);

  const handleApprovalToggle = async (id: number, approved: boolean) => {
    try {
      await updateUser(id, { approved: !approved });
      setUsers((prev) =>
        prev.map((user) =>
          user.id === id ? { ...user, approved: !approved } : user
        )
      );
    } catch (err) {
      console.error("Error updating approval:", err);
    }
  };

  const handleRoleChange = async (id: number, newRole: string) => {
    try {
      await updateUser(id, { role: newRole });
      setUsers((prev) =>
        prev.map((user) =>
          user.id === id ? { ...user, role: newRole as any } : user
        )
      );
    } catch (err) {
      console.error("Error updating role:", err);
    }
  };

  return (
    <div className="bg-white p-6 m-4 rounded-md">
      <h1 className="text-2xl font-bold mb-4">User Management</h1>
      <div className="overflow-x-auto">
        <table className="min-w-full bg-gray-100 text-sm rounded-md">
          <thead className="bg-gray-300">
            <tr>
              <th className="p-3 text-left">Name</th>
              <th className="p-3 text-left">Email</th>
              <th className="p-3 text-left">Role</th>
              <th className="p-3 text-left">Approved</th>
              <th className="p-3 text-left">Joined</th>
              <th className="p-3 text-left">Actions</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr
                key={user.id}
                className="border-t border-gray-300 hover:bg-gray-200 transition"
              >
                <td className="p-3">
                  {user.first_name} {user.last_name}
                </td>
                <td className="p-3">{user.email}</td>
                <td className="p-3 capitalize">{user.role}</td>
                <td className="p-3">{user.approved ? "Yes" : "No"}</td>
                <td className="p-3">
                  {new Date(user.createdAt).toLocaleDateString()}
                </td>
                <td className="p-3 flex gap-2 items-center">
                  <button
                    onClick={() => handleApprovalToggle(user.id, user.approved)}
                    className={`px-3 py-1 text-white rounded text-xs ${
                      user.approved
                        ? "bg-red-500 hover:bg-red-600"
                        : "bg-green-600 hover:bg-green-700"
                    }`}
                  >
                    {user.approved ? "Unapprove" : "Approve"}
                  </button>

                  {currentRole === "superadmin" && (
                    <select
                      value={user.role}
                      onChange={(e) =>
                        handleRoleChange(user.id, e.target.value)
                      }
                      className="p-1 text-sm border rounded"
                    >
                      <option value="user">User</option>
                      <option value="admin">Admin</option>
                      <option value="superadmin">Superadmin</option>
                    </select>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
