import { Card, Flex, Typography, Button, Tag, Divider } from 'antd'
import PropTypes from 'prop-types'
import FileIcon from '../../Icons/FileIcon'
import BinIcon from '../../Icons/BinIcon'
import EyeIcon from '../../Icons/EyeIcon'
import DownloadIcon from '../../Icons/DownloadIcon'
import { useContext, useState } from 'react'
import { ApiServerContext } from '../context/ApiServerContext'
import FilePreview from './FilePreview'
import EyeSlashIcon from '../../Icons/EyeSlashIcon'
import { getModelByName } from '../../../database/ObjectModels'
import InfoCircleIcon from '../../Icons/InfoCircleIcon'
import { useNavigate } from 'react-router-dom'

const { Text } = Typography

const FileList = ({
  files,
  onChange,
  multiple = true,
  editing = false,
  showPreview = true,
  showInfo = true,
  showDownload = true,
  defaultPreviewOpen = false
}) => {
  const { fetchFileContent } = useContext(ApiServerContext)
  const navigate = useNavigate()
  const [previewOpen, setPreviewOpen] = useState(defaultPreviewOpen)
  const infoAction = getModelByName('file').actions.filter(
    (action) => action.name == 'info'
  )[0]
  // Check if there are no items in the list
  const hasNoItems = multiple
    ? !files || !Array.isArray(files) || files.length === 0
    : !files

  if (hasNoItems) {
    return null
  }

  const handleRemove = (fileToRemove) => {
    if (multiple) {
      const currentFiles = Array.isArray(files) ? files : []
      const updatedFiles = currentFiles.filter((file) => {
        const fileUid = file._id || file.id
        const removeUid = fileToRemove._id || fileToRemove.id
        return fileUid !== removeUid
      })
      onChange(updatedFiles)
    } else {
      onChange(null)
    }
  }

  const handleDownload = async (file) => {
    await fetchFileContent(file, true)
  }

  const filesToRender = multiple ? files : [files]

  return (
    <div style={{ width: '100%' }}>
      {filesToRender.map((file, index) => (
        <Card
          styles={{ body: { padding: '10px' } }}
          key={file._id || file.id || index}
          style={{
            marginTop: index > 0 && multiple ? '4px' : undefined
          }}
        >
          <Flex vertical gap='10px'>
            <Flex justify='space-between'>
              <Flex gap={'small'} align='center'>
                <FileIcon style={{ margin: 0, fontSize: '24px' }} />

                <Text>{file.name || file.filename || 'Unknown file'}</Text>
                <Tag>{file.extension}</Tag>
              </Flex>
              <Flex gap={'small'} align='center'>
                {showDownload && (
                  <Button
                    icon={<DownloadIcon />}
                    size='small'
                    type='text'
                    onClick={() => handleDownload(file)}
                  />
                )}
                {showPreview && (
                  <Button
                    icon={previewOpen ? <EyeSlashIcon /> : <EyeIcon />}
                    size='small'
                    type='text'
                    onClick={() => {
                      if (previewOpen == true) {
                        setPreviewOpen(false)
                      } else {
                        setPreviewOpen(true)
                      }
                    }}
                  />
                )}
                {showInfo && (
                  <Button
                    icon={<InfoCircleIcon />}
                    size='small'
                    type='text'
                    onClick={() => {
                      navigate(infoAction.url(file._id))
                    }}
                  />
                )}
                {editing && (
                  <Button
                    icon={<BinIcon />}
                    size='small'
                    type='text'
                    onClick={() => handleRemove(file)}
                  />
                )}
              </Flex>
            </Flex>
            {previewOpen ? (
              <>
                <Divider style={{ margin: 0 }} />
                <FilePreview file={file} style={{ width: '100%' }} />
              </>
            ) : null}
          </Flex>
        </Card>
      ))}
    </div>
  )
}

FileList.propTypes = {
  files: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  onChange: PropTypes.func,
  multiple: PropTypes.bool,
  editing: PropTypes.bool,
  showPreview: PropTypes.string,
  showInfo: PropTypes.bool,
  showDownload: PropTypes.bool,
  defaultPreviewOpen: PropTypes.bool
}

export default FileList
