import {
    Bell,
    CalendarDays,
    ChevronDown,
    CircleHelp,
    Clock,
    Info,
    LogOut,
    Moon,
    Settings2,
    SlidersHorizontal,
    Sun,
    User,
} from "lucide-react";
import { useState } from "react";
import { AppPage } from "../../app/App";

type TopBarProps = {
    connected: boolean;
    lastTimestamp: string | null;
    notificationCount: number;
    userInitials: string;
    theme: "dark" | "light";
    activePage: AppPage | null;
    onToggleTheme: () => void;
};

const RADIUS = "rounded-[5px]";

export function TopBar({
    connected,
    lastTimestamp,
    notificationCount,
    userInitials,
    theme,
    activePage,
    onToggleTheme,
}: TopBarProps) {
    const [notificationsOpen, setNotificationsOpen] = useState(false);
    const [userMenuOpen, setUserMenuOpen] = useState(false);

    const isDark = theme === "dark";
    const ThemeIcon = isDark ? Moon : Sun;

    const systemDate = lastTimestamp ? new Date(lastTimestamp) : null;

    const formattedTime = systemDate
        ? systemDate.toLocaleTimeString("pt-PT", {
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
        })
        : "--:--:--";

    const formattedDate = systemDate
        ? systemDate.toLocaleDateString("pt-PT", {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
        })
        : "--/--/----";

    const dropdownClass = isDark
        ? `absolute right-0 top-12 z-50 ${RADIUS} border border-white/[0.04] bg-[#111827] shadow-2xl`
        : `absolute right-0 top-12 z-50 ${RADIUS} border border-slate-200 bg-white shadow-xl`;

    const dropdownTitleClass = isDark
        ? "text-sm font-bold text-slate-100"
        : "text-sm font-bold text-slate-950";

    const mutedTextClass = "text-slate-500";

    const menuItemClass = isDark
        ? `flex w-full items-center gap-3 ${RADIUS} px-3 py-2.5 text-left text-sm font-medium text-slate-300 transition hover:bg-white/[0.05] hover:text-slate-100`
        : `flex w-full items-center gap-3 ${RADIUS} px-3 py-2.5 text-left text-sm font-medium text-slate-700 transition hover:bg-slate-100 hover:text-slate-950`;

    const dividerClass = isDark ? "my-2 h-px bg-white/10" : "my-2 h-px bg-slate-200";

    return (
        <header
            className={
                isDark
                    ? "flex h-16 items-center justify-between bg-[#0b1220] px-6"
                    : "flex h-16 items-center justify-between border-b border-slate-200 bg-slate-50 px-6"
            }
        >
            <div>
                <h1
                    className={
                        isDark
                            ? "text-2xl font-black tracking-[-0.04em] text-slate-100"
                            : "text-2xl font-black tracking-[-0.04em] text-slate-950"
                    }
                >
                    {pageTitle(activePage)}
                </h1>
            </div>

            <div
                className={
                    isDark
                        ? "flex items-center gap-5 text-sm text-slate-400"
                        : "flex items-center gap-5 text-sm text-slate-500"
                }
            >
                <div
                    className={
                        isDark
                            ? `hidden items-center gap-2 ${RADIUS} border border-white/[0.04] bg-white/[0.03] px-3 py-1.5 md:flex`
                            : `hidden items-center gap-2 ${RADIUS} border border-slate-200 bg-white px-3 py-1.5 md:flex`
                    }
                >
                    <span
                        className={
                            connected
                                ? "h-2 w-2 rounded-full bg-emerald-500"
                                : "h-2 w-2 rounded-full bg-red-500"
                        }
                    />

                    <span className="font-medium">
                        {connected ? "Ligado ao sistema" : "Sistema desligado"}
                    </span>
                </div>

                <div className="hidden items-center gap-2 lg:flex">
                    <Clock className="h-4 w-4 text-slate-500" />
                    <span>{formattedTime}</span>
                </div>

                <div className="hidden items-center gap-2 lg:flex">
                    <CalendarDays className="h-4 w-4 text-slate-500" />
                    <span>{formattedDate}</span>
                </div>

                <div className="relative">
                    <button
                        type="button"
                        onClick={() => {
                            setNotificationsOpen(!notificationsOpen);
                            setUserMenuOpen(false);
                        }}
                        className={
                            isDark
                                ? `relative grid h-10 w-10 place-items-center ${RADIUS} border border-white/[0.04] bg-white/[0.03] text-slate-400 transition hover:bg-white/[0.06] hover:text-slate-100`
                                : `relative grid h-10 w-10 place-items-center ${RADIUS} border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-100 hover:text-slate-950`
                        }
                    >
                        <Bell className="h-5 w-5" />

                        {notificationCount > 0 && (
                            <span className="absolute -right-1 -top-1 min-w-5 rounded-full bg-slate-900 px-1.5 text-[10px] font-bold leading-5 text-white">
                                {notificationCount}
                            </span>
                        )}
                    </button>

                    {notificationsOpen && (
                        <div className={`${dropdownClass} w-80 p-4`}>
                            <div className="mb-3 flex items-center justify-between">
                                <span className={dropdownTitleClass}>Notificações</span>

                                <span className={`text-xs ${mutedTextClass}`}>
                                    {notificationCount} novas
                                </span>
                            </div>

                            <div
                                className={
                                    isDark
                                        ? `${RADIUS} border border-white/[0.04] bg-white/[0.03] px-4 py-4 text-sm text-slate-400`
                                        : `${RADIUS} border border-slate-200 bg-slate-50 px-4 py-4 text-sm text-slate-500`
                                }
                            >
                                Sem notificações.
                            </div>
                        </div>
                    )}
                </div>

                <div className="relative">
                    <button
                        type="button"
                        onClick={() => {
                            setUserMenuOpen(!userMenuOpen);
                            setNotificationsOpen(false);
                        }}
                        className={
                            isDark
                                ? `flex items-center gap-2 ${RADIUS} border border-white/[0.04] bg-white/[0.03] py-1 pl-1 pr-3 transition hover:bg-white/[0.06]`
                                : `flex items-center gap-2 ${RADIUS} border border-slate-200 bg-white py-1 pl-1 pr-3 transition hover:bg-slate-100`
                        }
                    >
                        <span
                            className={
                                isDark
                                    ? "flex h-8 w-8 items-center justify-center rounded-full bg-slate-200 text-xs font-black text-slate-950"
                                    : "flex h-8 w-8 items-center justify-center rounded-full bg-slate-900 text-xs font-black text-white"
                            }
                        >
                            {userInitials}
                        </span>

                        <ChevronDown
                            className={`h-4 w-4 text-slate-500 transition-transform ${userMenuOpen ? "rotate-180" : ""
                                }`}
                        />
                    </button>

                    {userMenuOpen && (
                        <div className={`${dropdownClass} w-64 p-3`}>
                            <div className={`mb-3 flex items-center gap-3 ${RADIUS} px-2 py-2`}>
                                <div
                                    className={
                                        isDark
                                            ? "flex h-10 w-10 items-center justify-center rounded-full bg-slate-200 text-sm font-black text-slate-950"
                                            : "flex h-10 w-10 items-center justify-center rounded-full bg-slate-900 text-sm font-black text-white"
                                    }
                                >
                                    {userInitials}
                                </div>

                                <div>
                                    <div className={dropdownTitleClass}>admin</div>

                                    <div className={`text-xs ${mutedTextClass}`}>
                                        Administrador
                                    </div>
                                </div>
                            </div>

                            <div className={dividerClass} />

                            <button type="button" className={menuItemClass}>
                                <User className={`h-4 w-4 ${mutedTextClass}`} />
                                Perfil
                            </button>

                            <button type="button" className={menuItemClass}>
                                <SlidersHorizontal className={`h-4 w-4 ${mutedTextClass}`} />
                                Preferências
                            </button>

                            <button
                                type="button"
                                onClick={onToggleTheme}
                                className={
                                    isDark
                                        ? `flex w-full items-center justify-between ${RADIUS} px-3 py-2.5 text-left text-sm font-medium text-slate-300 transition hover:bg-white/[0.05] hover:text-slate-100`
                                        : `flex w-full items-center justify-between ${RADIUS} px-3 py-2.5 text-left text-sm font-medium text-slate-700 transition hover:bg-slate-100 hover:text-slate-950`
                                }
                            >
                                <span className="flex items-center gap-3">
                                    <Settings2 className={`h-4 w-4 ${mutedTextClass}`} />
                                    Tema
                                </span>

                                <ThemeIcon className="h-4 w-4 text-slate-500" />
                            </button>

                            <div className={dividerClass} />

                            <button type="button" className={menuItemClass}>
                                <CircleHelp className={`h-4 w-4 ${mutedTextClass}`} />
                                Ajuda
                            </button>

                            <button type="button" className={menuItemClass}>
                                <Info className={`h-4 w-4 ${mutedTextClass}`} />
                                Sobre
                            </button>

                            <div className={dividerClass} />

                            <button
                                type="button"
                                className={
                                    isDark
                                        ? `flex w-full items-center gap-3 ${RADIUS} px-3 py-2.5 text-left text-sm font-medium text-red-300 transition hover:bg-red-500/10`
                                        : `flex w-full items-center gap-3 ${RADIUS} px-3 py-2.5 text-left text-sm font-medium text-red-600 transition hover:bg-red-50`
                                }
                            >
                                <LogOut className="h-4 w-4" />
                                Terminar sessão
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </header>
    );
}

function pageTitle(page: AppPage | null) {
    switch (page) {
        case "dashboard":
            return "";

        case "maincharts":
            return "Gráficos Gerais";

        case "meteo":
            return "Previsões Meteorológicas";
        case "meteoCharts":
            return "Gráficos Meteorológicos";

        case "synoptic":
            return "Sinótico";

        case "settings":
            return "Configurações";

        case "console":
            return "Consola (VNC)";

        // ALL CLIMATE PAGES
        case "climate":
        case "climateLighting":
        case "climateVentilation":
            return "Clima";

        case "climateCharts":
            return "Gráficos Climáticos";

        // ALL IRRIGATION / REGA PAGES
        case "irrigation":
        case "irrigationCharts":
        case "irrigationFilters":
        case "irrigationConsumption":
        case "irrigationDrainage":
            return "Rega";

        default:
            return "Painel Principal";
    }
}