import React from "react";
import { createRoot } from "react-dom/client";
import { useState, useEffect } from 'react';
import { ApiaryAPI, LoginAttempt, DummyApiaryAPIClient, ApiaryAPIClient, TotalStats, StatsResult } from "./api";
import { BrowserRouter, NavLink, Routes, Route } from "react-router";
import { Chart as ChartJS, Tooltip, ArcElement, Legend } from "chart.js";
import { Pie } from "react-chartjs-2";

ChartJS.register(Tooltip, ArcElement, Legend);

interface AppProps {
    api: ApiaryAPI
}

let chartColors = [
    "#1abc9c",
    "#2ecc71",
    "#3498db",
    "#9b59b6",
    "#34495e",
    "#16a085",
    "#27ae60",
    "#2980b9",
    "#8e44ad",
    "#2c3e50",
    "#f1c40f",
    "#e67e22",
    "#e74c3c",
    "#ecf0f1",
    "#95a5a6",
    "#f39c12",
    "#d35400",
    "#c0392b",
    "#bdc3c7",
    "#7f8c8d"
]

export function App({ api }: AppProps) {
    return (
        <>
            <BrowserRouter>
                <Header />
                <div className="content">
                    <Routes>
                        <Route path="/" element={<Home api={api} />} />
                        <Route path="/stats" element={<Stats api={api} />} />
                        <Route path="/live" element={<Live api={api} />} />
                        <Route path="/query" element={<Query api={api} />} />
                    </Routes>
                </div>
            </BrowserRouter>
        </>
    );
}

export function Stats({ api }: AppProps) {
    const [stats, setStats] = useState<StatsResult[]>([]);
    const [statsType, setStatsType] = useState<string>("password")

    const activeMenu = (name: string): boolean => {
        if (statsType === name) {
            return true
        }
        return false
    }
    const subMenuItems: SubMenuProps = {
        items: [
            {
                name: "Passwords",
                active: () => { return activeMenu("password") },
                onClick: () => setStatsType("password")
            },
            {
                name: "Usernames",
                active: () => { return activeMenu("username") },
                onClick: () => setStatsType("username")
            },
            {
                name: "IPs",
                active: () => { return activeMenu("ip") },
                onClick: () => setStatsType("ip")
            },
        ]
    }

    useEffect(() => {
        async function getStats() {
            try {
                let newStats = await api.stats(statsType, 10);
                if (JSON.stringify(newStats) !== JSON.stringify(stats)) {
                    setStats(newStats)
                }
            } catch (e) {
                console.log("Error getting stats", e)
            }
        }

        getStats()

        const interval = setInterval(() => {
            getStats()
        }, 5000)

        return () => {
            clearInterval(interval);
        }
    }, [stats, statsType])
    return (
        <>
            <SubMenu items={subMenuItems.items} />
            {stats.length > 0 ? <StatsPie data={stats} /> : <p>Loading...</p>}
        </>
    );
}

export interface StatsPieProps {
    data: StatsResult[]
}

export function StatsPie({ data }: StatsPieProps) {
    const labels = data.map((d) => d.name);
    const values = data.map((d) => d.count);
    const piedata = {
        labels,
        datasets: [{
            label: "# of attempts",
            data: values,
            backgroundColor: chartColors,
            borderWidth: 1
        }]
    };
    return (
        <div className="stats-pie">
            <Pie data={piedata} options={{ plugins: { legend: {} } }} />
        </div>
    )
}

export function Home({ api }: AppProps) {
    const [totals, setTotals] = useState<TotalStats | null>(null)
    useEffect(() => {
        async function getTotals() {
            let totals = await api.totals();
            setTotals(totals);
        }

        if (!totals) {
            getTotals();
        }

        const interval = setInterval(() => {
            getTotals();
        }, 5000)

        return () => {
            clearInterval(interval);
        }
    })
    return (
        <>
            {totals ? <Totals totals={totals} /> : <p>Loading...</p>}
        </>
    );
}

export interface TotalsProps {
    totals: TotalStats
}

export function Totals({ totals }: TotalsProps) {
    return (
        <div className="totals">
            <div className="totals-key">
                <h2>Unique passwords</h2>
                <h2>Unique username</h2>
                <h2>Unique IPs</h2>
                <h2>Total attempts</h2>
            </div>
            <div className="totals-value">
                <h2>{totals.password}</h2>
                <h2>{totals.username}</h2>
                <h2>{totals.ip}</h2>
                <h2>{totals.attempts}</h2>
            </div>
        </div>
    )
}

export function Live({ api }: AppProps) {
    let list: LoginAttempt[] = [];
    let [liveList, setLiveList] = useState(list);

    useEffect(() => {
        const cleanup = api.live((a) => {
            setLiveList((list) => {
                return [...list, a];
            });
        });

        return cleanup

    }, [liveList, api]);

    return (
        <>
            <LiveList list={liveList} />
        </>
    );
}

export interface LiveListProps {
    list: LoginAttempt[]
};

export function LiveList({ list }: LiveListProps) {
    let items = list.map((a) => {
        return (
            <tr key={a.date}>
                <td>{a.date}</td>
                <td>{a.username}</td>
                <td>{a.password}</td>
                <td>{a.remoteIP}</td>
                <td>{a.country}</td>
            </tr>
        )
    })
    return (
        <>
            <table className="live-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Username</th>
                        <th>Password</th>
                        <th>IP</th>
                        <th>Country</th>
                    </tr>
                </thead>
                <tbody>
                    {items}
                </tbody>
            </table>
        </>
    )
};


export function Query({ api }: AppProps) {
    const [liveList, setLiveList] = useState<LoginAttempt[]>([]);
    const [queryErr, setQueryErr] = useState<Error | null>(null);

    async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const value = event.currentTarget.query.value;
        if (value === "") {
            setQueryErr(new Error("Query cannot be empty"));
            return
        }
        try {
            const results = await api.query("", value)
            setQueryErr(null);
            setLiveList(results);
        } catch (e) {
            if (e instanceof Error) {
                setQueryErr(e);
            }
        }
    }
    return (
        <>
            <form onSubmit={handleSubmit}>
                <input placeholder="query" name="query" />
            </form>
            {queryErr ? <ErrorBox message={queryErr.message} /> : null}
            <LiveList list={liveList} />
        </>
    );
}

interface ErrorBoxProps {
    message: string | null
};

export function ErrorBox({ message }: ErrorBoxProps) {
    return (
        <div className="error-box">
            <p>Error: {message}</p>
        </div>
    )
}

export function Header() {
    return (
        <div className="navbar">
            <h2 id="menu-title">apiary.home.2rjus.net</h2>
            <nav className="nav-flex">
                <ul>
                    <li><NavLink to="/" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Home</NavLink></li>
                    <li><NavLink to="/stats" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Stats</NavLink></li>
                    <li><NavLink to="/live" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Live</NavLink></li>
                    <li><NavLink to="/query" className={({ isActive }) => isActive ? "menu-link-active" : "menu-link"}>Query</NavLink></li>
                </ul>
            </nav>
        </div>
    );
}

export interface SubMenuProps {
    items: Array<{ name: string, active: () => boolean, onClick: () => void }>
}

export function SubMenu({ items }: SubMenuProps) {
    return (
        <nav className="submenu">
            <ul>
                {items.map((item) => {
                    return <li>
                        <a
                            href="#"
                            className={item.active() ? "sub-menu-link-active" : "sub-menu-link"}
                            onClick={item.onClick}>{item.name}</a>
                    </li>
                })}
            </ul>
        </nav>
    )
}

const rootElement = document.getElementById('root');
if (rootElement) {
    const root = createRoot(rootElement);
    let api: ApiaryAPI;
    if (process.env.NODE_ENV === "production") {
        api = new ApiaryAPIClient();
    } else {
        api = new DummyApiaryAPIClient();
    }


    root.render(
        <App api={api} />
    );
}
