import React, {useContext, useState} from "react";
import { Link } from "react-router-dom";
import { AuthContext } from "../../AuthProvider";
import "bulma/css/bulma.min.css";
import {useConfig} from "../../ConfigProvider";
import "./MainNavigation.css";

const MainNavigation = () => {
    const { user, login, logout } = useContext(AuthContext);
    const config = useConfig();
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    if (config===undefined) {
        return <div>Loading ...</div>;
    }
    const handleGetBackup = async () => {
        try{
            const response = await fetch(
                `${config.BACKEND_HOST}/api/backup/`, {
                    method: "GET",
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem("accessToken")}`,
                    }
                }
            );
            if(response.ok){
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement("a");
                const contentDisposition = response.headers.get("Content-Disposition");
                let filename = "backup.zip";
                console.log(response.headers);
                console.log(contentDisposition);
                if (contentDisposition) {
                    const match = contentDisposition.match(/filename="?([^"]+)"?/);
                    console.log(match);
                    if (match && match[1]) {
                        console.log(match[1]);
                        filename = match[1];
                    }
                }
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            }else{
                alert("Failed to get backup");
            }
        } catch(err){
            console.log(err);
            alert("An error occurred while retrieving backup");
        }
    };

    return (
        <nav className="navbar is-dark" role="navigation" aria-label="main navigation">
            <div className="navbar-brand">
                <Link className="navbar-item" to="/">
                    <img src="/icons/logo.png" alt="Logo" style={{ height: "40px", marginRight: "10px" }} />
                    Home
                </Link>
                <a
                    role="button"
                    className="navbar-burger"
                    aria-label="menu"
                    aria-expanded="false"
                    data-target="navbarBasicExample"
                    onClick={(e) => {
                        e.currentTarget.classList.toggle("is-active");
                        document
                            .getElementById("navbarBasicExample")
                            .classList.toggle("is-active");
                    }}
                >
                    <span aria-hidden="true"></span>
                    <span aria-hidden="true"></span>
                    <span aria-hidden="true"></span>
                </a>
            </div>

            <div id="navbarBasicExample" className="navbar-menu">
                <div className="navbar-start">
                    <a
                        href="https://mail.hangman-lab.top"
                        className="navbar-item"
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        MailBox
                    </a>
                    <a
                        href="https://git.hangman-lab.top"
                        className="navbar-item"
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        Git
                    </a>
                </div>

                <div className="navbar-end">
                    {user && user.profile ? (
                        <div className="navbar-item has-dropdown is-hoverable">
                            <div className="buttons">
                                <span
                                    className="button is-primary is-light"
                                    onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                >
                                    {user.profile.name}
                                </span>
                                <div className={`navbar-dropdown ${isDropdownOpen ? "is-active" : ""}`}>
                                    <button
                                        className="button is-primary dropdown-option"
                                        onClick={handleGetBackup}
                                        type="button"
                                    >
                                        Get Backup
                                    </button>
                                    <button
                                        className="button is-danger dropdown-option"
                                        onClick={logout}
                                        type="button"
                                    >
                                        Logout
                                    </button>

                                </div>

                            </div>
                        </div>
                    ) : (
                        <div className="navbar-item">
                            <button
                                className="button is-primary"
                                onClick={login}
                                type="button"
                            >
                                Login
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </nav>
    );
};

export default MainNavigation;