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 CarrierCreate = () => {
  const {
    saveButtonProps,
    refineCore: {formLoading},
    register,
    control,
    formState: {errors},
  } = useForm({})

  const {autocompleteProps: cityAutocompleteProps} = useAutocomplete({
    resource: 'city',
  })

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

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

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