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

type Medias = AppRouterOutput["media"]["createMany"];
export type Media = Medias[number];

export type MediaPickerPickParams = Pick<MediaPickerProps, "multiple" | "autosubmit" | "mimeType" | "scope" | "acceptedFileTypes" | "selected" | "withAttachments" | "defaultAttached" | "onCreate">;

export type MediaPickerEvents = {
    createMany: { medias: Media[] };
    attach: { attached: string[] };
};

export type MediaPickerEventType = keyof MediaPickerEvents;

export type MediaPickerEventHandler<T extends MediaPickerEventType> = (payload: MediaPickerEvents[T]) => void;

export type MediaPickerContextTepe = {
    attached: string[];
    pick: (params: MediaPickerPickParams) => Promise<string[]>;
    setAttached: (ids: string[]) => void;
    attach: (ids: string[]) => void;
    on: <T extends MediaPickerEventType>(event: T, handler: MediaPickerEventHandler<T>) => void;
    off: <T extends MediaPickerEventType>(event: T, handler: MediaPickerEventHandler<T>) => void;
    emit: <T extends MediaPickerEventType>(event: T, payload: MediaPickerEvents[T]) => void;
};

export const MediaPickerContext = createContext<MediaPickerContextTepe>({
    attached: [],
    async pick() {
        return [];
    },
    setAttached() {},
    attach() {},
    on() {},
    off() {},
    emit() {},
});

export const useMediaPicker = () => useContext(MediaPickerContext);
