import { createContext, useContext } from "react";
import type { ProfilePickerProps } from "@/components/ui/profile-picker/profile-picker";
import type { AppRouterOutput } from "@/lib/trpc/router";

export type Profile = AppRouterOutput["profile"]["paginate"]["items"][number];

export type ProfilePickerPickParams = Pick<ProfilePickerProps, "multiple" | "personal" | "selected" | "autosubmit" | "onCreate"> & {
    editId?: string;
};

export type ProfilePickerEvents = {
    create: { profile: Profile };
    select: { selected: string[] };
};

export type ProfilePickerEventType = keyof ProfilePickerEvents;

export type ProfilePickerEventHandler<T extends ProfilePickerEventType> = (payload: ProfilePickerEvents[T]) => void;

export type ProfilePickerContextType = {
    pick: (params: ProfilePickerPickParams) => Promise<string[]>;
    edit: (id: string) => Promise<string[]>;
    on: <T extends ProfilePickerEventType>(event: T, handler: ProfilePickerEventHandler<T>) => void;
    off: <T extends ProfilePickerEventType>(event: T, handler: ProfilePickerEventHandler<T>) => void;
    emit: <T extends ProfilePickerEventType>(event: T, payload: ProfilePickerEvents[T]) => void;
};

export const ProfilePickerContext = createContext<ProfilePickerContextType>({
    async pick() {
        return [];
    },
    async edit() {
        return [];
    },
    on() {},
    off() {},
    emit() {},
});

export const useProfilePicker = () => useContext(ProfilePickerContext);
