import { useState, useCallback } from 'react';
import { useDelete } from '@refinedev/core';
import { notification } from 'antd';

export interface BatchDeleteResult {
  successIds: React.Key[];
  failedIds: React.Key[];
  successCount: number;
  failedCount: number;
}

export interface UseBatchDeleteConfig {
  resourceName: string;
  /** Called after all deletes complete (regardless of success/failure) */
  onComplete?: (result: BatchDeleteResult) => void;
  /** Called only when at least one delete succeeds */
  onSuccess?: (result: BatchDeleteResult) => void;
  /** Called only when at least one delete fails */
  onError?: (result: BatchDeleteResult) => void;
  /** i18n translation function */
  t?: (key: string, defaultValue?: string) => string;
  /** Whether to show notification (default: true) */
  showNotification?: boolean;
  /** Custom notification handler - if provided, replaces default notification */
  customNotification?: (result: BatchDeleteResult) => void;
  /** Custom delete function - if provided, replaces default refine useDelete */
  customDeleteFn?: (id: number) => Promise<void>;
  /** Confirmation handler - return true to proceed, false to cancel */
  confirmDelete?: (selectedKeys: React.Key[]) => Promise<boolean>;
}

export interface UseBatchDeleteResult {
  /** Delete selected items and return failed IDs */
  deleteSelectedItems: (selectedKeys: React.Key[]) => Promise<React.Key[]>;
  /** Delete a single item */
  deleteOne: (id: number) => Promise<void>;
  /** Loading state */
  deleteManyIsLoading: boolean;
}

/**
 * Hook for batch deleting selected items
 *
 * @example
 * // Basic usage
 * const { deleteSelectedItems, deleteManyIsLoading } = useBatchDelete({
 *   resourceName: 'audit',
 * });
 *
 * @example
 * // With custom confirmation
 * const { deleteSelectedItems } = useBatchDelete({
 *   resourceName: 'audit',
 *   confirmDelete: async (keys) => {
 *     return await myConfirmDialog(`Delete ${keys.length} items?`);
 *   },
 * });
 *
 * @example
 * // With custom notification
 * const { deleteSelectedItems } = useBatchDelete({
 *   resourceName: 'audit',
 *   showNotification: false,
 *   onComplete: (result) => {
 *     toast.info(`Deleted ${result.successCount} items`);
 *   },
 * });
 */
export function useBatchDelete({
  resourceName,
  onComplete,
  onSuccess,
  onError,
  t = (key, defaultValue) => defaultValue || key,
  showNotification = true,
  customNotification,
  customDeleteFn,
  confirmDelete,
}: UseBatchDeleteConfig): UseBatchDeleteResult {
  const [deleteManyIsLoading, setDeleteManyIsLoading] = useState(false);
  const { mutate: refineDeleteOne } = useDelete();

  const deleteOne = useCallback(
    (id: number): Promise<void> => {
      if (customDeleteFn) {
        return customDeleteFn(id);
      }

      return new Promise((resolve, reject) =>
        refineDeleteOne(
          {
            resource: resourceName,
            id,
            successNotification: false,
            errorNotification: false,
          },
          {
            onError: (error) => {
              console.error('deleteOne error:', error);
              reject(error);
            },
            onSuccess: () => {
              resolve();
            },
          },
        ),
      );
    },
    [refineDeleteOne, resourceName, customDeleteFn],
  );

  const deleteSelectedItems = useCallback(
    async (selectedKeys: React.Key[]): Promise<React.Key[]> => {
      // Confirmation check
      if (confirmDelete) {
        const confirmed = await confirmDelete(selectedKeys);
        if (!confirmed) {
          return selectedKeys; // Return all keys as "not deleted"
        }
      }

      setDeleteManyIsLoading(true);

      const successIds: React.Key[] = [];
      const failedIds: React.Key[] = [];

      for (const id of selectedKeys) {
        try {
          await deleteOne(Number(id));
          successIds.push(id);
        } catch {
          failedIds.push(id);
        }
      }

      setDeleteManyIsLoading(false);

      const result: BatchDeleteResult = {
        successIds,
        failedIds,
        successCount: successIds.length,
        failedCount: failedIds.length,
      };

      // Callbacks
      onComplete?.(result);
      if (result.successCount > 0) {
        onSuccess?.(result);
      }
      if (result.failedCount > 0) {
        onError?.(result);
      }

      // Notification
      if (customNotification) {
        customNotification(result);
      } else if (showNotification) {
        const message = t(
          'batch.deleteResult',
          `Delete success: ${result.successCount}, failed: ${result.failedCount}`,
        );

        if (result.failedCount === selectedKeys.length) {
          notification.error({ message });
        } else if (result.failedCount > 0) {
          notification.warning({ message });
        } else {
          notification.success({ message });
        }
      }

      return failedIds;
    },
    [
      deleteOne,
      onComplete,
      onSuccess,
      onError,
      t,
      showNotification,
      customNotification,
      confirmDelete,
    ],
  );

  return {
    deleteSelectedItems,
    deleteOne,
    deleteManyIsLoading,
  };
}
