import {Box, TextField, Button, Typography, FormControl, InputLabel, Select, MenuItem} from '@mui/material'
import {Edit} from '@refinedev/mui'
import {useForm} from '@refinedev/react-hook-form'
import {useState, useEffect} from 'react'
import {useShow} from '@refinedev/core'

import {MEDIA_TYPES} from '../../lib/constants'

type MediaFormValues = {
  filename: string
  media_type: number
  file?: File
}

export const MediaEdit = () => {
  const {
    saveButtonProps,
    refineCore: {onFinish},
    register,
    formState: {errors},
    setValue,
    handleSubmit,
  } = useForm<MediaFormValues>({
    defaultValues: {
      filename: '',
      media_type: '',
      file: undefined,
    },
  })

  const {query} = useShow()
  const {data} = query
  const record = data?.data

  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)

  useEffect(() => {
    if (record?.id) {
      setPreviewUrl(`https://wn.krbl.ru/media/${record.id}/download`)
      setValue('filename', record?.filename || '')
      setValue('media_type', record?.media_type)
    }
  }, [record, setValue])

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setValue('file', file)
      setSelectedFile(file)

      if (file.type.startsWith('image/')) {
        const url = URL.createObjectURL(file)
        setPreviewUrl(url)
      }
    }
  }

  return (
    <Edit
      saveButtonProps={{
        ...saveButtonProps,
        onClick: handleSubmit((data) => {
          const formData = {
            filename: data.filename,
            type: Number(data.media_type),
          }

          onFinish(formData)
        }),
      }}
    >
      <Box component="form" sx={{display: 'flex', flexDirection: 'column'}} autoComplete="off">
        <Box display="flex" flexDirection="column-reverse" alignItems="center" gap={6}>
          <Box display="flex" alignItems="center" gap={2}>
            <Button variant="contained" component="label">
              {selectedFile ? 'Изменить файл' : 'Загрузить файл'}
              <input type="file" hidden onChange={handleFileChange} />
            </Button>

            {selectedFile && (
              <Typography variant="body2" color="text.secondary">
                {selectedFile.name}
              </Typography>
            )}
          </Box>

          {previewUrl && (
            <Box mt={2} display="flex" justifyContent="center">
              <img src={previewUrl} alt="Preview" style={{maxWidth: '200px', borderRadius: 8}} />
            </Box>
          )}
        </Box>

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

        <FormControl fullWidth margin="normal" error={!!errors.media_type}>
          <InputLabel id="media-type-label">Тип</InputLabel>
          <Select
            labelId="media-type-label"
            label="Тип"
            {...register('media_type', {
              required: 'Это поле является обязательным',
              valueAsNumber: true,
            })}
            defaultValue=""
          >
            {MEDIA_TYPES.map((option) => (
              <MenuItem key={option.value} value={option.value}>
                {option.label}
              </MenuItem>
            ))}
          </Select>

          {errors.media_type && (
            <Typography variant="caption" color="error">
              {(errors as any)?.message}
            </Typography>
          )}
        </FormControl>
      </Box>
    </Edit>
  )
}
