import React, {useState} from "react";
import dialogPolyfill from "dialog-polyfill";

import "./App.scss";
import {SaiEntryProps, JutEntryProps, ElesuEntryProps, TukEntryProps, Conlang, SearchDirection} from "./types";
import {SaiEntry, JutEntry, ElesuEntry, TukEntry} from "./Entries";
import {setPassword, searchEntry} from "./requests";

const PasswordDialog = (_props) => {
    const [password, setPasswordStr] = useState("");

    const save = () => {
        setPassword(password);
        const modal: any = document.querySelector(".passwordDialog");
        dialogPolyfill.registerDialog(modal);
        modal.close();
        location.reload(); // TODO this is a hack
    };

    const cancel = () => {
        const modal: any = document.querySelector(".passwordDialog");
        dialogPolyfill.registerDialog(modal);
        modal.close();
    };

    return (
        <dialog className="passwordDialog">
            <input type="password" placeholder="enter password" value={password} onChange={ (evt) => setPasswordStr(evt.target.value) } />
            <button onClick={save}>Save</button>
            <button onClick={cancel}>Cancel</button>
        </dialog>);
};

const renderConlang = (conlang: Conlang): string => {
    if (conlang === Conlang.Saimiar) {
        return "Saimiar";
    }

    if (conlang === Conlang.Elesu) {
        return "Elésu";
    }

    if (conlang === Conlang.Juteyuji) {
        return "Juteyuji";
    }

    if (conlang === Conlang.Tukvaysi) {
        return "Tukvaysi";
    }
};

interface EntryProps {
    conlang: Conlang;
    entry: SaiEntryProps | JutEntryProps | ElesuEntryProps | TukEntryProps;
    key: string;
}

const Entry = (props: EntryProps) => {
    const {conlang} = props;
    if (conlang === Conlang.Saimiar) {
        return <SaiEntry entry={ props.entry as SaiEntryProps } />;
    }

    if (conlang === Conlang.Juteyuji) {
        return <JutEntry entry={ props.entry as JutEntryProps } />;
    }

    if (conlang === Conlang.Elesu) {
        return <ElesuEntry entry={ props.entry as ElesuEntryProps } />;
    }

    if (conlang === Conlang.Tukvaysi) {
        return <TukEntry entry={ props.entry as TukEntryProps } />;
    }
};

interface ResultsProps {
    searchResults: Array<any>;
    searchTerm: string;
    conlang: Conlang;
    direction: SearchDirection;
}

const Results = (props: ResultsProps) => {
    const content = () => {
        const {conlang} = props;
        const num = props.searchResults.length;

        const renderedName = renderConlang(conlang);
        const searchType = (props.direction === SearchDirection.ToConlang) ? `English -> ${renderedName}` : `${renderedName} -> English`;
        const result = num === 1 ? "result" : "results";
        const header = (
            <div className="searchResultHeader" key="header">
        Searched for <b>{ props.searchTerm }</b>, { searchType }, found { num } { result }
            </div>);
        const entries = props.searchResults.map(
            (entry, _idx) => <Entry entry={ entry } key= { entry.id } conlang={ conlang } />,
        );
        return [header].concat(entries);
    };

    const results = props.searchResults;
    return (
        <div className="results">
            { results ? content() : "No search" }
        </div>
    );
};

const convertSearchBoxShorthand = (input: string, conlang: Conlang): string => {
    if (conlang === Conlang.Saimiar) {
        return (input as any)
            .replaceAll(/ee/g, "ê")
            .replaceAll(/oo/g, "ô")
            .replaceAll(/o'/g, "ø")
            .replaceAll(/c'/g, "ç")
            .replaceAll(/n'/g, "ŋ");
    }

    return input;
};

const App = (_props) => {
    const defaultConlang = window.sessionStorage.getItem("conlang") as Conlang || Conlang.Saimiar;
    const [searchResults, setSearchResults] = useState(null);
    const [conlang, setConlangState] = useState(defaultConlang);
    const [direction, setDirection] = useState(null);
    const [searchTerm, setSearchTerm] = useState(null);

    const [searchBoxInput, setSearchBoxInput] = useState("");

    const setConlang = (conlang: Conlang) => {
        setConlangState(conlang);
        window.sessionStorage.setItem("conlang", conlang);
    };

    const handleSearch = (direction: SearchDirection) => {
        const searchTerm = direction === SearchDirection.ToEnglish ? convertSearchBoxShorthand(searchBoxInput, conlang) : searchBoxInput;
        if (searchTerm === "") {
            setSearchResults(null);
            setSearchTerm(null);
            setDirection(null);
        } else {
            searchEntry(searchTerm, conlang, direction, (json) => {
                setSearchResults(json);
                setSearchTerm(searchTerm);
                setDirection(direction);
            });
        }
    };

    const handleLangChange = (evt) => {
        const conlang: Conlang = evt.target.value as Conlang;
        setConlang(conlang);
        setSearchResults(null);
    };

    const conlangs = [Conlang.Saimiar, Conlang.Elesu, Conlang.Tukvaysi, Conlang.Juteyuji];
    const langSelectDropdown = (
        <select className="searchDropdown" value={conlang} onChange={ handleLangChange }>
            {conlangs.map((conlang) => <option value={conlang} key={conlang}>{renderConlang(conlang)}</option>)}
        </select>
    );

    const showPasswordBox = () => {
        const modal: any = document.querySelector(".passwordDialog");
        dialogPolyfill.registerDialog(modal);
        modal.showModal();
    };

    return (
        <main>
            <PasswordDialog />
            <div className="container">
                <div className="search">
                    <h1>Kucinako - Wordbook of Arzhanai languages</h1>
                    <p><b>Kucinako</b> is a dictionary of words in various languages of the world Arzhanø, and their English
                    equivalents.</p>
                    <div className="textInput">
                        <input className="textInput" type="text" value={ searchBoxInput } onChange={ (evt) => {
                            setSearchBoxInput(evt.target.value);
                        } } />
                    </div>
                    <br/>
                    { langSelectDropdown }
                    <button onClick={ () => handleSearch(SearchDirection.ToEnglish) } className="searchButton">{renderConlang(conlang)}</button>
                    <button onClick={ () => handleSearch(SearchDirection.ToConlang) } className="searchButton">English</button>
                    <button onClick={ showPasswordBox } className="searchButton">Password</button>
                </div>
                <Results
                    searchResults={ searchResults }
                    searchTerm= { searchTerm }
                    conlang={ conlang }
                    direction={ direction }
                />
            </div>
        </main>
    );
};

export default App;
