import apiClient from '../../../shared/services/apiClient';

export interface TeamUser {
  id: number;
  full_name: string;
  email: string;
  avatar_url: string | null;
  role: string | null;
  status?: string;
  last_seen?: string;
}

export interface ChannelMember {
  id: number;
  full_name: string;
  email: string;
  avatar_url: string | null;
  role: string | null;
}

export interface TeamMessage {
  id: number;
  channel_id: number;
  sender_id: number;
  sender: TeamUser | null;
  content: string;
  priority: 'normal' | 'high' | 'urgent';
  reply_to_id: number | null;
  reference_type: string | null;
  reference_id: number | null;
  is_edited: boolean;
  is_deleted: boolean;
  created_at: string;
  edited_at: string | null;
}

export interface TeamChannel {
  id: number;
  name: string;
  description: string | null;
  channel_type: 'direct' | 'group' | 'department' | 'announcement';
  department: string | null;
  is_private: boolean;
  is_active: boolean;
  created_at: string;
  last_message_at: string | null;
  unread_count: number;
  members: ChannelMember[];
  last_message: TeamMessage | null;
}

export interface CreateChannelData {
  name?: string;
  description?: string;
  channel_type?: 'group' | 'department' | 'announcement';
  department?: string;
  is_private?: boolean;
  member_ids?: number[];
}

export interface SendMessageData {
  content: string;
  priority?: 'normal' | 'high' | 'urgent';
  reply_to_id?: number;
  reference_type?: string;
  reference_id?: number;
}

export interface DirectMessageData {
  recipient_id: number;
  content: string;
  priority?: 'normal' | 'high' | 'urgent';
}

class TeamChatService {
  // Channels
  async getMyChannels(): Promise<{ success: boolean; data: TeamChannel[] }> {
    const response = await apiClient.get('/team-chat/channels');
    return response.data;
  }

  async createChannel(data: CreateChannelData): Promise<{ success: boolean; data: TeamChannel }> {
    const response = await apiClient.post('/team-chat/channels', data);
    return response.data;
  }

  async getChannel(channelId: number): Promise<{ success: boolean; data: TeamChannel }> {
    const response = await apiClient.get(`/team-chat/channels/${channelId}`);
    return response.data;
  }

  async updateChannel(channelId: number, data: Partial<CreateChannelData>): Promise<{ success: boolean; data: TeamChannel }> {
    const response = await apiClient.put(`/team-chat/channels/${channelId}`, data);
    return response.data;
  }

  async addChannelMembers(channelId: number, memberIds: number[]): Promise<{ success: boolean; message: string }> {
    const response = await apiClient.post(`/team-chat/channels/${channelId}/members`, memberIds);
    return response.data;
  }

  async removeChannelMember(channelId: number, userId: number): Promise<{ success: boolean; message: string }> {
    const response = await apiClient.delete(`/team-chat/channels/${channelId}/members/${userId}`);
    return response.data;
  }

  // Messages
  async getChannelMessages(
    channelId: number, 
    limit: number = 50, 
    beforeId?: number
  ): Promise<{ success: boolean; data: TeamMessage[] }> {
    const params = new URLSearchParams({ limit: limit.toString() });
    if (beforeId) params.append('before_id', beforeId.toString());
    const response = await apiClient.get(`/team-chat/channels/${channelId}/messages?${params}`);
    return response.data;
  }

  async sendMessage(channelId: number, data: SendMessageData): Promise<{ success: boolean; data: TeamMessage }> {
    const response = await apiClient.post(`/team-chat/channels/${channelId}/messages`, data);
    return response.data;
  }

  async editMessage(messageId: number, content: string): Promise<{ success: boolean; data: TeamMessage }> {
    const response = await apiClient.put(`/team-chat/messages/${messageId}`, { content });
    return response.data;
  }

  async deleteMessage(messageId: number): Promise<{ success: boolean; message: string }> {
    const response = await apiClient.delete(`/team-chat/messages/${messageId}`);
    return response.data;
  }

  // Direct Messages
  async sendDirectMessage(data: DirectMessageData): Promise<{ success: boolean; data: { channel_id: number; message: TeamMessage } }> {
    const response = await apiClient.post('/team-chat/direct', data);
    return response.data;
  }

  // Users
  async getTeamUsers(role?: string): Promise<{ success: boolean; data: TeamUser[] }> {
    const params = role ? `?role=${role}` : '';
    const response = await apiClient.get(`/team-chat/users${params}`);
    return response.data;
  }

  // Presence
  async updatePresence(status: 'online' | 'away' | 'busy' | 'offline', customStatus?: string): Promise<{ success: boolean; message: string }> {
    const response = await apiClient.put('/team-chat/presence', { status, custom_status: customStatus });
    return response.data;
  }

  // Department Channels
  async initializeDepartmentChannels(): Promise<{ success: boolean; message: string }> {
    const response = await apiClient.post('/team-chat/departments/init');
    return response.data;
  }

  async joinDepartmentChannel(department: string): Promise<{ success: boolean; data: TeamChannel }> {
    const response = await apiClient.post(`/team-chat/departments/${department}/join`);
    return response.data;
  }
}

export const teamChatService = new TeamChatService();
export default teamChatService;

