import {
  mdiCartOutline,
  mdiFileDocumentOutline,
  mdiHistory,
  mdiLogout,
  mdiMapMarkerOutline,
  mdiPackageVariantClosed,
} from "@mdi/js";
import jwt from "jsonwebtoken";
import { useRouter } from "next/router";
import React, { ReactNode, useEffect } from "react";

import BaseIcon from "../components/BaseIcon";
import { useAppDispatch, useAppSelector } from "../stores/hooks";
import { findMe, logoutUser } from "../stores/authSlice";

type Props = {
  children: ReactNode;
};

const navItems = [
  { label: "Catalog", href: "#catalog", icon: mdiCartOutline },
  { label: "PO draft", href: "#purchase-order", icon: mdiFileDocumentOutline },
  { label: "Orders", href: "#orders", icon: mdiHistory },
  { label: "Samples", href: "#samples", icon: mdiPackageVariantClosed },
];

const isStoredTokenValid = (token: string | null) => {
  if (!token) {
    return false;
  }

  const decodedToken = jwt.decode(token) as { exp?: number } | null;
  if (!decodedToken?.exp) {
    return false;
  }

  return new Date().getTime() / 1000 < decodedToken.exp;
};

export default function LayoutBuyerPortal({ children }: Props) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { currentUser } = useAppSelector((state) => state.auth);

  useEffect(() => {
    if (!router.isReady) {
      return;
    }

    const token = localStorage.getItem("token");
    if (!isStoredTokenValid(token)) {
      dispatch(logoutUser());
      const returnTo = encodeURIComponent(router.asPath || "/buyer-portal/");
      router.replace(`/buyer-login?returnTo=${returnTo}`);
      return;
    }

    if (!currentUser) {
      dispatch(findMe());
    }
  }, [currentUser, dispatch, router.isReady, router.asPath]);

  const handleLogout = () => {
    dispatch(logoutUser());
    router.push("/buyer-login?returnTo=%2Fbuyer-portal%2F");
  };

  const buyerName =
    [currentUser?.firstName, currentUser?.lastName].filter(Boolean).join(" ") ||
    currentUser?.email ||
    "Purchasing team";
  const buyerRole = currentUser?.app_role?.name || "Buyer account";

  return (
    <div className="min-h-screen bg-[#f6f3ec] text-slate-950">
      <header className="sticky top-0 z-40 border-b border-stone-200 bg-white/95 backdrop-blur">
        <div className="mx-auto flex max-w-[1440px] flex-col gap-4 px-5 py-4 lg:flex-row lg:items-center lg:justify-between lg:px-8">
          <div className="flex items-center justify-between gap-4">
            <a href="/" className="min-w-0">
              <p className="text-xs font-bold uppercase tracking-[0.24em] text-emerald-700">
                Northstar Foodservice
              </p>
              <p className="truncate text-lg font-semibold text-slate-950">
                Buyer Portal
              </p>
            </a>

            <button
              type="button"
              onClick={handleLogout}
              className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-stone-200 text-slate-600 hover:border-emerald-200 hover:bg-emerald-50 hover:text-emerald-700 lg:hidden"
              aria-label="Sign out"
            >
              <BaseIcon path={mdiLogout} size={18} />
            </button>
          </div>

          <nav className="flex gap-2 overflow-x-auto pb-1 lg:pb-0">
            {navItems.map((item) => (
              <a
                key={item.href}
                href={item.href}
                className="inline-flex shrink-0 items-center gap-2 rounded-full border border-stone-200 bg-stone-50 px-4 py-2 text-sm font-semibold text-slate-700 hover:border-emerald-200 hover:bg-emerald-50 hover:text-emerald-800"
              >
                <BaseIcon path={item.icon} size={16} />
                {item.label}
              </a>
            ))}
          </nav>

          <div className="hidden items-center gap-3 lg:flex">
            <div className="flex items-center gap-2 rounded-full border border-stone-200 bg-stone-50 px-4 py-2 text-sm font-semibold text-slate-700">
              <BaseIcon path={mdiMapMarkerOutline} size={16} />
              Harbor Table
            </div>
            <div className="max-w-[260px] rounded-full bg-slate-950 px-4 py-2 text-sm font-semibold text-white">
              <span className="block truncate">{buyerName}</span>
              <span className="block truncate text-[11px] font-semibold text-slate-300">
                {buyerRole}
              </span>
            </div>
            <button
              type="button"
              onClick={handleLogout}
              className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-stone-200 bg-white text-slate-600 hover:border-rose-200 hover:bg-rose-50 hover:text-rose-700"
              aria-label="Sign out"
            >
              <BaseIcon path={mdiLogout} size={18} />
            </button>
          </div>
        </div>
      </header>

      <main>{children}</main>
    </div>
  );
}
