import {Autocomplete, Box, TextField} from '@mui/material'
import {Create, useAutocomplete} from '@refinedev/mui'
import {useForm} from '@refinedev/react-hook-form'
import {Controller} from 'react-hook-form'

export const CityCreate = () => {
  const {
    saveButtonProps,
    refineCore: {formLoading},
    register,
    control,
    formState: {errors},
  } = useForm({})

  const {autocompleteProps: countryAutocompleteProps} = useAutocomplete({
    resource: 'country',
  })

  return (
    <Create isLoading={formLoading} saveButtonProps={saveButtonProps}>
      <Box component="form" sx={{display: 'flex', flexDirection: 'column'}} autoComplete="off">
        <Controller
          control={control}
          name="country_code"
          rules={{required: 'Это поле является обязательным'}}
          defaultValue={null}
          render={({field}) => (
            <Autocomplete
              {...countryAutocompleteProps}
              value={countryAutocompleteProps.options.find((option) => option.code === field.value) || null}
              onChange={(_, value) => {
                field.onChange(value?.code || '')
              }}
              getOptionLabel={(item) => {
                return item ? item.code : ''
              }}
              isOptionEqualToValue={(option, value) => {
                return option.id === value?.id
              }}
              renderInput={(params) => <TextField {...params} label="Код страны" margin="normal" variant="outlined" error={!!errors.country_code} helperText={(errors as any)?.country_code?.message} required />}
            />
          )}
        />

        <TextField
          {...register('name', {
            required: 'Это поле является обязательным',
          })}
          error={!!(errors as any)?.name}
          helperText={(errors as any)?.name?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{shrink: true}}
          type="text"
          label={'Название *'}
          name="name"
        />
      </Box>
    </Create>
  )
}
