import { create } from "zustand";
import { apiClient } from "@/api/client";
import type {
  AckInfo,
  NetworkWithStreams,
  Stream,
  StreamParticle,
} from "@/api/types";

interface AppState {
  networks: NetworkWithStreams[];
  selectedNetworkId: string | null;
  isLoading: boolean;

  fetchStartup: () => Promise<void>;
  setSelectedNetwork: (id: string | null) => void;
  addStream: (networkId: string, stream: Stream) => void;
  addParticleToStream: (streamId: string, particle: StreamParticle) => void;
  markParticlesSeen: (particleIds: string[]) => void;
  ackParticle: (particleId: string, email: string) => void;
}

export const useAppStore = create<AppState>((set, get) => ({
  networks: [],
  selectedNetworkId: null,
  isLoading: false,

  fetchStartup: async () => {
    set({ isLoading: true });
    try {
      const data = await apiClient.startup();
      const state = get();
      const shouldAutoSelect =
        !state.selectedNetworkId && data.networks.length > 0;
      set({
        networks: data.networks,
        ...(shouldAutoSelect
          ? { selectedNetworkId: data.networks[0].id }
          : {}),
      });
    } finally {
      set({ isLoading: false });
    }
  },

  setSelectedNetwork: (id) => {
    set({ selectedNetworkId: id });
  },

  addStream: (networkId, stream) => {
    set({
      networks: get().networks.map((n) =>
        n.id === networkId ? { ...n, streams: [stream, ...n.streams] } : n,
      ),
    });
  },

  addParticleToStream: (streamId, particle) => {
    set({
      networks: get().networks.map((n) => ({
        ...n,
        streams: n.streams.map((s) =>
          s.id === streamId
            ? { ...s, particles: [...s.particles, particle] }
            : s,
        ),
      })),
    });
  },

  ackParticle: (particleId, email) => {
    const ack: AckInfo = { email, acked_at: new Date().toISOString() };
    set({
      networks: get().networks.map((n) => ({
        ...n,
        streams: n.streams.map((s) => ({
          ...s,
          particles: s.particles.map((p) =>
            p.id === particleId ? { ...p, acks: [...p.acks, ack] } : p,
          ),
        })),
      })),
    });
  },

  markParticlesSeen: (particleIds) => {
    const idSet = new Set(particleIds);
    set({
      networks: get().networks.map((n) => ({
        ...n,
        streams: n.streams.map((s) => {
          const unseenMarked = s.particles.filter(
            (p) => !p.seen && idSet.has(p.id),
          ).length;
          if (unseenMarked === 0) return s;
          return {
            ...s,
            unseen_count: Math.max(0, s.unseen_count - unseenMarked),
            particles: s.particles.map((p) =>
              idSet.has(p.id) ? { ...p, seen: true } : p,
            ),
          };
        }),
      })),
    });
  },
}));
