'use client'

// React Imports
import { useEffect, useState } from 'react'

// MUI Imports
import type { BoxProps } from '@mui/material/Box'
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardHeader from '@mui/material/CardHeader'
import IconButton from '@mui/material/IconButton'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import Typography from '@mui/material/Typography'
import { styled } from '@mui/material/styles'

// Third-party Imports
import { useDropzone } from 'react-dropzone'

// Component Imports
import Link from '@components/Link'
import CustomAvatar from '@core/components/mui/Avatar'

// Styled Component Imports
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
import { useDispatch, useSelector } from 'react-redux'
import { useFilesMutation } from '../../../../../services/mutations/files'
import { setProductField } from '../../../../../redux-store/slices/product'
import { RootState } from '../../../../../redux-store'

type FileProp = {
  name: string
  type: string
  size: number
}

// Styled Dropzone Component
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
  '& .dropzone': {
    minHeight: 'unset',
    padding: theme.spacing(12),
    [theme.breakpoints.down('sm')]: {
      paddingInline: theme.spacing(5)
    },
    '&+.MuiList-root .MuiListItem-root .file-name': {
      fontWeight: theme.typography.body1.fontWeight
    }
  }
}))

const ProductImage = () => {
  const dispatch = useDispatch()
  const { mutate, isPending } = useFilesMutation().uploadFile

  const { image_url } = useSelector((state: RootState) => state.productReducer.productRequest)

  // States
  const [files, setFiles] = useState<File[]>([])

  console.log(files)

  const handleUpload = () => {
    if (!files.length) return

    const formData = new FormData()
    formData.append('file', files[0])
    formData.append('file_type', 'image')
    formData.append('description', 'Product image')

    mutate(formData, {
      onSuccess: data => {
        dispatch(setProductField({ field: 'image_url', value: data.file_url }))
        // Clear the local files after successful upload
        setFiles([])
      }
    })
  }

  // Hooks
  const { getRootProps, getInputProps } = useDropzone({
    onDrop: (acceptedFiles: File[]) => {
      // Replace files instead of adding to them
      setFiles([acceptedFiles[0]]) // Only take the first file
    }
  })

  const renderFilePreview = (file: FileProp) => {
    if (file.type.startsWith('image')) {
      return <img width={38} height={38} alt={file.name} src={URL.createObjectURL(file as any)} />
    } else {
      return <i className='tabler-file-description' />
    }
  }

  const handleRemoveFile = (file: FileProp) => {
    const uploadedFiles = files
    const filtered = uploadedFiles.filter((i: FileProp) => i.name !== file.name)

    setFiles([...filtered])
  }

  const handleRemoveCurrentImage = () => {
    dispatch(setProductField({ field: 'image_url', value: '' }))
  }

  const fileList = files.map((file: FileProp) => (
    <ListItem key={file.name} className='pis-4 plb-3'>
      <div className='file-details'>
        <div className='file-preview'>{renderFilePreview(file)}</div>
        <div>
          <Typography className='file-name font-medium' color='text.primary'>
            {file.name}
          </Typography>
          <Typography className='file-size' variant='body2'>
            {Math.round(file.size / 100) / 10 > 1000
              ? `${(Math.round(file.size / 100) / 10000).toFixed(1)} mb`
              : `${(Math.round(file.size / 100) / 10).toFixed(1)} kb`}
          </Typography>
        </div>
      </div>
      <IconButton onClick={() => handleRemoveFile(file)}>
        <i className='tabler-x text-xl' />
      </IconButton>
    </ListItem>
  ))

  const handleRemoveAllFiles = () => {
    setFiles([])
  }

  return (
    <Dropzone>
      <Card>
        <CardHeader
          title='Product Image'
          action={
            <Typography component={Link} color='primary.main' className='font-medium'>
              Add media from URL
            </Typography>
          }
          sx={{ '& .MuiCardHeader-action': { alignSelf: 'center' } }}
        />
        <CardContent>
          <div {...getRootProps({ className: 'dropzone' })}>
            <input {...getInputProps()} />
            <div className='flex items-center flex-col gap-2 text-center'>
              <CustomAvatar variant='rounded' skin='light' color='secondary'>
                <i className='tabler-upload' />
              </CustomAvatar>
              <Typography variant='h4'>
                {image_url && !files.length ? 'Drop New Image to Replace' : 'Drag and Drop Your Image Here.'}
              </Typography>
              <Typography color='text.disabled'>or</Typography>
              <Button variant='tonal' size='small'>
                Browse Image
              </Button>
            </div>
          </div>
          {/* Show current image if it exists */}
          {image_url && !files.length && (
            <div className='current-image mb-4'>
              <Typography variant='subtitle2' className='mb-2'>
                Current Image:
              </Typography>
              <div className='flex items-center justify-between p-3 border border-gray-200 rounded'>
                <div className='flex items-center gap-3'>
                  <img
                    width={60}
                    height={60}
                    alt='Current product image'
                    src={image_url}
                    className='rounded object-cover'
                  />
                  <div>
                    <Typography className='font-medium' color='text.primary'>
                      Current product image
                    </Typography>
                    <Typography variant='body2' color='text.secondary'>
                      Uploaded image
                    </Typography>
                  </div>
                </div>
                <IconButton onClick={handleRemoveCurrentImage} color='error'>
                  <i className='tabler-x text-xl' />
                </IconButton>
              </div>
            </div>
          )}
          {files.length ? (
            <>
              <List>{fileList}</List>
              <div className='buttons'>
                <Button color='error' variant='tonal' onClick={handleRemoveAllFiles}>
                  Remove All
                </Button>
                <Button variant='contained' onClick={handleUpload} disabled={isPending}>
                  {isPending ? 'Uploading...' : 'Upload'}
                </Button>
              </div>
            </>
          ) : null}
        </CardContent>
      </Card>
    </Dropzone>
  )
}

export default ProductImage
