"use client";

import type { Dispatch, ReactNode } from "react";
import { createActorContext, shallowEqual } from "@xstate/react";
import type { SnapshotFrom } from "xstate";

import type { PrivateZonePostEvent } from "./private-zone-post-events";
import { privateZonePostMachine } from "./private-zone-post-machine";

type Snapshot = SnapshotFrom<typeof privateZonePostMachine>;
const Context = createActorContext(privateZonePostMachine);

export interface PrivateZonePostProviderProps {
  children: ReactNode;
  characterId: string;
}

export function PrivateZonePostProvider({
  children,
  characterId,
}: PrivateZonePostProviderProps) {
  return (
    <Context.Provider options={{ input: { characterId } }}>
      {children}
    </Context.Provider>
  );
}

function selectState(snapshot: Snapshot) {
  return {
    status: String(snapshot.value),
    ...snapshot.context,
    isLoading: snapshot.matches("loading"),
    isLoadingMore: snapshot.matches("loadingMore"),
    isUnlocking: snapshot.matches("unlocking"),
  };
}

export function usePrivateZonePostState() {
  return Context.useSelector(selectState, shallowEqual);
}

export function usePrivateZonePostDispatch(): Dispatch<PrivateZonePostEvent> {
  return Context.useActorRef().send;
}
