import { create } from 'zustand';
import { api } from '../lib/api.ts';

export interface Server {
  id: string;
  name: string;
  icon: string | null;
  ownerId: string;
  unread?: boolean;
}

interface ServerState {
  servers: Server[];
  activeServerId: string | null;
  userPermissions: {
    kick_members: boolean;
    ban_members: boolean;
    mute_members: boolean;
    manage_channels: boolean;
    manage_server: boolean;
    administrator: boolean;
  };
  isLoading: boolean;
  error: string | null;
  fetchServers: () => Promise<void>;
  setActiveServer: (id: string | null) => void;
  addServer: (server: Server) => void;
  updateServer: (server: Server) => void;
  removeServer: (id: string) => void;
  setUserPermissions: (perms: Partial<ServerState['userPermissions']>) => void;
}

export const useServerStore = create<ServerState>((set) => ({
  servers: [],
  activeServerId: null,
  userPermissions: {
    kick_members: false,
    ban_members: false,
    mute_members: false,
    manage_channels: false,
    manage_server: false,
    administrator: false,
  },
  isLoading: false,
  error: null,

  fetchServers: async () => {
    set({ isLoading: true, error: null });
    try {
      const servers = await api.get<Server[]>('/servers');
      set({ servers, isLoading: false });
    } catch (error) {
      set({
        isLoading: false,
        error: error instanceof Error ? error.message : 'Failed to fetch servers',
      });
    }
  },

  setActiveServer: (id) => set({ activeServerId: id }),

  addServer: (server) =>
    set((state) => ({
      servers: [...state.servers, server],
    })),

  updateServer: (server) =>
    set((state) => ({
      servers: state.servers.map((s) => (s.id === server.id ? server : s)),
    })),

  removeServer: (id) =>
    set((state) => ({
      servers: state.servers.filter((s) => s.id !== id),
      activeServerId: state.activeServerId === id ? null : state.activeServerId,
    })),

  setUserPermissions: (perms) =>
    set((state) => ({
      userPermissions: { ...state.userPermissions, ...perms },
    })),
}));
