import { useState, useCallback } from 'react';
import { message } from 'antd';
import type { ApprovalParams } from '@rent/shared-types';

interface UseApprovalOptions {
  approveFn: (params: ApprovalParams) => Promise<void>;
  onSuccess?: () => void;
}

interface UseApprovalReturn {
  approving: boolean;
  handleApprove: (id: number) => Promise<void>;
  handleReject: (id: number, reason: string) => Promise<void>;
}

/**
 * 审核操作Hook
 * 统一处理审核通过、拒绝的逻辑
 */
export function useApproval(options: UseApprovalOptions): UseApprovalReturn {
  const { approveFn, onSuccess } = options;
  const [approving, setApproving] = useState(false);

  const handleApprove = useCallback(
    async (id: number) => {
      setApproving(true);
      try {
        await approveFn({ id, action: 'approve' });
        message.success('审核通过');
        onSuccess?.();
      } catch (error: any) {
        message.error(error.message || '审核失败');
      } finally {
        setApproving(false);
      }
    },
    [approveFn, onSuccess]
  );

  const handleReject = useCallback(
    async (id: number, reason: string) => {
      if (!reason || !reason.trim()) {
        message.warning('请输入拒绝原因');
        return;
      }

      setApproving(true);
      try {
        await approveFn({ id, action: 'reject', rejectReason: reason });
        message.success('已拒绝');
        onSuccess?.();
      } catch (error: any) {
        message.error(error.message || '操作失败');
      } finally {
        setApproving(false);
      }
    },
    [approveFn, onSuccess]
  );

  return {
    approving,
    handleApprove,
    handleReject,
  };
}
