import { FileUploader } from "react-drag-drop-files"
import BaseForm from "./BaseForm"
import { mimeType } from "@/utlis/format"
import { useState } from "react"

function FileUploaderInput(props) {
	const { name, data, setData, multiple = true, disabled = false, maxSize = 2, handleOpenPreview = null } = props
	const [error, setError] = useState({
		fileType: null,
		fileSize: null
	})

	function handleSetFiles(files) {
    if (multiple) {
      setData((state) => ({
        ...state,
        [name]: [...state[name], ...files]
      })) 
    } else {
      setData((state) => ({
        ...state,
        [name]: [files]
      })) 
    }
    

		setError((state) => ({
			...state,
			fileType: null,
			fileSize: null
		}))
	}

	function handleRemoveFile(file) {
		const files = data[name].filter((state) => state != file)
		setData((state) => ({
			...state,
			[name]: files
		}))
	}

	const handleSetError = (type, message) => {
		setError((state) => ({
			...state,
			[type]: message
		}))
	}

	let accept = ''

  if (typeof props.accept == 'string'){
    accept = mimeType(props.accept)
  }
  if (typeof props.accept == 'object'){
    accept = props.accept?.map(accept=> mimeType(accept))?.join(',')
  }
  
	accept = accept.split(',').filter((item) => item.startsWith('.')).map((item) => item.replace('.', '').toUpperCase())

	let inputProps = { name, multiple, disabled, maxSize }
	let files = typeof data[name] === 'object' ? data[name] : []  

	return (
		<div className="grid gap-2 w-full z-50">
			<BaseForm {...props}>
				<FileUploader handleChange={handleSetFiles} types={accept} onTypeError={(e)=>handleSetError('fileType', e)} onSizeError={(e)=>handleSetError('fileSize', e)} {...inputProps}>
					<div className={`flex items-start gap-2 w-full border min-h-[4rem] p-4 ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
						<i className="fas fa-upload"></i>
						<div className="">
							<p>Click or Drop Files to Upload. Max: {maxSize} MB</p>
							<p className="text-xs mt-4">{accept.join(', ')}</p>

							{error.fileType ? (
								<p className="text-xs mt-4 text-red-600">* {error.fileType}</p>
							) : null}
							{error.fileSize ? (
								<p className="text-xs mt-4 text-red-600">* {error.fileSize}. Max: {maxSize} MB</p>
							) : null}
						</div>
					</div>
				</FileUploader>
			</BaseForm>

			<div className="flex flex-wrap gap-2 w-full text-gray-700">
				{files?.length > 0 ? files.map((file) => {
					let imageUrl = file?.type?.startsWith('image') ? URL.createObjectURL(file) : null

          if (file?.value?.startsWith('/storage')) {
            imageUrl = file?.value
          }
          if (file?.value?.startsWith('/image')) {
            imageUrl = file?.value
          }

          let label = file.name
          if (!label) {
            label = file?.label
          }

          if (imageUrl && !file?.type?.startsWith('image')) {
            let imageTypes = mimeType('image').split(',').filter((item) => item.startsWith('.')).map((item) => item.replace('.', '').toLowerCase())
            let fileType = imageUrl.split('.')
            let ext = fileType[fileType.length - 1].toLowerCase()
            if (!imageTypes.includes(ext)) {
              imageUrl = ""
            }
          }

					return (
						<div className={`border px-2 rounded-lg flex gap-2 w-full py-1`}>
							<button onClick={() => handleRemoveFile(file)} type="button" className="btn btn-xs btn-neutral btn-circle">
								<i className="fas fa-x"></i>
							</button>
							<div className="">
                <button type="button" onClick={handleOpenPreview ? ()=> handleOpenPreview(file) : null} className={`${handleOpenPreview ? 'link-hover' : ''}`}>
  								<p>{label}</p>
                </button>
								{imageUrl ? (
									<figure>
										<img src={imageUrl} className="w-full max-w-2xl h-full max-h-[10rem] object-cover mt-2" />
									</figure>
								) : null}
							</div>
						</div>
					)
				}) : null}
			</div>
		</div>
	)
}

export default FileUploaderInput
