import React, { useState, FC } from 'react' import { components, helpers } from '@vtex/address-form' import { PostalCode } from './PostalCode' import { ShippingResult } from './ShippingResult' import { newAddress } from './utils/address' import { CheckoutAddress, Address, DeliveryOption, AddressWithValidation, } from './types' const { AddressContainer, AddressRules, StyleguideInput } = components const { addValidation, removeValidation } = helpers interface CustomProps { canEditData: boolean insertAddress: (address: CheckoutAddress) => Promise selectedAddress: Address deliveryOptions: DeliveryOption[] countries: string[] selectDeliveryOption: (option: string) => void numberOfItems: number numberOfUnavailableItems: number } export const EstimateShipping: FC = ({ canEditData, insertAddress, selectedAddress, deliveryOptions = [], countries = [], selectDeliveryOption, numberOfItems, numberOfUnavailableItems, }) => { const [address, setAddress] = useState( addValidation( selectedAddress ? newAddress(selectedAddress) : newAddress({ country: 'BRA' }) ) ) const [loading, setLoading] = useState(false) const [showResult, setShowResult] = useState( selectedAddress && !!selectedAddress.postalCode ) const handleAddressChange = (updatedAddress: AddressWithValidation) => { setAddress(updatedAddress) } const handleSubmit = () => { const addressWithoutValidation = removeValidation(address) const postalCodeValid = address?.postalCode?.valid if (!postalCodeValid) { return } setLoading(true) insertAddress(addressWithoutValidation).then(() => { setShowResult(true) setLoading(false) }) } return ( {showResult ? ( ) : ( )} ) }