'use client'

import { useDropzone } from 'react-dropzone'
import { useTranslations } from 'next-intl'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import { styled } from '@mui/material/styles'
import type { BoxProps } from '@mui/material/Box'
import CustomAvatar from '@core/components/mui/Avatar'
import AppReactDropzone from '@/libs/styles/AppReactDropzone'

export interface UploadedFile {
  file: File
  preview: string
}

interface UploadBoxProps {
  file: UploadedFile | null
  onFileSelect: (file: UploadedFile | null) => void
  onError?: (message: string | null) => void
  error?: string
}

const DropzoneWrapper = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
  '& .dropzone': {
    minHeight: 200,
    padding: theme.spacing(4, 3),
    borderRadius: '16px',
    border: '2px dashed',
    borderColor: 'var(--mui-palette-divider)',
    transition: 'all 0.3s ease',
    '&:hover': {
      borderColor: 'var(--mui-palette-primary-main)',
      backgroundColor: 'var(--mui-palette-primary-lighterOpacity)',
    },
  },
  '& .dropzone.active': {
    borderColor: 'var(--mui-palette-primary-main)',
    backgroundColor: 'var(--mui-palette-primary-lighterOpacity)',
  },
  '& .dropzone.hasFile': {
    borderColor: 'var(--mui-palette-primary-main)',
    minHeight: 'unset',
    padding: theme.spacing(3),
  },
  '& .dropzone.error': {
    borderColor: 'var(--mui-palette-error-main)',
    backgroundColor: 'var(--mui-palette-error-lighterOpacity)',
  },
}))

export default function UploadBox({ file, onFileSelect, onError, error }: UploadBoxProps) {
  const t = useTranslations('pestDetection.upload')
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop: (acceptedFiles) => {
      onError?.(null)
      const validFile = acceptedFiles[0]
      if (validFile) {
        onFileSelect({
          file: validFile,
          preview: URL.createObjectURL(validFile),
        })
      } else {
        onFileSelect(null)
      }
    },
    onDropRejected: () => {
      onError?.(t('invalidFile'))
      onFileSelect(null)
    },
    accept: {
      'image/*': ['.jpeg', '.jpg', '.png', '.gif', '.webp'],
    },
    maxFiles: 1,
    maxSize: 10 * 1024 * 1024, // 10MB
  })

  const handleRemove = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (file) {
      URL.revokeObjectURL(file.preview)
      onFileSelect(null)
    }
  }

  const dropzoneClass = [
    'dropzone',
    isDragActive && 'active',
    file && 'hasFile',
    error && 'error',
  ]
    .filter(Boolean)
    .join(' ')

  return (
    <DropzoneWrapper>
      <div {...getRootProps({ className: dropzoneClass })}>
        <input {...getInputProps()} aria-label={t('ariaLabel')} />
        {file ? (
          <Box className="flex flex-col items-center gap-3 sm:flex-row sm:items-start sm:gap-4">
            <Box
              className="relative shrink-0 overflow-hidden rounded-xl"
              sx={{
                width: { xs: 140, sm: 160 },
                height: { xs: 140, sm: 160 },
                borderRadius: '12px',
                border: '1px solid',
                borderColor: 'divider',
                bgcolor: 'action.hover',
              }}
            >
              <Box
                component="img"
                src={file.preview}
                alt={file.file.name}
                sx={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                }}
              />
            </Box>
            <Box className="flex flex-1 flex-col items-center sm:items-start text-center sm:text-start min-w-0">
              <Typography variant="body2" fontWeight={600} color="text.primary" noWrap sx={{ maxWidth: '100%' }}>
                {file.file.name}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {(file.file.size / 1024).toFixed(1)} KB
              </Typography>
              <Button
                variant="tonal"
                color="error"
                size="small"
                onClick={handleRemove}
                startIcon={<i className="tabler-trash text-base" />}
                className="mt-2"
                sx={{ alignSelf: { sm: 'flex-start' } }}
              >
                {t('remove')}
              </Button>
            </Box>
          </Box>
        ) : (
          <Box className="flex flex-col items-center gap-3 text-center">
            <CustomAvatar
              variant="rounded"
              skin="light"
              color="success"
              className="w-16 h-16"
              sx={{ width: 64, height: 64 }}
            >
              <i className={`${isDragActive ? 'tabler-photo-down' : 'tabler-upload'} text-3xl`} />
            </CustomAvatar>
            <Box>
              <Typography variant="body1" fontWeight={600} color="text.primary">
                {isDragActive ? t('dropHere') : t('dragDrop')}
              </Typography>
              <Typography variant="caption" color="text.secondary" className="mt-1 block">
                {t('fileFormats')}
              </Typography>
            </Box>
            <Button variant="tonal" size="small" color="success">
              {t('dragDrop')}
            </Button>
          </Box>
        )}
      </div>
      {error && (
        <Typography variant="caption" color="error" className="mt-2 block" role="alert">
          {error}
        </Typography>
      )}
    </DropzoneWrapper>
  )
}
