import { ButtonAccess, SafeModal } from '@/components';
import { useIntl } from '@@/exports';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { message, Modal } from 'antd';
import { useState } from 'react';
import { BizDestroyProps } from './typing';

export default function BizDestroy<
	BizVO extends Record<string, any>,
	Func extends Record<string, any>,
>(props: BizDestroyProps<BizVO, Func>) {
	const {
		row,
		permission,
		rowId,
		rowKey,
		intlPrefix,
		onFinish,
		methodUpper,
		func,
		disable,
		positionKey,
	} = props;

	const intl = useIntl();
	const [openSafeModal, setOpenSafeModal] = useState<boolean>(false);

	const destroy = (rowId?: any) => {
		Modal.confirm({
			title: intl.formatMessage({
				id: intlPrefix + '.modal.delete.confirm.title',
			}),
			icon: <ExclamationCircleFilled />,
			content: intl.formatMessage({
				id: intlPrefix + '.modal.delete.confirm.content',
			}),
			okText: intl.formatMessage({
				id: intlPrefix + '.modal.delete.confirm.okText',
			}),
			okType: 'danger',
			cancelText: intl.formatMessage({
				id: intlPrefix + '.modal.delete.confirm.cancelText',
			}),
			onOk: async () => {
				const { success, errCode } = await func?.[`destroy${methodUpper}`]({
					[`${rowKey}`]: rowId,
				});

				if (success) {
					if (errCode === '401') {
						setOpenSafeModal(true);
						return false;
					} else {
						message.success(
							intl.formatMessage({ id: intlPrefix + '.modal.delete.success' }),
						);
					}
				}

				onFinish?.();

				return true;
			},
			onCancel() {},
		});
	};

	return (
		<>
			<SafeModal
				open={openSafeModal}
				onVisibleChange={(openSafeModal) => setOpenSafeModal(openSafeModal)}
			/>

			<ButtonAccess
				key={'delete'}
				permission={permission + '-delete'}
				danger={true}
				type={'link'}
				disabled={disable?.(row)}
				onClick={(event) => {
					destroy(rowId);
					event.stopPropagation();
				}}
				positionKey={positionKey}
			>
				{intl.formatMessage({
					id: intlPrefix + '.modal.delete.button',
				})}
			</ButtonAccess>
		</>
	);
}
