import { create } from "zustand";
import { apiJson, getAccessToken } from "../lib/apiClient";

export interface FriendUser {
  id: string;
  username: string | null;
  displayName: string;
  avatarUrl: string | null;
}

export interface FriendEntry {
  friendshipId: string;
  user: FriendUser;
}

export interface SearchResult extends FriendUser {
  relationship:
    | "none"
    | "pending_out"
    | "pending_in"
    | "friends"
    | "blocked";
}

interface FriendsState {
  friends: FriendEntry[];
  incoming: FriendEntry[];
  outgoing: FriendEntry[];
  loading: boolean;
  load: () => Promise<void>;
  search: (q: string) => Promise<SearchResult[]>;
  sendRequest: (username: string) => Promise<void>;
  accept: (friendshipId: string) => Promise<void>;
  decline: (friendshipId: string) => Promise<void>;
  unfriend: (friendshipId: string) => Promise<void>;
}

export const useFriendsStore = create<FriendsState>((set, get) => ({
  friends: [],
  incoming: [],
  outgoing: [],
  loading: false,

  load: async () => {
    if (!getAccessToken()) {
      set({ friends: [], incoming: [], outgoing: [] });
      return;
    }
    set({ loading: true });
    try {
      const [friendsRes, requestsRes] = await Promise.all([
        apiJson<{ friends: FriendEntry[] }>("/friends"),
        apiJson<{ incoming: FriendEntry[]; outgoing: FriendEntry[] }>(
          "/friends/requests",
        ),
      ]);
      set({
        friends: friendsRes.friends,
        incoming: requestsRes.incoming,
        outgoing: requestsRes.outgoing,
      });
    } finally {
      set({ loading: false });
    }
  },

  search: async (q) => {
    if (!getAccessToken() || q.trim().length < 2) return [];
    const res = await apiJson<{ results: SearchResult[] }>(
      `/friends/search?q=${encodeURIComponent(q.trim())}`,
    );
    return res.results;
  },

  sendRequest: async (username) => {
    await apiJson("/friends/requests", {
      method: "POST",
      body: JSON.stringify({ username }),
    });
    await get().load();
  },

  accept: async (friendshipId) => {
    await apiJson(`/friends/requests/${friendshipId}/accept`, {
      method: "POST",
    });
    await get().load();
  },

  decline: async (friendshipId) => {
    await apiJson(`/friends/requests/${friendshipId}/decline`, {
      method: "POST",
    });
    await get().load();
  },

  unfriend: async (friendshipId) => {
    await apiJson(`/friends/${friendshipId}`, { method: "DELETE" });
    await get().load();
  },
}));
