import { useCallback } from 'react';
import { useServerStore } from '../stores/server.ts';
import { useAuthStore } from '../stores/auth.ts';
import { useRoleStore } from '../stores/role.ts';

const PERMS = {
  VIEW_CHANNEL: 1,
  SEND_MESSAGES: 2,
  MANAGE_MESSAGES: 4,
  KICK_MEMBERS: 8,
  BAN_MEMBERS: 16,
  MANAGE_SERVER: 32,
  MANAGE_CHANNELS: 64,
  ADMINISTRATOR: 128,
  CONNECT_VOICE: 256,
  SPEAK_VOICE: 512,
  SHARE_SCREEN: 1024,
  MUTE_MEMBERS: 2048,
  CHANGE_NICKNAME: 8192,
  MANAGE_NICKNAMES: 16384,
  MANAGE_ROLES: 32768,
} as const;

export { PERMS };

export function usePermissions(serverId: string | null) {
  const user = useAuthStore((s) => s.user);
  const servers = useServerStore((s) => s.servers);
  const roles = useRoleStore((s) => s.roles);

  const server = serverId ? servers.find((s) => s.id === serverId) : null;
  const isOwner = Boolean(server && user && server.owner_id === user.id);

  const memberRoles = roles.filter((r) => r.server_id === serverId);

  const has = useCallback(
    (flag: number) => {
      if (!serverId || !user) return false;
      if (isOwner) return true;
      const effective = memberRoles.reduce((acc, r) => acc | r.permissions, 0);
      if ((effective & PERMS.ADMINISTRATOR) !== 0) return true;
      return (effective & flag) === flag;
    },
    [serverId, user, isOwner, memberRoles],
  );

  return {
    canKick: has(PERMS.KICK_MEMBERS),
    canBan: has(PERMS.BAN_MEMBERS),
    canMute: has(PERMS.MUTE_MEMBERS),
    canManageChannels: has(PERMS.MANAGE_CHANNELS),
    canManageRoles: has(PERMS.MANAGE_ROLES),
    canManageServer: has(PERMS.MANAGE_SERVER),
    canChangeNickname: has(PERMS.CHANGE_NICKNAME),
    canManageNicknames: has(PERMS.MANAGE_NICKNAMES),
    isOwner,
  };
}
