import { useMemo } from 'react';
import { emit } from '@ablogcms/events';
import BlogSelect from '@features/blog/components/blog-select/blog-select';
import { pending } from '@ablogcms/pending';
import { notify } from '@ablogcms/notify';
import { Button } from '@ablogcms/components/button';
import { Select } from '@ablogcms/components/select';
import type { BulkAction } from '@ablogcms/components/dataview/types';
import { getDataviewBulkActionRegistry } from '@ablogcms/plugins/core';
import { HStack } from '@ablogcms/components/stack';
import type { ModuleType } from '../types';
import { bulkChangeBlog, bulkChangeStatus, bulkDelete, exportModules } from '../api';
import { MODULE_STATUSES } from '../constants';

export interface GetBulkActionsContext {
  invalidate: () => void;
  searchParams: URLSearchParams;
  bulkActions: string[];
}

export interface UseModuleAdminBulkActionsOptions {
  getBulkActions: (bulkActions: BulkAction<ModuleType>[], context: GetBulkActionsContext) => BulkAction<ModuleType>[];
  context: GetBulkActionsContext;
}

export default function useModuleAdminBulkActions({ getBulkActions, context }: UseModuleAdminBulkActionsOptions) {
  const bulkActions = useMemo<BulkAction<ModuleType>[]>(() => {
    const bulkActions: BulkAction<ModuleType>[] = [
      {
        id: 'status',
        label: ACMS.i18n('module_index.bulk_action.status'),
        onAction: async (formData: FormData) => {
          const gateResult = await emit('module.bulk-status.before', { formData });
          if (gateResult.canceled) {
            if (gateResult.reason) {
              notify.danger(gateResult.reason);
            }
            return;
          }
          const end = pending.splash(ACMS.i18n('module_index.bulk_action.feedback.status.pending'));
          try {
            await bulkChangeStatus(gateResult.event.formData);
            context.invalidate();
            notify.info(ACMS.i18n('module_index.bulk_action.feedback.status.success'));
            void emit('module.bulk-status.success', gateResult.event);
          } catch (error) {
            notify.danger(ACMS.i18n('module_index.bulk_action.feedback.status.error'));
            console.error(error);
          } finally {
            end();
          }
        },
        renderForm: () => (
          <>
            <Select name="status">
              {MODULE_STATUSES.map((status) => (
                <option key={status.value} value={status.value}>
                  {status.label}
                </option>
              ))}
            </Select>
            <Button
              type="submit"
              name="ACMS_POST_Module_Index_Status"
              unstyled
              className="acms-admin-btn-admin acms-admin-btn-admin-primary acms-admin-margin-left-mini"
            >
              {ACMS.i18n('module_index.bulk_change')}
            </Button>
          </>
        ),
        condition: () => context.bulkActions.includes('status'),
      },
      {
        id: 'blog',
        label: ACMS.i18n('module_index.bulk_action.blog'),
        onAction: async (formData: FormData) => {
          const end = pending.splash(ACMS.i18n('module_index.bulk_action.feedback.blog.pending'));
          try {
            await bulkChangeBlog(formData);
            context.invalidate();
            notify.info(ACMS.i18n('module_index.bulk_action.feedback.blog.success'));
          } catch (error) {
            notify.danger(ACMS.i18n('module_index.bulk_action.feedback.blog.error'));
            console.error(error);
          } finally {
            end();
          }
        },
        renderForm: () => (
          <div>
            <HStack spacing="0.25rem">
              <div style={{ maxWidth: '100%', width: '220px' }}>
                <BlogSelect name="bid" isClearable={false} scope="loggedInUserBlog" />
              </div>
              <div>
                <Button
                  type="submit"
                  name="ACMS_POST_Module_Index_Blog"
                  unstyled
                  className="acms-admin-btn-admin acms-admin-btn-admin-primary acms-admin-margin-left-mini"
                >
                  {ACMS.i18n('module_index.bulk_change')}
                </Button>
              </div>
            </HStack>
          </div>
        ),
        condition: () => context.bulkActions.includes('status'),
      },
      {
        id: 'export',
        label: ACMS.i18n('module_index.bulk_action.export'),
        onAction: async (formData: FormData) => {
          const end = pending.splash(ACMS.i18n('module_index.bulk_action.feedback.export.pending'));
          try {
            await exportModules(formData);
            notify.info(ACMS.i18n('module_index.bulk_action.feedback.export.success'));
          } catch (error) {
            notify.danger(ACMS.i18n('module_index.bulk_action.feedback.export.error'));
            console.error(error);
          } finally {
            end();
          }
        },
        renderForm: () => (
          <Button
            type="submit"
            name="ACMS_POST_Module_Index_Export"
            unstyled
            className="acms-admin-btn-admin acms-admin-btn-admin-primary"
          >
            {ACMS.i18n('module_index.exec')}
          </Button>
        ),
        condition: () => context.bulkActions.includes('export'),
      },
      {
        id: 'delete',
        label: ACMS.i18n('module_index.bulk_action.delete'),
        onAction: async (formData: FormData) => {
          if (!window.confirm(ACMS.i18n('module_index.bulk_action.feedback.delete.confirm'))) {
            return;
          }
          const end = pending.splash(ACMS.i18n('module_index.bulk_action.feedback.delete.pending'));
          try {
            await bulkDelete(formData);
            context.invalidate();
            notify.info(ACMS.i18n('module_index.bulk_action.feedback.delete.success'));
          } catch (error) {
            notify.danger(ACMS.i18n('module_index.bulk_action.feedback.delete.error'));
            console.error(error);
          } finally {
            end();
          }
        },
        renderForm: () => (
          <div>
            <div>
              <Button
                type="submit"
                name="ACMS_POST_Module_Index_Delete"
                unstyled
                className="acms-admin-btn-admin acms-admin-btn-admin-danger"
              >
                {ACMS.i18n('module_index.exec')}
              </Button>
            </div>
          </div>
        ),
        condition: () => context.bulkActions.includes('delete'),
      },
    ];
    // コア定義 → レジストリ（ctx.dataview.registerBulkAction('module', ...)） → レガシー getter の順にマージする
    const registryBulkActions = Object.values(
      getDataviewBulkActionRegistry().getAll('module')
    ) as BulkAction<ModuleType>[];
    const combinedBulkActions = [...bulkActions, ...registryBulkActions];
    return getBulkActions(combinedBulkActions, context);
  }, [getBulkActions, context]);

  return bulkActions;
}
