import { FormEvent, useMemo, useState } from 'react' import { __ } from '@wordpress/i18n' import { resolveSelect, useDispatch, useSelect } from '@wordpress/data' import apiFetch from '@wordpress/api-fetch' import Select from 'react-select' import classNames from 'classnames' import { store } from '../../../../store/backend' import { Label } from '../../../components/Form/Fields/Label/Label' import { formatOptions } from '../../../components/Form/Fields/GenericSelectField/utils' import { IOption } from '../../../components/Form/types' import { Button } from '../../../components/Button/Button' import { getAdminSelectStyles } from '../../../utils/adminSelectStyles' import closeIcon from '../../../../../public/images/icon-close.svg' import { GrantPackageFormProps, PackageProductItem } from './types' import './GrantPackageForm.scss' const selectStyles = getAdminSelectStyles() export const GrantPackageForm = ({ onDone }: GrantPackageFormProps) => { const { setToastNotification, invalidateResolution } = useDispatch(store) const [productId, setProductId] = useState('') const [userId, setUserId] = useState('') const [busy, setBusy] = useState(false) const [showValidation, setShowValidation] = useState(false) const [productFocused, setProductFocused] = useState(false) const [userFocused, setUserFocused] = useState(false) const products = useSelect( (select) => select(store).getItems('package_products') || [], [] ) as PackageProductItem[] const userFieldOptions = useSelect( (select) => select(store).getFieldOptions('customer_packages', 'user_id', []), [] ) const usersLoading = useSelect( (select) => select(store).getFieldLoading('customer_packages', 'user_id'), [] ) const productOptions = useMemo( () => products .filter((product) => product?.id && product?.name) .map((product) => ({ value: String(product.id), label: product.name, })), [products] ) const userOptions = useMemo( () => formatOptions(userFieldOptions || {}), [userFieldOptions] ) const selectedProduct = productOptions.find((option) => option.value === productId) || null const selectedUser = userOptions.find((option) => option.value === userId) || null const productMissing = showValidation && !productId const userMissing = showValidation && !userId const submit = async (event?: FormEvent) => { event?.preventDefault() if (!productId || !userId) { setShowValidation(true) return } setBusy(true) try { await apiFetch({ path: '/wbk/v2/grant-package/', method: 'POST', data: { product_id: Number(productId), user_id: Number(userId), }, }) invalidateResolution('getItems', ['customer_packages']) await resolveSelect(store).getItems('customer_packages') setToastNotification({ type: 'success', message: __('Package granted.', 'webba-booking-lite'), }) onDone() } catch (error: any) { setToastNotification({ type: 'error', message: error?.message || error?.description || __('Could not grant package.', 'webba-booking-lite'), }) } finally { setBusy(false) } } return (
{__('Grant package', 'webba-booking-lite')}
) }