import {Box, TextField} from '@mui/material'
import {Edit} from '@refinedev/mui'
import {useForm} from '@refinedev/react-hook-form'
import {useParams} from 'react-router'
import {LinkedItems} from '../../components/LinkedItems'
import {type SightItem, sightFields} from './types'

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

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

  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('description', {
            // required: 'Это поле является обязательным',
          })}
          error={!!(errors as any)?.description}
          helperText={(errors as any)?.description?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{shrink: true}}
          type="text"
          label={'Описание'}
          name="description"
        />
        <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"
        />
      </Box>

      {stationId && (
        <LinkedItems<SightItem>
          type="edit" // display and manage
          parentId={stationId}
          parentResource="station"
          childResource="sight"
          fields={sightFields}
          title="достопримечательности"
        />
      )}
    </Edit>
  )
}
