import { Upload, Button, Flex, Typography, Space } from 'antd'
import PropTypes from 'prop-types'
import { ApiServerContext } from '../context/ApiServerContext'
import UploadIcon from '../../Icons/UploadIcon'
import { useContext, useState, useEffect } from 'react'
import ObjectSelect from './ObjectSelect'
import FileList from './FileList'
import PlusIcon from '../../Icons/PlusIcon'

const { Text } = Typography

const FileUpload = ({
  value,
  onChange,
  multiple = true,
  defaultPreviewOpen = false,
  showPreview = true
}) => {
  const { uploadFile } = useContext(ApiServerContext)

  // Track current files using useState
  const [currentFiles, setCurrentFiles] = useState(() => {
    if (multiple) {
      return Array.isArray(value) ? value : []
    } else {
      return value || null
    }
  })

  // Update currentFiles when value prop changes
  useEffect(() => {
    if (multiple) {
      setCurrentFiles(Array.isArray(value) ? value : [])
    } else {
      setCurrentFiles(value || null)
    }
  }, [value, multiple])

  // Track if there are no items in the list
  const [hasNoItems, setHasNoItems] = useState(false)

  // Update hasNoItems when currentFiles changes
  useEffect(() => {
    const noItems = multiple
      ? !currentFiles ||
        !Array.isArray(currentFiles) ||
        currentFiles.length === 0
      : !currentFiles
    setHasNoItems(noItems)
    console.log('No items', noItems)
  }, [currentFiles, multiple])

  const handleFileUpload = async (file) => {
    try {
      const uploadedFile = await uploadFile(file)
      if (uploadedFile) {
        if (multiple) {
          // For multiple files, add to existing array
          const newFiles = [...currentFiles, uploadedFile]
          setCurrentFiles(newFiles)
          onChange(newFiles)
        } else {
          // For single file, replace the value
          setCurrentFiles(uploadedFile)
          onChange(uploadedFile)
        }
      }
    } catch (error) {
      console.error('File upload failed:', error)
    }
    return false // Prevent default upload behavior
  }

  return (
    <Flex gap={'small'} vertical>
      {hasNoItems ? (
        <Flex gap={'small'} align='center'>
          <Space.Compact style={{ flexGrow: 1 }}>
            <ObjectSelect type={'file'} />
            <Button icon={<PlusIcon />} />
          </Space.Compact>
          <Text style={{ whiteSpace: 'nowrap' }} type='secondary'>
            or
          </Text>
          <Upload
            beforeUpload={handleFileUpload}
            showUploadList={false}
            multiple={multiple}
          >
            <Button style={{ width: '100%' }} icon={<UploadIcon />}>
              Upload
            </Button>
          </Upload>
        </Flex>
      ) : null}
      <FileList
        files={currentFiles}
        multiple={multiple}
        editing={true}
        showInfo={false}
        showPreview={showPreview}
        defaultPreviewOpen={defaultPreviewOpen}
        onChange={(updatedFiles) => {
          setCurrentFiles(updatedFiles)
        }}
      />
    </Flex>
  )
}

FileUpload.propTypes = {
  value: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  onChange: PropTypes.func,
  multiple: PropTypes.bool,
  showPreview: PropTypes.string,
  defaultPreviewOpen: PropTypes.bool
}

export default FileUpload
