
'use client';

import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { useSession, signOut } from 'next-auth/react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  BarChart3, 
  Building2, 
  Calculator, 
  Calendar,
  FileText, 
  Home, 
  Menu,
  Settings, 
  Shield, 
  Upload,
  User,
  Users,
  X,
  Bell,
  Search,
  ChevronDown,
  LogOut,
  UserCircle,
  Briefcase,
  Trophy,
  Rocket,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';

interface NavItem {
  title: string;
  href: string;
  icon: any;
  badge?: number;
  roles: string[];
  description?: string;
}

const navigationItems: NavItem[] = [
  {
    title: 'Dashboard',
    href: '/dashboard',
    icon: Home,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR', 'CUSTOMER'],
    description: 'Overview and analytics',
  },
  {
    title: 'Marketplace',
    href: '/marketplace',
    icon: Briefcase,
    roles: ['CONTRACTOR'],
    description: 'Purchase available contracts',
  },
  {
    title: 'Leads',
    href: '/leads',
    icon: Users,
    roles: ['ADMIN', 'SALES'],
    description: 'Lead management and qualification',
  },
  {
    title: 'Quotes',
    href: '/quotes',
    icon: Calculator,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR', 'CUSTOMER'],
    description: 'Quote builder and management',
  },
  {
    title: 'Contracts',
    href: '/contracts',
    icon: FileText,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR', 'CUSTOMER'],
    description: 'Contract generation and tracking',
  },
  {
    title: 'Calendar',
    href: '/calendar',
    icon: Calendar,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR'],
    description: 'Schedule and sync events',
  },
  {
    title: 'Performance',
    href: '/contractors/performance',
    icon: Trophy,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR'],
    description: 'Contractor performance and leaderboards',
  },
  {
    title: 'Cockpit',
    href: '/cockpit',
    icon: BarChart3,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR'],
    description: 'Operational command center',
  },
  {
    title: 'Phase 3',
    href: '/phase3',
    icon: Rocket,
    roles: ['ADMIN', 'SALES'],
    description: 'Advanced features and automation',
  },
  {
    title: 'Admin Oversight',
    href: '/admin/oversight',
    icon: Shield,
    roles: ['ADMIN'],
    description: 'Advanced filtering and oversight',
  },
  {
    title: 'CRM Export',
    href: '/export',
    icon: Upload,
    roles: ['ADMIN', 'SALES'],
    description: 'Export tracking and handoff',
  },
  {
    title: 'Analytics',
    href: '/analytics',
    icon: BarChart3,
    roles: ['ADMIN', 'SALES'],
    description: 'Performance metrics and reports',
  },
  {
    title: 'Settings',
    href: '/settings',
    icon: Settings,
    roles: ['ADMIN', 'SALES', 'CONTRACTOR', 'CUSTOMER'],
    description: 'Account and system settings',
  },
];

export function MainNav() {
  const [isOpen, setIsOpen] = useState(false);
  const { data: session } = useSession() || {};
  const pathname = usePathname();
  
  const userRole = session?.user?.role;
  const userName = session?.user?.name || session?.user?.email;
  const userInitials = userName?.split(' ').map(n => n[0]).join('').toUpperCase() || 'U';
  
  // Filter navigation items based on user role
  const filteredNavItems = navigationItems.filter(item => 
    userRole && item.roles.includes(userRole)
  );

  const handleSignOut = async () => {
    await signOut({ callbackUrl: '/' });
  };

  return (
    <nav className="sticky top-0 z-50 w-full bg-[#1e5a5a] backdrop-blur-sm border-b border-[#1e5a5a]/20 shadow-md">
      <div className="max-w-app mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16">
          {/* Logo and Brand */}
          <div className="flex items-center">
            <Link href="/dashboard" className="flex items-center space-x-2">
              <div className="relative w-40 h-12">
                <Image 
                  src="/brand-logo.png" 
                  alt="Quote2ContractPro" 
                  fill
                  priority
                  className="object-contain"
                />
              </div>
            </Link>
          </div>

          {/* Desktop Navigation */}
          <div className="hidden md:flex items-center space-x-1">
            {filteredNavItems.slice(0, 6).map((item) => {
              const isActive = pathname === item.href;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={cn(
                    'px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 relative group',
                    isActive
                      ? 'text-[#c8d946] bg-white/10'
                      : 'text-white hover:text-[#c8d946] hover:bg-white/5'
                  )}
                >
                  <div className="flex items-center space-x-2">
                    <item.icon className="w-4 h-4" />
                    <span>{item.title}</span>
                    {item.badge && (
                      <Badge variant="secondary" className="ml-1 text-xs bg-[#c8d946] text-[#1e5a5a]">
                        {item.badge}
                      </Badge>
                    )}
                  </div>
                  {isActive && (
                    <motion.div
                      className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#c8d946]"
                      layoutId="activeTab"
                      initial={false}
                      transition={{ type: "spring", stiffness: 500, damping: 30 }}
                    />
                  )}
                </Link>
              );
            })}
          </div>

          {/* Right side items */}
          <div className="flex items-center space-x-4">
            {/* Search Button */}
            <Button variant="ghost" size="sm" className="hidden sm:flex text-white hover:text-[#c8d946] hover:bg-white/10">
              <Search className="w-4 h-4" />
            </Button>

            {/* Notifications */}
            <Button variant="ghost" size="sm" className="relative text-white hover:text-[#c8d946] hover:bg-white/10">
              <Bell className="w-4 h-4" />
              <span className="absolute -top-1 -right-1 w-2 h-2 bg-[#c8d946] rounded-full"></span>
            </Button>

            {/* User Menu */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 rounded-full p-0 hover:bg-white/10">
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={session?.user?.image || undefined} />
                    <AvatarFallback className="bg-[#c8d946] text-[#1e5a5a] text-xs font-semibold">
                      {userInitials}
                    </AvatarFallback>
                  </Avatar>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-64">
                <DropdownMenuLabel className="font-normal">
                  <div className="flex flex-col space-y-1">
                    <p className="text-sm font-medium leading-none">{userName}</p>
                    <p className="text-xs leading-none text-muted-foreground">
                      {session?.user?.email}
                    </p>
                    <div className="flex items-center space-x-2 mt-1">
                      <Badge variant="outline" className="text-xs">
                        {userRole?.toLowerCase()}
                      </Badge>
                      {session?.user?.companyName && (
                        <Badge variant="secondary" className="text-xs">
                          {session.user.companyName}
                        </Badge>
                      )}
                    </div>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem asChild>
                  <Link href="/profile" className="cursor-pointer">
                    <UserCircle className="w-4 h-4 mr-2" />
                    Profile
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href="/settings" className="cursor-pointer">
                    <Settings className="w-4 h-4 mr-2" />
                    Settings
                  </Link>
                </DropdownMenuItem>
                {session?.user?.isPartner && (
                  <DropdownMenuItem asChild>
                    <Link href="/partner-dashboard" className="cursor-pointer">
                      <Briefcase className="w-4 h-4 mr-2" />
                      Partner Dashboard
                    </Link>
                  </DropdownMenuItem>
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem 
                  onClick={handleSignOut}
                  className="cursor-pointer text-red-600"
                >
                  <LogOut className="w-4 h-4 mr-2" />
                  Sign out
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Mobile menu button */}
            <Button
              variant="ghost"
              size="sm"
              className="md:hidden text-white hover:text-[#c8d946] hover:bg-white/10"
              onClick={() => setIsOpen(!isOpen)}
            >
              {isOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
            </Button>
          </div>
        </div>

        {/* Mobile Navigation */}
        <AnimatePresence>
          {isOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.2 }}
              className="md:hidden border-t border-white/20 bg-[#1e5a5a]"
            >
              <div className="px-2 pt-2 pb-3 space-y-1">
                {filteredNavItems.map((item) => {
                  const isActive = pathname === item.href;
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={() => setIsOpen(false)}
                      className={cn(
                        'block px-3 py-2 rounded-md text-base font-medium transition-colors',
                        isActive
                          ? 'text-[#c8d946] bg-white/10'
                          : 'text-white hover:text-[#c8d946] hover:bg-white/5'
                      )}
                    >
                      <div className="flex items-center space-x-3">
                        <item.icon className="w-5 h-5" />
                        <div>
                          <div className="font-medium">{item.title}</div>
                          {item.description && (
                            <div className="text-xs text-white/70">
                              {item.description}
                            </div>
                          )}
                        </div>
                        {item.badge && (
                          <Badge variant="secondary" className="ml-auto bg-[#c8d946] text-[#1e5a5a]">
                            {item.badge}
                          </Badge>
                        )}
                      </div>
                    </Link>
                  );
                })}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </nav>
  );
}
