import React, { useState, useRef, useEffect } from "react";
import { Icons } from "../Icons";
import { Pill } from "../Pill";
import { FileUploadProps } from "./FileUpload.types";
import cx from "classnames"
import "./style.scss"
import { Loading } from "../Loading";
import { Label } from "..";
import { useLocale } from "../../hooks/useLocale";

export const FileUpload: React.FC<FileUploadProps> = ({
    placeholder = "select_files",
    id = "FileUpload-ID",
    name,
    filesExtensions = ".jpg, .png, .txt",
    value = [],
    isMultiple = false,
    isDisabled = false,
    maxSize = 4,
    maxSizeMessage = "Max file size reached",
    style = {},
    label,
    helpText,
    className,
    uploadedAttachment,
    loadingUploadFile,
    uploadAttachment,
    onReadFile,
    onChange,
}) => {
    const inputFileRef = useRef<any>();
    const [isFileValid, setIsFileValid] = useState<boolean>(true)
    const [errorMessage, setErrorMessage] = useState<string>("")
    const [componentEvent, setComponentEvent] = useState<any>(null)
    const prevUploadedAttachment = useRef<any>(null)

    const labels = {
        placeholder: useLocale(placeholder)
    }

    const addNewImage = (image: any) => {
        setComponentEvent(null)
        let files = value || [];
        files = files.concat([image]);
        if (onChange) onChange(files);
    }

    useEffect(() => {
        // Uso tipico (no olvides de comparar los props):
    
        if (uploadedAttachment !== prevUploadedAttachment.current) {
            if (uploadedAttachment && !prevUploadedAttachment.current) {
                //console.log("this.props.id",this.props.id,"this.state.componentEvent?.target?.id",this.state.componentEvent?.target)
                ( id && componentEvent?.target?.id) && addNewImage(uploadedAttachment) ||  !id && addNewImage(uploadedAttachment) ;
            } else if (
                uploadedAttachment
                && uploadedAttachment?.id != prevUploadedAttachment.current?.id
            ) {
                const newFile = uploadedAttachment;
                let exists;
                if (value) {
                    exists = value.find((file: any) => file.id === newFile.id);
                }
                if (!exists) {
                    ( id && componentEvent?.target?.id) && addNewImage(newFile) || !id && addNewImage(newFile)  ;
                }
            }
        }
        prevUploadedAttachment.current = uploadedAttachment
    },[uploadedAttachment])
    

    const validate = (val: any) => {
        let isValid = true;
        let errorMessage = "";
        let tempValue = val || value;
  
        if (maxSize) {
          let bytes = maxSize * 1000000;
          if (tempValue[0]?.size > bytes) {
            isValid = false;
            errorMessage = maxSizeMessage;
          }
        }
        setIsFileValid(isValid)
        setErrorMessage(errorMessage)
        //this.setState({ isValid, errorMessage });
        return isValid;
    }

    const uploadImg = (e: any) => {
        //** saving component event for validation */
        e.persist();
        //this.setState({componentEvent:e})
        setComponentEvent(e)
        const fileKey = e.target.files[0];
        const payload = {
          fileKey
        };
        if (fileKey && !onReadFile) {
          uploadAttachment(payload);            // <------------ Action from redux
        }else{
          if(onReadFile){         // <------------ Function from uploadRoute
            onReadFile(fileKey);
          }
        }
      }

    const closePillAttachment = (item: any) => {
        let files = value || [];
        files = files.filter((file:any) => file.id != item.id)
        if (item.fileUri) {
            //delete
        }
        validate(files);
        if (onChange) onChange(files);
    }

    return (
        <div className="gtc-rc-fileupload-container">
            { label && 
                <Label className="gtc-rc-fileupload-label">
                    {label}
                </Label>  
            }
            {loadingUploadFile ? (
                <div className="gtc-rc-input-loading">
                    <Loading /> 
                </div>
            ) : (
                <div className="gtc-rc-fileupload-container-input">
                    <div className={cx("gtc-rc-fileupload-input", className)} style={style} onClick={() => inputFileRef.current.click()}> {/* onClick={() => inputFileRef.current.click()}> */}
                        <label className="gtc-rc-fileupload-placeholder" >{/* htmlFor={id} > */}
                            {labels['placeholder']}
                        </label>
                        <input
                            ref={inputFileRef}
                            id={id}
                            name={name}
                            type="file"
                            multiple={isMultiple}
                            accept={filesExtensions}
                            style={{ display: 'none' }}
                            onClick={(e:any) => {
                                if (!isMultiple) e.target.value = null;
                            }}
                            onChange={(e) => {
                                if(validate(e.target.files)){
                                    uploadImg(e);
                                } 
                            }}
                            disabled={isDisabled}
                        />
                        <div className="gtc-rc-fileupload-icon-button" > {/* onClick={() => inputFileRef.current.click()}> */}
                            { 
                            !isDisabled &&
                                <Icons name="add" size="small"/>
                            }
                        </div>
                    </div>

                    {value && value.length > 0 && (
                        <div className="gtc-rc-fileupload-file-container">
                            {value.map((item:any, key:any) => {
                            return (
                                <Pill 
                                    key={"file-"+key}
                                    item={{ ...item, label: item?.originalName, color: "default-green" }}
                                    size="full"
                                    icon="cancel"
                                    clickable={false}
                                    onClickIcon={()=> {closePillAttachment(item)}}
                                    style={{ marginBottom: 5 }}
                                />
                            );
                            })}
                        </div>
                    )}
                    
                    {helpText && (
                        <small id={`${id}-help`} className="form-text gtc-rc-text-muted">
                            {helpText}
                        </small>
                    )}

                    {!isFileValid && errorMessage && (
                        <small className="gtc-rc-text-danger" style={{ paddingTop: 5 }}>
                            {errorMessage}
                        </small>
                    )}
                </div>
            )}
        </div>
    )
}