'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Home, Search, PlusCircle, MessageCircle, User, Briefcase, MapPin, Users } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
import { useRegion } from '@/contexts/RegionContext';
import { useMessages } from '@/contexts/MessagesContext';
import { UnreadBadge } from '@/components/ui/unread-badge';
import { DEFAULT_REGION_SLUG } from '@/lib/region';
import { buildPostJobAuthUrl } from '@/lib/createJob';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';

function buildPublicNav(
  homePath: string,
  jobsPath: string,
  mapPath: string,
  workersPath: string
) {
  if (!JOBS_FEATURE_ENABLED) {
    return [
      { href: homePath, icon: Home, label: 'Home' },
      { href: workersPath, icon: Search, label: 'Workers' },
      { href: mapPath, icon: MapPin, label: 'Map' },
      { href: '/categories', icon: Users, label: 'Trades' },
      { href: '/become-worker', icon: PlusCircle, label: 'Join' },
    ];
  }

  return [
    { href: homePath, icon: Home, label: 'Home' },
    { href: jobsPath, icon: Briefcase, label: 'Jobs' },
    { href: mapPath, icon: MapPin, label: 'Map' },
    { href: workersPath, icon: Search, label: 'Workers' },
    { href: buildPostJobAuthUrl(), icon: PlusCircle, label: 'Post' },
  ];
}

const customerNavWithJobs = [
  { href: '/customer/dashboard', icon: Home, label: 'Home' },
  { href: '/customer/jobs', icon: Briefcase, label: 'Jobs' },
  { href: '/customer/jobs/create', icon: PlusCircle, label: 'Post' },
  { href: '/customer/messages', icon: MessageCircle, label: 'Chat' },
  { href: '/customer/profile', icon: User, label: 'Profile' },
];

const customerNavDirectory = [
  { href: '/customer/dashboard', icon: Home, label: 'Home' },
  { href: '/workers', icon: Search, label: 'Workers' },
  { href: '/customer/hire-invitations', icon: Briefcase, label: 'Hires' },
  { href: '/customer/messages', icon: MessageCircle, label: 'Chat' },
  { href: '/customer/profile', icon: User, label: 'Profile' },
];

const workerNavWithJobs = [
  { href: '/worker/dashboard', icon: Home, label: 'Home' },
  { href: '/worker/jobs', icon: Briefcase, label: 'Jobs' },
  { href: '/worker/messages', icon: MessageCircle, label: 'Chat' },
  { href: '/worker/profile', icon: User, label: 'Profile' },
];

const workerNavDirectory = [
  { href: '/worker/dashboard', icon: Home, label: 'Home' },
  { href: '/worker/hire-invitations', icon: Briefcase, label: 'Hires' },
  { href: '/worker/messages', icon: MessageCircle, label: 'Chat' },
  { href: '/worker/profile', icon: User, label: 'Profile' },
];

export function BottomNav() {
  const pathname = usePathname();
  const { user } = useAuth();
  const { homePath, regionPath, slug } = useRegion();
  const { unreadCount: messageUnreadCount } = useMessages();

  const useRegionalLinks = slug !== DEFAULT_REGION_SLUG;
  const publicNav = buildPublicNav(
    homePath(),
    useRegionalLinks ? regionPath('/jobs') : '/jobs',
    useRegionalLinks ? regionPath('/map') : '/map',
    useRegionalLinks ? regionPath('/workers') : '/workers'
  );

  const hideOnPaths = ['/login', '/register', '/admin'];
  if (hideOnPaths.some((p) => pathname.startsWith(p))) return null;

  const isChatThread = /^\/(customer|worker)\/messages\/[^/]+$/.test(pathname);
  if (isChatThread) return null;

  let nav = publicNav;
  if (user?.role === 'CUSTOMER') {
    nav = JOBS_FEATURE_ENABLED ? customerNavWithJobs : customerNavDirectory;
  }
  if (user?.role === 'WORKER') {
    nav = JOBS_FEATURE_ENABLED ? workerNavWithJobs : workerNavDirectory;
  }
  if (user?.role === 'ADMIN') return null;

  return (
    <nav data-bottom-nav className="fixed bottom-0 left-0 right-0 z-50 border-t border-border bg-surface safe-area-bottom md:hidden shadow-[0_-4px_12px_rgba(15,23,42,0.06)]">
      <div className="flex items-center justify-around px-1 py-1.5">
        {nav.map((item) => {
          const isActive = pathname === item.href || pathname.startsWith(item.href + '/');
          const isMessages = item.href.includes('/messages');
          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                'flex flex-col items-center gap-0.5 px-2 py-1.5 rounded-lg min-w-[56px] transition-colors',
                isActive ? 'text-primary' : 'text-slate-400'
              )}
            >
              <span className="relative">
                <item.icon className={cn('h-5 w-5', isActive && 'stroke-[2.5]')} />
                {isMessages && (
                  <UnreadBadge
                    count={messageUnreadCount}
                    className="absolute -top-1.5 -right-2"
                  />
                )}
              </span>
              <span className="text-[10px] font-semibold">{item.label}</span>
            </Link>
          );
        })}
      </div>
    </nav>
  );
}
