"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import useAxios from "@/hooks/useAxios";
import Cookies from "js-cookie";
import { cn } from "@/lib/utils";
import { useScrollDirection } from "@/hooks/useScrollDirection";
import { useNetworkStatus } from "@/hooks/useNetworkStatus";
import { useQueryClient } from "@tanstack/react-query";

function Header() {
  const { request } = useAxios();
  const queryClient = useQueryClient();
  const { state, startSync, endSync, isOffline, isSyncing } = useNetworkStatus();
  const [unreadMessages, setUnreadMessages] = useState<number>();
  const [unreadNotification, setUnreadNotification] = useState<number>();
  const { compact, hidden } = useScrollDirection(20);
  const token = Cookies.get("token");

  const refreshBadges = async () => {
    const [notif, msgs] = await Promise.all([
      request<{ newNotificationsCount: number }>(
        "GET",
        `/notifications/unread`,
        null,
        { noToast: true }
      ),
      request<{ unread_messages_count: number }>(
        "GET",
        `/messages/unread`,
        null,
        { noToast: true }
      ),
    ]);
    setUnreadNotification(notif?.newNotificationsCount);
    setUnreadMessages(msgs?.unread_messages_count);
  };

  useEffect(() => {
    if (!token) return;
    void refreshBadges();
  }, [request, token]);

  const prevNetwork = React.useRef(state);
  useEffect(() => {
    const wasOffline = prevNetwork.current === "offline";
    prevNetwork.current = state;
    if (!wasOffline || state !== "online" || !token) return;
    startSync();
    const t = window.setTimeout(async () => {
      await queryClient.invalidateQueries({ queryKey: ["posts"] });
      try {
        await refreshBadges();
      } finally {
        endSync();
      }
    }, 800);
    return () => window.clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state, token]);

  const iconBtn = cn(
    "gentle-transition relative flex h-9 w-9 shrink-0 items-center justify-center rounded-full",
    "hover:bg-black/5 active:scale-90 dark:hover:bg-white/10"
  );

  const badge = (count?: number) =>
    count ? (
      <span className="absolute -left-0.5 -top-0.5 z-10 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-red-500 px-1 text-[9px] font-bold text-white">
        {count > 99 ? "99+" : count}
      </span>
    ) : null;

  const headerBarClass = cn(
    "gentle-transition mx-auto flex items-center",
    compact
      ? "glass-panel safari-header-pill w-full max-w-lg justify-between rounded-full px-2 py-2 shadow-lg"
      : "glass-panel w-full max-w-none justify-center rounded-none border-b border-white/30 px-4 py-1 dark:border-white/5",
    isOffline && "header-offline",
    isSyncing && "header-syncing"
  );

  const LogoBlock = () => (
    <div className="relative flex items-center justify-center">
      <Link
        href="/"
        className={cn(
          "brand-logo gentle-transition active:scale-95",
          isSyncing && "pointer-events-none"
        )}
        aria-label="خانه"
      >
        <Image
          alt="مادستاگرام"
          width={compact ? 124 : 130}
          height={compact ? 34 : 36}
          className={cn(
            "h-auto w-auto dark:invert gentle-transition",
            compact ? "h-[30px] max-w-[124px]" : "h-8 max-w-[130px]"
          )}
          src="/images/icons/logo.svg"
          priority
        />
      </Link>
      {isSyncing && (
        <span className="absolute text-[11px] font-medium text-neutral-600 dark:text-neutral-300">
          در حال بروزرسانی
          <span className="header-syncing-dots mr-0.5 inline-flex">
            <span>.</span>
            <span>.</span>
            <span>.</span>
          </span>
        </span>
      )}
    </div>
  );

  return (
    <header
      className={cn(
        "sticky top-0 z-[999] pt-[env(safe-area-inset-top)] transition-all duration-300 ease-in-out will-change-transform",
        compact ? "py-2" : "py-3",
        hidden
          ? "pointer-events-none -translate-y-[130%] opacity-0"
          : "translate-y-0 opacity-100"
      )}
    >
      <div className={headerBarClass}>
        {compact ? (
          <>
            <Link
              href="/settings/chats"
              className={cn(iconBtn, "-mr-0.5")}
              aria-label="پیام‌ها"
            >
              {badge(unreadMessages)}
              <Image
                alt=""
                width={22}
                height={22}
                className="dark:invert"
                src="/images/icons/sms.svg"
              />
            </Link>
            <LogoBlock />
            <Link
              href="/settings/notifications"
              className={cn(iconBtn, "-ml-0.5")}
              aria-label="اعلان‌ها"
            >
              {badge(unreadNotification)}
              <Image
                alt=""
                width={22}
                height={22}
                className="dark:invert"
                src="/images/icons/notification.svg"
              />
            </Link>
          </>
        ) : (
          <div className="flex w-full max-w-3xl items-center justify-between px-2">
            <Link href="/settings/chats" className={iconBtn} aria-label="پیام‌ها">
              {badge(unreadMessages)}
              <Image
                alt=""
                width={24}
                height={24}
                className="dark:invert"
                src="/images/icons/sms.svg"
              />
            </Link>
            <LogoBlock />
            <Link
              href="/settings/notifications"
              className={iconBtn}
              aria-label="اعلان‌ها"
            >
              {badge(unreadNotification)}
              <Image
                alt=""
                width={24}
                height={24}
                className="dark:invert"
                src="/images/icons/notification.svg"
              />
            </Link>
          </div>
        )}
      </div>
    </header>
  );
}

export default Header;
