import { useState } from "react";
import {
  handleUpdateUserPermission,
  handleUpdateUserRoles,
} from "../../utils/api";
import { toast } from "react-hot-toast";
import { capitalizeFirstLetter } from "../../utils/capitalizeFirstLetter";

interface UserAccessCardProps {
  user: {
    _id: string;
    userName: string;
    roles: string[];
    permissions?: string[];
  };
  onUpdated: (updatedUser: any) => void;
}

const ALL_ROLES = ["staff", "manager", "admin", "developer"];
const ALL_PERMISSIONS = [
  "canViewReports",
  "canEditProduct",
  "canDeleteUser",
  "canChangeRole",
  "canManageOrders",
];

export default function UserAccessCard({
  user,
  onUpdated,
}: UserAccessCardProps) {
  const [roles, setRoles] = useState<string[]>(user.roles);
  const [permissions, setPermissions] = useState<string[]>(
    user.permissions || []
  );
  const [loading, setLoading] = useState(false);

  const toggleRole = (role: string) => {
    setRoles((prev) =>
      prev.includes(role) ? prev.filter((r) => r !== role) : [...prev, role]
    );
  };

  const togglePermission = (perm: string) => {
    setPermissions((prev) =>
      prev.includes(perm) ? prev.filter((p) => p !== perm) : [...prev, perm]
    );
  };

  const handleUpdate = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem("token");
      const userId = user._id;

      await handleUpdateUserRoles({ roles, userId, token });
      await handleUpdateUserPermission({
        permissions,
        token,
        onUpdated,
        userId,
      });

      toast.success("Access updated successfully!");
    } catch (err) {
      console.error("Update failed:", err);
      toast.error("Failed to update access.");
    } finally {
      setLoading(false);
    }
  };

  const isDeveloper = roles.includes("developer");

  return (
    <div className="bg-white border rounded-xl shadow p-5 transition hover:shadow-md">
      <div className="mb-4">
        <h3 className="text-lg font-semibold text-gray-800">
          {capitalizeFirstLetter(user.userName)}
        </h3>
        {/* <p className="text-sm text-gray-500">ID: {user._id}</p> */}
      </div>

      <div className="mb-4">
        <p className="text-sm font-medium text-gray-700 mb-1">Roles:</p>
        <div className="flex flex-wrap gap-2">
          {ALL_ROLES.map((role) => (
            <button
              key={role}
              type="button"
              onClick={() => toggleRole(role)}
              className={`px-3 py-1 rounded-full text-sm border ${
                roles.includes(role)
                  ? "bg-blue-600 text-white border-blue-600"
                  : "bg-gray-100 text-gray-700 border-gray-300"
              }`}
            >
              {role}
            </button>
          ))}
        </div>
      </div>

      <div className="mb-4">
        <p className="text-sm font-medium text-gray-700 mb-1">Permissions:</p>

        {isDeveloper ? (
          <div className="text-sm text-gray-500 italic">
            Developer has all permissions by default.
          </div>
        ) : (
          <div className="grid grid-cols-2 gap-2">
            {ALL_PERMISSIONS.map((perm) => (
              <label key={perm} className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={permissions.includes(perm)}
                  onChange={() => togglePermission(perm)}
                  className="accent-blue-600"
                />
                {perm}
              </label>
            ))}
          </div>
        )}
      </div>

      <div className="text-right">
        {!isDeveloper && (
          <button
            onClick={handleUpdate}
            disabled={loading}
            className="bg-blue-600 text-white px-4 py-1.5 rounded hover:bg-blue-700 transition disabled:opacity-50"
          >
            {loading ? "Updating..." : "Update Access"}
          </button>
        )}
      </div>
    </div>
  );
}


this is my simple design. i need modern, smart, animation, professional and unique design