import {Autocomplete, Box, TextField} from '@mui/material'
import {Edit, useAutocomplete} from '@refinedev/mui'
import {useForm} from '@refinedev/react-hook-form'
import {Controller} from 'react-hook-form'
import {useParams} from 'react-router'
import {LinkedItems} from '../../components/LinkedItems'
import {ArticleItem, articleFields} from './types'

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

  const {id: sightId} = useParams<{id: string}>()

  const {autocompleteProps: cityAutocompleteProps} = useAutocomplete({
    resource: 'city',
    onSearch: (value) => [
      {
        field: 'name',
        operator: 'contains',
        value,
      },
    ],
  })

  return (
    <Edit saveButtonProps={saveButtonProps}>
      <Box component="form" sx={{display: 'flex', flexDirection: 'column'}} autoComplete="off">
        <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"
        />
        <TextField
          {...register('latitude', {
            required: 'Это поле является обязательным',
            valueAsNumber: true,
          })}
          error={!!(errors as any)?.latitude}
          helperText={(errors as any)?.latitude?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{shrink: true}}
          type="number"
          label={'Широта *'}
          name="latitude"
        />
        <TextField
          {...register('longitude', {
            required: 'Это поле является обязательным',
            valueAsNumber: true,
          })}
          error={!!(errors as any)?.longitude}
          helperText={(errors as any)?.longitude?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{shrink: true}}
          type="number"
          label={'Долгота *'}
          name="longitude"
        />

        <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
              }}
              filterOptions={(options, {inputValue}) => {
                return options.filter((option) => option.name.toLowerCase().includes(inputValue.toLowerCase()))
              }}
              renderInput={(params) => <TextField {...params} label="Выберите город" margin="normal" variant="outlined" error={!!errors.city_id} helperText={(errors as any)?.city_id?.message} required />}
            />
          )}
        />
      </Box>
      {sightId && <LinkedItems<ArticleItem> type="edit" parentId={sightId} parentResource="sight" childResource="article" fields={articleFields} title="статьи" />}
    </Edit>
  )
}
