import React, { useRef, useState, useEffect } from 'react'
import { LoadingDots, ButtonAria, Icon } from '$core-components'
import { t } from '$themelocalization'
import './RecipientListContent.scss'

const VALID_EXTENSIONS = ['.xml', '.xls', '.xlsx', '.mdb', '.accdb', '.csv']
const MOBILE_BREAKPOINT = 575 // $sm breakpoint

const RecipientListContent = ({
  templateUrl,
  uploadedFile,
  isUploading,
  error,
  onUpload,
  onDelete
}) => {
  const fileInputRef = useRef(null)
  const [isDragOver, setIsDragOver] = useState(false)
  const [isMobileView, setIsMobileView] = useState(window.innerWidth < MOBILE_BREAKPOINT)

  useEffect(() => {
    const handleResize = () => {
      setIsMobileView(window.innerWidth < MOBILE_BREAKPOINT)
    }
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  const handleBrowseClick = () => {
    fileInputRef.current?.click()
  }

  const handleFileChange = (event) => {
    const file = event.target.files[0]
    if (file) {
      onUpload(file)
    }
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  const handleDragOver = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (!isMobileView && !isUploading) {
      setIsDragOver(true)
    }
  }

  const handleDragLeave = (e) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragOver(false)
  }

  const handleDrop = (e) => {
    const files = e.dataTransfer?.files
    const file = files?.[0]

    e.preventDefault()
    e.stopPropagation()
    setIsDragOver(false)

    if (isMobileView || isUploading) return

    if (file) {
      onUpload(file)
    }
  }

  const getAcceptedExtensions = () => VALID_EXTENSIONS.join(',')

  const getErrorMessage = () => {
    if (!error) return null

    if (error === 'UNSUPPORTED_FORMAT') {
      return t('RecipientList.Error.UnsupportedFormat')
    }
    if (error.type === 'TEMPLATE_MISMATCH') {
      return t('RecipientList.Error.TemplateMismatch', { fileName: error.fileName })
    }
    if (error.type === 'API_ERROR') {
      return error.message
    }
    if (error === 'REQUIRED') {
      return t('RecipientList.Error.Required')
    }
    if (error === 'UPLOAD_FAILED') {
      return t('RecipientList.Error.UploadFailed')
    }
    return null
  }

  const hasError = !!error || (uploadedFile && uploadedFile.IsActive === false)
  const errorMessage = getErrorMessage()
  const hasActiveFile = !!uploadedFile?.FileUrl

  return (
    <div className="recipient-list-content">
      {templateUrl && !hasActiveFile && (
        <a
          href={templateUrl}
          className="recipient-list-download-template"
          download
          title={t('RecipientList.DownloadTemplate')}
        >
          <Icon name="download.svg" width="16px" height="16px" title={t('RecipientList.DownloadTemplate')} />
          <span>{t('RecipientList.DownloadTemplate')}</span>
        </a>
      )}
      {!hasActiveFile && (
        <>
          {isMobileView ? (
            <div className="recipient-list-mobile">
              <input
                ref={fileInputRef}
                type="file"
                className="recipient-list-file-input"
                onChange={handleFileChange}
                accept={getAcceptedExtensions()}
                disabled={isUploading}
              />
              <ButtonAria
                className={`button recipient-list-upload-button ${hasError ? 'has-error' : ''}`}
                onClick={handleBrowseClick}
                disabled={isUploading}
              >
                {isUploading ? (
                  <LoadingDots />
                ) : (
                  <>
                    <Icon name="upload.svg" width="16px" height="16px" />
                    <span>{t('RecipientList.UploadFile')}</span>
                  </>
                )}
              </ButtonAria>
              <div className="recipient-list-supported-files">
                {t('RecipientList.SupportedFiles')}
              </div>
            </div>
          ) : (
            /* Desktop: Drag & drop zone */
            <>
              <div
                className={`recipient-list-dropzone ${isDragOver ? 'drag-over' : ''} ${hasError ? 'has-error' : ''}`}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
              >
                {isUploading ? (
                  <div className="recipient-list-uploading">
                    <LoadingDots />
                  </div>
                ) : (
                  <>
                    <input
                      ref={fileInputRef}
                      type="file"
                      className="recipient-list-file-input"
                      onChange={handleFileChange}
                      accept={getAcceptedExtensions()}
                    />
                    <div className="recipient-list-dropzone-content">
                      <span className="recipient-list-drag-text">
                        {t('RecipientList.DragAndDrop')}
                      </span>
                      <ButtonAria
                        className="button recipient-list-upload-button"
                        onClick={handleBrowseClick}
                      >
                        <Icon name="upload.svg" width="16px" height="16px" />
                        <span>{t('RecipientList.UploadFile')}</span>
                      </ButtonAria>
                    </div>
                  </>
                )}
              </div>
              <div className="recipient-list-supported-files">
                {t('RecipientList.SupportedFiles')}
              </div>
            </>
          )}
        </>
      )}
      {errorMessage && (
        <div className="recipient-list-error">
          {errorMessage}
        </div>
      )}
      {uploadedFile && (
        <div className={`recipient-list-file-info ${!uploadedFile.IsActive ? 'deleted' : ''}`}>
          {uploadedFile.IsActive && uploadedFile.FileUrl ? (
            <a
              href={uploadedFile.FileUrl}
              className="recipient-list-file-download"
              download
              title={uploadedFile.FileName}
            >
              <Icon name="download.svg" width="16px" height="16px" title={uploadedFile.FileName} />
              <span className="recipient-list-file-name">
                {uploadedFile.FileName}
              </span>
            </a>
          ) : (
            <span className="recipient-list-file-name" title={uploadedFile.FileName}>
              {uploadedFile.FileName}
            </span>
          )}
          <span className="recipient-list-recipients-count">
            ({uploadedFile.NumberOfRecipients} {t('RecipientList.Recipients')})
          </span>
          {uploadedFile.IsActive === false && (
            <span className="recipient-list-deleted-message">
              - {t('RecipientList.DeletedByPolicy')}
            </span>
          )}
          {uploadedFile.IsActive && (
            <button
              className="recipient-list-delete-button"
              onClick={onDelete}
              type="button"
              aria-label="Delete"
            >
              <Icon name="cart_delete.svg" width="16px" height="16px" />
            </button>
          )}
        </div>
      )}
    </div>
  )
}

export default RecipientListContent
