import React, { useState } from "react";
import styles from './AddWord.module.scss';
import { ReactComponent as ChevronLeft } from '../../assets/icons/chevron-left.svg';
import { ReactComponent as SearchIcon } from '../../assets/icons/bx-search-alt.svg';
import { ReactComponent as SpeakerIcon } from '../../assets/icons/speaker.svg';
import { ReactComponent as AddIcon } from '../../assets/icons/plus.svg';

import { NavLink, useHistory } from "react-router-dom";
import { getWordResult } from "../../services/words";
import { MobileWord } from "../../shared/models/word";
import { MobileUser } from "../../shared/models/user";
import { updateShelf } from "../../services/shelf";
import { getAllData } from "../../services/user";

export const AddWord: React.FC = () => {
    const [searchResult, setSearchResult] = useState<Array<MobileWord>>();
    const [selectedWord, setSelectedWord] = useState<MobileWord>();
    const [searchWord, setSearchWord] = useState<string>('');
    const userProfile: MobileUser = JSON.parse(localStorage.getItem('userProfile') || "");
    const history = useHistory();

    const searchWords = () => {
        if (searchWord.length > 0) {
            getWordResult(searchWord).then((wordResult: any) => {
                let result: Array<MobileWord> = wordResult.data;
                setSearchResult(result);
            }, err => {
                console.log("Unable to search Words", err)
            });
        }
    }

    return <section className="modalPage">

        <header className={styles.navHeader}>
            <button onClick={() => {
                if (selectedWord) {
                    setSelectedWord(undefined);
                } else {
                    window.history.back()
                }
            }}>
                <ChevronLeft />
            </button>
            {!selectedWord && <h5> Add a Word </h5>}
            {selectedWord && <h5> Add to Shelf </h5>}
        </header>

        {!selectedWord && <section>
            <div className={styles.searchBarHolder}>
                <div className={styles.searchBar}>
                    <input type="text" autoFocus={true} placeholder={'Search and add a word'} onChange={(event) => setSearchWord(event.currentTarget.value)} />
                    <button onClick={() => searchWords()}>
                        <SearchIcon />
                    </button>
                </div>
            </div>

            { searchResult && <ul className={styles.searchResult}>
                {searchResult.map((word) => {
                    return <li key={word.name}>
                        <header>
                            <h4> {word.name} <span> {word.pronounciation} </span> </h4>
                            <button>
                                <SpeakerIcon />
                            </button>
                        </header>
                        <div className={styles.description}>
                            <span> {word.grammaticalDetails[0]?.type} </span>
                            <p> {word.grammaticalDetails[0]?.description} </p>
                        </div>
                        <button className={styles.addButton} onClick={() => setSelectedWord(word)}> <AddIcon />  Add </button>
                    </li>
                })}
            </ul> }
        </section>}


        {selectedWord && <section>
            <div className={styles.searchBarHolder}>
                <div className={styles.searchBar}>
                    <input type="text" placeholder={'Search shelves'} />
                    <SearchIcon />
                </div>
            </div>

            <ul className={styles.shelfList}>
                <header>
                    <h5> All Shelves </h5>
                </header>
                {userProfile.categories.map((category, categoryIndex) => {
                    return category?.shelves?.map((shelf, shelfIndex) => {
                        return <li key={shelfIndex} onClick={() => {

                            let words: any = shelf.words ? shelf.words : [];

                            if (words.findIndex((word: any) => word.word.name === selectedWord.name) >= 0) {
                                alert("Word already Present!");
                            } else {
                                words.push({
                                    word: selectedWord,
                                    notes: [],
                                    isArchived: false,
                                    spaceBetweenRecall: 1,
                                    nextRevisionDateTime: new Date()
                                })
    
                                let updatedWords: any = [];
    
                                updatedWords = words.map((word: any) => {
                                    return {
                                        ...word,
                                        word: word.word._id,
                                    }
                                });

                                updateShelf(shelf._id, updatedWords).then(() => {
                                    
                                    getAllData().then((response: any) => {
                                        localStorage.setItem('userProfile', JSON.stringify(response.data));
                                        history.push('/shelf-details/category_id=' + category._id + '&&shelf_id=' + shelf._id);
                                    }, (err) => {
                                        window.alert("Failed to fetch deep copy of user profile");
                                        console.log(err);
                                    });
                                    
                                }, (err) => {
                                    window.alert("Failed to update");
                                    console.log(err);
                                });
                            }
                        }}>
                            <div className={styles.icon}>
                                {category.icon}
                            </div>
                            <div className={styles.info}>
                                <label> {shelf.name} </label>
                                <span> {category.name} </span>
                            </div>
                        </li>
                    })
                })}

                <NavLink to={'/add-shelf'} className={styles.AddShelfButton}> <span> <AddIcon /> </span> Create New Shelf </NavLink>
            </ul>
        </section>}

    </section>
}