import React, {
  Suspense,
  lazy,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import type { Column } from '../../model';
import type { FieldActions } from '../../types/SchemaConfig';
import type { FieldActionPermissions } from '../FieldActions';
import { FieldActionsState } from '../../state/FieldActionsState';

const SidePanelFieldActionsRow = lazy(() =>
  import(
    /* webpackChunkName: "SidePanelFieldActions" */ './SidePanelFieldActionsRow'
  ).then((m) => ({
    default: m.SidePanelFieldActionsRow,
  })),
);

const SidePanelFieldActionsModal = lazy(
  () =>
    import(
      /* webpackChunkName: "SidePanelFieldActions" */ './SidePanelFieldActionsModal'
    ),
);

export interface UseSidePanelFieldActionsResult {
  fieldActionsByColumn: Record<string, ReactNode>;
  fieldActionsModal: ReactNode;
}

export function useSidePanelFieldActions(
  columns: Column[],
  fieldActions?: FieldActions,
  refresh?: () => Promise<void>,
  permissions?: FieldActionPermissions,
): UseSidePanelFieldActionsResult {
  const { translate, showToast } = useWixPatternsContainer();

  const [fieldActionsState] = useState(
    () =>
      new FieldActionsState(
        translate,
        fieldActions,
        permissions,
        showToast,
        refresh,
      ),
  );

  useEffect(() => {
    fieldActionsState.setHandlers(fieldActions);
  }, [fieldActionsState, fieldActions]);

  useEffect(() => {
    fieldActionsState.setPermissions(permissions);
  }, [fieldActionsState, permissions]);

  useEffect(() => {
    fieldActionsState.setRefresh(refresh);
  }, [fieldActionsState, refresh]);

  const fieldActionsByColumn = useMemo(() => {
    const result: Record<string, ReactNode> = {};

    for (const col of columns) {
      result[col.id] = (
        <Suspense fallback={null}>
          <SidePanelFieldActionsRow column={col} state={fieldActionsState} />
        </Suspense>
      );
    }

    return result;
  }, [columns, fieldActionsState]);

  const fieldActionsModal = (
    <Suspense fallback={null}>
      <SidePanelFieldActionsModal state={fieldActionsState} />
    </Suspense>
  );

  return { fieldActionsByColumn, fieldActionsModal };
}
