import React, { useContext, useState } from "react";
import { Link } from "react-router-dom";
import { AuthContext } from "../../AuthProvider";
import { useConfig } from "../../ConfigProvider";
import {
    Download,
    Upload,
    KeyRound,
    KeySquare,
    LogOut,
    LogIn,
    ChevronDown,
    Mail,
    GitBranch,
} from "lucide-react";
import ApiKeyCreationModal from "../Modals/ApiKeyCreationModal";
import ApiKeyRevokeModal from "../Modals/ApiKeyRevokeModal";
import { Button } from "../ui/button";
import {
    DropdownMenu,
    DropdownMenuTrigger,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
} from "../ui/dropdown-menu";

const MainNavigation = () => {
    const { user, login, logout } = useContext(AuthContext);
    const config = useConfig();
    const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false);
    const [isRevokeModalOpen, setIsRevokeModalOpen] = useState(false);

    if (config === undefined) {
        return (
            <header className="flex h-14 items-center border-b border-border px-5 text-sm text-muted-foreground">
                Loading …
            </header>
        );
    }

    const handleLoadBackup = async () => {
        try {
            const input = document.createElement("input");
            input.type = "file";
            input.accept = ".zip";
            input.onchange = async (event) => {
                const file = event.target.files[0];
                if (!file) return;
                const formData = new FormData();
                formData.append("file", file);
                try {
                    const response = await fetch(
                        `${config.BACKEND_HOST}/api/backup/load`,
                        {
                            method: "POST",
                            headers: {
                                Authorization: `Bearer ${localStorage.getItem("accessToken")}`,
                            },
                            body: formData,
                        }
                    );
                    if (response.ok) {
                        await response.json();
                        alert("Backup loaded");
                    } else {
                        const error = await response.json();
                        alert(`failed to load ${error.error}`);
                    }
                } catch (error) {
                    console.error(error);
                    alert("error when loading backup");
                }
            };
            input.click();
        } catch (error) {
            console.error(error);
            alert(`Unexpected error`);
        }
    };

    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";
                if (contentDisposition) {
                    const match = contentDisposition.match(
                        /filename="?([^"]+)"?/
                    );
                    if (match && 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 (
        <>
            <header className="glass relative z-20 flex h-14 shrink-0 items-center gap-1 border-b border-border px-4">
                <Link
                    to="/"
                    className="group flex items-center gap-2.5 pr-3"
                >
                    <img
                        src="/icons/hangman-lab-logo.svg"
                        alt="Hangman Lab"
                        className="h-7 w-7"
                    />
                    <span className="font-display text-base leading-none tracking-tight">
                        <span className="text-foreground">hangman</span>
                        <span className="neon-text"> lab</span>
                    </span>
                </Link>

                <nav className="ml-2 hidden items-center gap-1 sm:flex">
                    <a
                        href="https://mail.hangman-lab.top"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
                    >
                        <Mail className="h-3.5 w-3.5" /> Mail
                    </a>
                    <a
                        href="https://git.hangman-lab.top"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
                    >
                        <GitBranch className="h-3.5 w-3.5" /> Git
                    </a>
                </nav>

                <div className="ml-auto flex items-center">
                    {user && user.profile ? (
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    className="gap-2"
                                >
                                    <span className="grid h-5 w-5 place-items-center rounded-full bg-primary/15 font-mono text-[10px] font-bold text-primary">
                                        {(user.profile.name || "?")
                                            .charAt(0)
                                            .toUpperCase()}
                                    </span>
                                    <span className="max-w-[10rem] truncate">
                                        {user.profile.name}
                                    </span>
                                    <ChevronDown className="h-3.5 w-3.5 opacity-60" />
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                                <DropdownMenuLabel>
                                    {user.profile.name}
                                </DropdownMenuLabel>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem onClick={handleGetBackup}>
                                    <Download /> Get Backup
                                </DropdownMenuItem>
                                <DropdownMenuItem onClick={handleLoadBackup}>
                                    <Upload /> Load Backup
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={() => setIsApiKeyModalOpen(true)}
                                >
                                    <KeyRound /> Create API Key
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={() => setIsRevokeModalOpen(true)}
                                >
                                    <KeySquare /> Revoke API Key
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                    onClick={logout}
                                    className="text-destructive focus:text-destructive [&_svg]:text-destructive"
                                >
                                    <LogOut /> Logout
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    ) : (
                        <Button size="sm" onClick={login} className="gap-2">
                            <LogIn className="h-4 w-4" /> Login
                        </Button>
                    )}
                </div>
            </header>
            <ApiKeyCreationModal
                isOpen={isApiKeyModalOpen}
                onClose={() => setIsApiKeyModalOpen(false)}
            />
            <ApiKeyRevokeModal
                isOpen={isRevokeModalOpen}
                onClose={() => setIsRevokeModalOpen(false)}
            />
        </>
    );
};

export default MainNavigation;
