import React, {useState, useEffect, KeyboardEvent} from 'react';
import {useDropzone} from 'react-dropzone';
import {read, utils} from 'xlsx';
import InvitationBox from './InvitationBox';
import PlusSignSmall from '../../../../SVG/PlusSignSmall';
import DownloadIcon from '../../../../SVG/DownloadIcon';
import UploadIcon from '../../../../SVG/UploadIcon';
import './dropzone.scss'
import CustomFormSection from "../../../../UI/CustomFormSection/CustomFormSection";
import CustomLabel from "../../../../UI/CustomLabel/CustomLabel";
import Garbage from "../../../../SVG/Garbage";
const xlsxFile = require('../../../../../assets/files/template-visitors.xlsx');

interface DropzoneProps {
    persons: any,
    setPersons: any
    deletePerson: any
    deleteAllPersons:any
    hasError: string
}

const Dropzone = ({hasError,
                      persons,
                      setPersons,
                      deletePerson,
                      deleteAllPersons,
                  }: DropzoneProps) => {
    const [isLoading, setIsLoading] = useState(false);

    const {getRootProps, getInputProps, acceptedFiles} = useDropzone({});
    const [visitorsAddCount, setVisitorsAddCount] = useState(0);
    const [valid, setValid] = useState(false);
    const [errorState, setErrorState] = useState(false);
    const [manualInput, setManualInput] = useState("");
    const [isHeaderBlue, setIsHeaderBlue] = useState(false);
    const files = acceptedFiles;
    const [isOpened, setIsOpened] = useState(false);
    const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);

    const handleEmailValidation = (e: KeyboardEvent) => {
        const emails = manualInput.split(',').map((email) => email.trim());
        const isValid = emails.every((email) =>
            email !== "" && /^[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(email)
        );

        setValid(isValid);
        setErrorState(!isValid);
    };

    const deleteVisitor = (email: string) => {
        // @ts-ignore
        const newState = persons.filter(person => person.email !== email)
        deletePerson()
        setPersons(newState);

    }
    const deleteAllVisitors = (event: React.MouseEvent<HTMLSpanElement>) => {
        event.stopPropagation();
        if (showDeleteConfirmation) {
            deleteAllPersons();
        } else {
            setShowDeleteConfirmation(true);
        }
    };

    const handleUserInput = (e: any) => {
        setManualInput(e.target.value);
    };


    const renderPersons = () => {
        return (
            persons && persons.map((person: any, index: number) => (
                <InvitationBox key={index} email={person} deleteVisitor={() => deletePerson(index)}/>
            ))
        )
    }

    const handleImport = () => {
        if (files) {
            const file = files[0];
            const reader = new FileReader();
            reader.onload = (event) => {
                const target = event.target;
                if (target instanceof FileReader && target.result) {
                    const wb = read(target.result);
                    const sheets = wb.SheetNames;
                    if (sheets.length) {
                        const rows: { Email?: string }[] = utils.sheet_to_json(wb.Sheets[sheets[0]]);
                        const newEmails: string[] = rows.map((row) => row.Email || '');
                        const validEmails: string[] = [];
                        const invalidEmails: string[] = [];
                        const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
                        newEmails.forEach((email) => {
                            if (emailRegex.test(email)) {
                                validEmails.push(email);
                            } else {
                                invalidEmails.push(email);
                            }
                        });
                        const uniqueValidEmails = [...new Set(validEmails)];
                        const newEmailsFiltered = uniqueValidEmails.filter((newEmail) => !persons.includes(newEmail.trim()));
                        setPersons(newEmailsFiltered);
                        setVisitorsAddCount(newEmailsFiltered.length);
                    }
                }
            };
            reader.readAsArrayBuffer(file);
        }

        setIsOpen(false);
        setIsOpened(false);
        setIsLoading(true);
        setTimeout(() => {
            setIsLoading(false);
        }, 2000);
    };



    useEffect(() => {
        acceptedFiles.length > 0 &&
        handleImport()
    }, [acceptedFiles])

    const handleDownload = () => {
        fetch(xlsxFile.default)
            .then(response => response.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(new Blob([blob]));
                const link = document.createElement('a');
                link.href =  xlsxFile;
                link.setAttribute('download', 'template-visitors.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            })
            .catch(error => {

            });
    };

    const handleManualInput = (input: string) => {
        const visitors = input.split(',');

        // Filter out visitors that are already in persons array
        const newVisitors = visitors.filter((visitor) => !persons.includes(visitor.trim()));
        const uniqueNewVisitors = newVisitors.filter((value, index, array) => array.indexOf(value) === index);
        const newVisitorsFiltered = uniqueNewVisitors.filter((newVisitor) => !persons.includes(newVisitor.trim()));
        // Add new visitors to persons array

        setPersons(newVisitorsFiltered);

        setIsOpen(false);
        setManualInput("");
        setVisitorsAddCount(newVisitorsFiltered.length);
        setIsOpened(false);
        setIsLoading(true);

        setTimeout(() => {
            setIsLoading(false);
        }, 1000);
    }


    useEffect(() => {
        manualInput === "" &&
        setValid(false);
    }, [manualInput])
    const [isOpen, setIsOpen] = useState(false);

    return (
        <div className={"row dropzone"}>
            <div className={"formpair-dropzone"}>
                <CustomFormSection theme={"user-form"}>
                    <div className={'row'}>
                        <div className={'col-12 col-lg-6'}>
                            <CustomLabel>
                                ΚΑΤΑΧΩΡΗΣΗ ΠΑΡΑΛΗΠΤΩΝ
                            </CustomLabel>
                            {/* <p>Γράψτε ένα ή περισσότερα e-mails χωρίζοντάς τα με κόμμα (,)
                                :</p> */}
                            <div className='row mt-4'>
                                {/*we give the attribute form a value different than the form we want to submit.that way on enter the real form wont be submitted*/}
                                <div className={'col-12 col-xxl-7 pe-0'}><input
                                    form={'notTheRealForm'}
                                    onKeyUp={(e) => {
                                        if (e.key === 'Enter' && valid) {
                                            handleManualInput(manualInput);
                                        } else {
                                            handleEmailValidation(e);
                                        }
                                    }}
                                    onChange={(e) => handleUserInput(e)}
                                    value={manualInput} className="text-field user-form-field" id="visitor-names"
                                    type="text"
                                    placeholder='Πχ: email1@email1.gr,email2@email2.gr'/></div>
                                <div className={'col-12 col-xxl-3 ps-0  gy-3 gy-xxl-0'}>
                                    <button disabled={!valid}
                                            onClick={() => handleManualInput(manualInput)}
                                            type="button"
                                            className={`form-button-alt ${valid ? 'enable-btn' : 'disable-btn'}`}><PlusSignSmall
                                        color={'white'}/><p className={"form-button-alt-text"}>Προσθήκη</p></button>
                                </div>


                            </div>
                            <p id="mail-error"
                               className={`error-msg ${errorState ? 'display-error' : 'no-display-error'}`}>Παρακαλώ
                                συμπληρώστε πραγματικό e-mail</p>
                        </div>


                        <div className={'col-12 col-lg-6'}>
                            <CustomLabel>
                                ΜΕΤΑΦΟΡΤΩΣΗ ΑΡΧΕΙΟΥ EXCEL ΠΑΡΑΛΗΠΤΩΝ
                            </CustomLabel>
                            {/* <p>Κατεβάστε το πρότυπο, Συμπληρώστε το & Μεταφορτώστε το</p> */}
                            <div className={'row mt-4'}>
                                <div className={'col-12 col-xxl-6'}>
                                    <button type={"button"} onClick={handleDownload} className="form-button-alt"><p>Λήψη
                                        Προτύπου</p><DownloadIcon
                                    color={'white'}/>
                                    </button>
                                </div>
                                <div className={'col-12 col-xxl-6 gy-3 gy-xxl-0'}>
                                    <button type={"button"} {...getRootProps({className: "dropzone form-button-alt"})}>
                                        <input id="excel-input"
                                               accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" {...getInputProps()}/>
                                        <p>Μεταφόρτωση</p><UploadIcon
                                        color={'white'}/>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div className={'col-12 d-flex justify-content-center'}>  {hasError && <p className={'error-message'}>{hasError}</p>}</div>
                    </div>

                </CustomFormSection>
            </div>
            {renderPersons().length > 0 && <div className={`list-container `}>
                <div id="uploaded-emails"
                     className={`uploaded-emails ${isLoading ? "loading" : ""} ${isOpen ? "open" : "closed"} `}>
                    <h4 className={`uploaded-emails-head ${!isOpened && "notopened"}`} >{isLoading
                        ? "Loading..."
                        :
                        <span id={`justuploaded`}>Επιτυχής μεταφόρτωση {visitorsAddCount} Επισκέπτων</span>}
                        {!isLoading && (
                            <div id={"total"}>
                                {showDeleteConfirmation ? (

                                        <p className={'deleteallprompt'}><span>Αφαίρεση όλων; </span>  <span className={'d-flex'}>
                                            <button onClick={() => {deleteAllPersons()
                                                setShowDeleteConfirmation(false);
                                            }}>Ναι</button>
                                            <button onClick={() => setShowDeleteConfirmation(false)}>
                                                Όχι
                                            </button>
                                        </span></p>
                                ) : (
                                        <p  className={'totaluploadedcount'}>
                                           <span  onClick={() => {
                                               !isLoading && setIsOpen(!isOpen)
                                               setIsOpened(true)
                                               setIsHeaderBlue(!isHeaderBlue);}}> Μεταφορτωμένα email Επισκεπτών: {renderPersons().length}</span><span  id={"deleteall"}
                                                                                                                        onClick={(event) => deleteAllVisitors(event)}> <Garbage color={"white"} /></span>
                                        </p>

                                )}
                            </div>
                        )}

                    </h4>
                    <div className={`uploaded-emails-body`}>
                        <ul className='person-container'>
                            {
                                renderPersons()
                            }
                        </ul>
                    </div>
                </div>


            </div>}


        </div>
    );
}
export default Dropzone;
