import { create } from 'zustand';
import { api } from '@/lib/api';
import type {
  FriendListItem,
  PendingReceivedItem,
  PendingSentItem,
  SocialNotification,
} from '@/types/social';
import type { PaginationMeta } from '@/types/api';

interface OnlineFriend {
  userId: string;
  name: string | null;
  email: string;
}

interface SocialState {
  // Friends
  friends: FriendListItem[];
  friendsPagination: PaginationMeta | null;
  pendingReceived: PendingReceivedItem[];
  pendingSent: PendingSentItem[];

  // Online presence
  onlineFriends: OnlineFriend[];

  // Notifications
  unreadNotificationCount: number;
  notifications: SocialNotification[];
  notificationsPagination: PaginationMeta | null;

  // Loading states
  loadingFriends: boolean;
  loadingNotifications: boolean;

  // Actions
  fetchFriends: (page?: number) => Promise<void>;
  fetchPendingReceived: () => Promise<void>;
  fetchPendingSent: () => Promise<void>;
  sendFriendRequest: (userId: string) => Promise<void>;
  acceptRequest: (friendshipId: number) => Promise<void>;
  declineRequest: (friendshipId: number) => Promise<void>;
  cancelRequest: (friendshipId: number) => Promise<void>;
  unfriend: (friendId: string) => Promise<void>;
  blockUser: (userId: string) => Promise<void>;
  unblockUser: (userId: string) => Promise<void>;
  fetchUnreadCount: () => Promise<void>;
  fetchNotifications: (page?: number) => Promise<void>;
  markNotificationRead: (id: number) => Promise<void>;
  markAllNotificationsRead: () => Promise<void>;
  fetchOnlineFriends: () => Promise<void>;
}

export const useSocialStore = create<SocialState>((set, get) => ({
  friends: [],
  friendsPagination: null,
  pendingReceived: [],
  pendingSent: [],
  onlineFriends: [],
  unreadNotificationCount: 0,
  notifications: [],
  notificationsPagination: null,
  loadingFriends: false,
  loadingNotifications: false,

  fetchFriends: async (page = 1) => {
    set({ loadingFriends: true });
    try {
      const { data } = await api.get('/social/friends', { params: { page, limit: 20 } });
      set({ friends: data.friends, friendsPagination: data.pagination, loadingFriends: false });
    } catch {
      set({ loadingFriends: false });
    }
  },

  fetchPendingReceived: async () => {
    try {
      const { data } = await api.get('/social/friends/pending/received');
      set({ pendingReceived: data.requests });
    } catch {}
  },

  fetchPendingSent: async () => {
    try {
      const { data } = await api.get('/social/friends/pending/sent');
      set({ pendingSent: data.requests });
    } catch {}
  },

  sendFriendRequest: async (userId: string) => {
    await api.post('/social/friends/request', { userId });
    // Refresh pending sent
    get().fetchPendingSent();
  },

  acceptRequest: async (friendshipId: number) => {
    await api.post(`/social/friends/${friendshipId}/accept`);
    get().fetchPendingReceived();
    get().fetchFriends();
  },

  declineRequest: async (friendshipId: number) => {
    await api.post(`/social/friends/${friendshipId}/decline`);
    get().fetchPendingReceived();
  },

  cancelRequest: async (friendshipId: number) => {
    await api.delete(`/social/friends/${friendshipId}/cancel`);
    get().fetchPendingSent();
  },

  unfriend: async (friendId: string) => {
    await api.delete(`/social/friends/${friendId}`);
    get().fetchFriends();
  },

  blockUser: async (userId: string) => {
    await api.post('/social/blocks', { userId });
    get().fetchFriends(); // Refresh since blocking auto-unfriends
  },

  unblockUser: async (userId: string) => {
    await api.delete(`/social/blocks/${userId}`);
  },

  fetchUnreadCount: async () => {
    try {
      const { data } = await api.get('/social/notifications/count');
      set({ unreadNotificationCount: data.count });
    } catch {}
  },

  fetchNotifications: async (page = 1) => {
    set({ loadingNotifications: true });
    try {
      const { data } = await api.get('/social/notifications', { params: { page, limit: 20 } });
      set({
        notifications: data.notifications,
        notificationsPagination: data.pagination,
        loadingNotifications: false,
      });
    } catch {
      set({ loadingNotifications: false });
    }
  },

  markNotificationRead: async (id: number) => {
    await api.post(`/social/notifications/${id}/read`);
    set((state) => ({
      notifications: state.notifications.map((n) =>
        n.id === id ? { ...n, isRead: true, readAt: new Date().toISOString() } : n,
      ),
      unreadNotificationCount: Math.max(0, state.unreadNotificationCount - 1),
    }));
  },

  markAllNotificationsRead: async () => {
    await api.post('/social/notifications/read-all');
    set((state) => ({
      notifications: state.notifications.map((n) => ({
        ...n,
        isRead: true,
        readAt: n.readAt || new Date().toISOString(),
      })),
      unreadNotificationCount: 0,
    }));
  },

  fetchOnlineFriends: async () => {
    try {
      const { data } = await api.get('/social/sse/online-friends');
      set({ onlineFriends: data.friends });
    } catch {}
  },
}));
