import {Box, TextField, Button, Typography} 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'

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

  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`)
    }
  }, [record])

  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}>
      <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 ? 'Change File' : 'Upload File'}
              <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: 'This field is required',
          })}
          error={!!(errors as any)?.filename}
          helperText={(errors as any)?.filename?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{shrink: true}}
          type="text"
          label="File Name"
          name="filename"
        />

        <TextField
          {...register('media_type', {
            required: 'This field is required',
            valueAsNumber: true,
          })}
          error={!!(errors as any)?.media_type}
          helperText={(errors as any)?.media_type?.message}
          margin="normal"
          fullWidth
          InputLabelProps={{shrink: true}}
          type="number"
          label="Media Type"
          name="media_type"
        />
      </Box>
    </Edit>
  )
}
