"use client";

import { createContext, useContext, useMemo, useState, type ReactNode } from "react";
import { ImagePickerDialog, type PickerTab } from "@/components/media/image-picker-dialog";
import type { MediaKind, MediaSelection } from "@/types/media";

interface PickerState {
  open: boolean;
  defaultTab: PickerTab;
  mediaType: MediaKind;
  multiple: boolean;
  onSelect?: (selection: MediaSelection) => void;
}

interface ImagePickerContextValue {
  openPicker: (options: {
    onSelect: (selection: MediaSelection) => void;
    defaultTab?: PickerTab;
    mediaType?: MediaKind;
    multiple?: boolean;
  }) => void;
}

const ImagePickerContext = createContext<ImagePickerContextValue | undefined>(undefined);

interface ImagePickerProviderProps {
  documentId: string;
  workspaceId: string;
  children: ReactNode;
}

export function ImagePickerProvider({ documentId, workspaceId, children }: ImagePickerProviderProps) {
  const [state, setState] = useState<PickerState>({
    open: false,
    defaultTab: "upload",
    mediaType: "image",
    multiple: false,
  });

  const contextValue = useMemo<ImagePickerContextValue>(
    () => ({
      openPicker: ({ onSelect, defaultTab = "upload", mediaType = "image", multiple = false }) => {
        setState({
          open: true,
          onSelect,
          defaultTab,
          mediaType,
          multiple,
        });
      },
    }),
    [],
  );

  const handleClose = () => {
    setState((prev) => ({ ...prev, open: false }));
  };

  const handleSelect = (selection: MediaSelection) => {
    state.onSelect?.(selection);
    if (!state.multiple) {
      setState((prev) => ({ ...prev, open: false }));
    }
  };

  return (
    <ImagePickerContext.Provider value={contextValue}>
      {children}
      <ImagePickerDialog
        open={state.open}
        defaultTab={state.defaultTab}
        mediaType={state.mediaType}
        multiple={state.multiple}
        documentId={documentId}
        workspaceId={workspaceId}
        onClose={handleClose}
        onSelect={handleSelect}
      />
    </ImagePickerContext.Provider>
  );
}

export function useImagePicker() {
  const context = useContext(ImagePickerContext);
  if (!context) {
    throw new Error("useImagePicker 必须在 ImagePickerProvider 中使用");
  }
  return context;
}
