"use client";

import Link from 'next/link';
import { useNavigation } from '@/hooks/useNavigation';
import { ReactNode, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';

interface NavLinkProps {
  readonly href: string;
  readonly children: ReactNode;
}

export function NavLink({ href, children }: NavLinkProps) {
  const { activePath } = useNavigation();
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [isNavigating, setIsNavigating] = useState(false);
  const isActive = activePath === href;

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    // Don't navigate if already on this page
    if (isActive) {
      e.preventDefault();
      return;
    }

    e.preventDefault();
    
    // Trigger global loading indicator
    window.dispatchEvent(new Event('navigationStart'));
    
    // Immediate visual feedback
    setIsNavigating(true);
    
    // Use startTransition for smooth navigation
    startTransition(() => {
      router.push(href);
      // Reset after a short delay to ensure user sees feedback
      setTimeout(() => setIsNavigating(false), 300);
    });
  };

  // Base classes with touch feedback
  const mobileBaseClasses = "flex flex-col items-center justify-center flex-1 py-2 px-1 text-xs transition-all duration-200 active:scale-90 touch-manipulation no-select";
  const desktopBaseClasses = "px-3 py-2 text-sm font-medium transition-all duration-200 rounded-md no-select";

  // Active/Inactive classes
  const mobileActive = "text-brand-600 dark:text-brand-400 hover:text-brand-700 dark:hover:text-brand-500";
  const mobileInactive = "text-gray-500 hover:text-brand-600 dark:hover:text-brand-400";
  const desktopActive = "bg-brand-50 text-gray-900 dark:bg-brand-950 dark:text-white";
  const desktopInactive = "text-gray-500 hover:text-brand-900 dark:hover:text-brand-400";

  // Loading/pending state classes
  const loadingClasses = (isPending || isNavigating) ? "opacity-70 scale-90" : "opacity-100 scale-100";
  const navColor = isActive ? "var(--color-brand-500)" : "var(--color-secondary-500)";

  // Combining both sets of classes and applying the active/inactive classes
  const combinedClasses = `${mobileBaseClasses} ${desktopBaseClasses} ${loadingClasses} ${isActive ? `${mobileActive} ${desktopActive}` : `${mobileInactive} ${desktopInactive}`}`;

  return (
    <Link 
      href={href} 
      className={combinedClasses}
      style={{ color: navColor }}
      onClick={handleClick}
    >
      {children}
    </Link>
  );
}
