"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { useSelector, useDispatch } from "react-redux";
import { selectIsAuthenticated, logout, selectCurrentUser } from "@/redux/slices/authSlice";
import { useLogoutMutation } from "@/redux/apis/authApi";
import { User, LogOut, ChevronDown, Bookmark, CheckCircle } from "lucide-react";

export default function Header() {
  const [mounted, setMounted] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [profileDropdownOpen, setProfileDropdownOpen] = useState(false);
  const pathname = usePathname();
  const router = useRouter();
  const dispatch = useDispatch();

  const isAuthenticated = useSelector(selectIsAuthenticated);
  const user = useSelector(selectCurrentUser);
  const [logoutMutation] = useLogoutMutation();

  useEffect(() => {
    setMounted(true);
  }, []);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest(".profile-dropdown-container")) {
        setProfileDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleLogout = async () => {
    try {
      await logoutMutation();
    } catch (error) {
      console.error("Logout failed", error);
    } finally {
      dispatch(logout());
      setProfileDropdownOpen(false);
      setMobileMenuOpen(false);
      router.push("/login");
    }
  };

  const navLinks = [
    { name: "Home", href: "/" },
    { name: "About", href: "/about" },
    { name: "Categories", href: "/categories" },
    { name: "Gallery", href: "/gallery" },
    { name: "Finance", href: "/finance" },
    { name: "Tender Winner", href: "/tender-winner" },
    { name: "Blogs", href: "/blogs" },
  ];

  return (
    <motion.header
      initial={{ y: -100, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ duration: 0.6, ease: "easeOut" }}
      className="sticky top-0 left-0 right-0 z-50 w-full bg-white shadow-sm"
    >
      {/* Top Bar */}
      {/* Top Bar */}
      <div className="w-full bg-gradient-to-r from-[#3e2b56] via-purple-700 to-[#d6336c] text-white text-[10px] sm:text-xs py-2 overflow-hidden relative z-50">
        <div className="flex w-fit">
          {[...Array(10)].map((_, i) => (
            <motion.div
              key={i}
              initial={{ x: "-100%" }}
              animate={{ x: "0%" }}
              transition={{
                duration: 25,
                repeat: Infinity,
                ease: "linear",
              }}
              className="flex items-center gap-4 sm:gap-8 px-4 whitespace-nowrap"
            >
              <span className="flex items-center gap-1">
                <span className="opacity-70">SALES:</span>
                <a href="tel:+919423006651" className="hover:text-white/90 transition-colors font-medium">+91 9423 006651</a>
              </span>
              <span className="text-white/40">|</span>
              <span className="flex items-center gap-1">
                <span className="opacity-70">SUPPORT:</span>
                <a href="tel:+910000000000" className="hover:text-white/90 transition-colors font-medium">+91 00000 00000</a>
              </span>
              <span className="text-white/40">|</span>
              <span className="flex items-center gap-1">
                <span className="opacity-70">BIDDING SOLUTION:</span>
                <a href="tel:+910000000000" className="hover:text-white/90 transition-colors font-medium">+91 00000 00000</a>
              </span>
              <span className="text-white/40">|</span>
              <Link href="/plans">
                <button className="bg-[#0099cc] hover:bg-[#0088bb] text-white px-4 py-1 rounded text-[10px] font-bold uppercase tracking-wide transition-colors shadow-sm whitespace-nowrap cursor-pointer relative z-10 pointer-events-auto">
                  BUY PLAN
                </button>
              </Link>
            </motion.div>
          ))}
        </div>
      </div>

      {/* Navbar Container */}
      {/* Navbar Container */}
      <div className="w-full border-b border-gray-100">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
          <div className="flex items-center h-16 sm:h-20">
            {/* Logo */}
            <Link href="/">
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.6, delay: 0.2, ease: "easeOut" }}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="flex items-center gap-2 sm:gap-3 cursor-pointer group"
              >
                <motion.div
                  className="flex flex-col items-center leading-tight"
                  whileHover={{ y: -2 }}
                  transition={{ type: "spring", stiffness: 400, damping: 17 }}
                >
                  <Image
                    src="/Maharashtra Solar.png"
                    alt="Maharashtra Solar"
                    width={140}
                    height={140}
                    className="object-contain transition-transform duration-300 group-hover:rotate-3"
                    priority
                  />

                </motion.div>
              </motion.div>
            </Link>

            {/* Desktop Navigation */}
            <nav className="hidden lg:flex items-center gap-6 ml-auto mr-6">
              {navLinks.map((link, index) => (
                <Link key={link.name} href={link.href}>
                  <motion.div
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: 0.3 + index * 0.1, ease: "easeOut" }}
                    whileHover={{ y: -2 }}
                    whileTap={{ scale: 0.95 }}
                    className="relative group"
                  >
                    <span
                      className={`relative px-2 py-2 font-medium transition-colors duration-300 ${pathname === link.href
                        ? "text-green-600"
                        : "text-gray-700 hover:text-green-600"
                        }`}
                    >
                      {link.name}
                    </span>
                    {pathname === link.href && (
                      <motion.div
                        layoutId="activeNav"
                        className="absolute bottom-0 left-0 right-0 h-0.5 bg-green-600"
                        initial={false}
                        transition={{ type: "spring", stiffness: 380, damping: 30 }}
                      />
                    )}
                  </motion.div>
                </Link>
              ))}
            </nav>

            {/* CTA Buttons - Auth State Aware */}
            <div className="hidden lg:flex items-center gap-3">
              {mounted && isAuthenticated ? (
                <div className="relative profile-dropdown-container">
                  <motion.button
                    initial={{ opacity: 0, x: 20 }}
                    animate={{ opacity: 1, x: 0 }}
                    onClick={() => setProfileDropdownOpen(!profileDropdownOpen)}
                    className="flex items-center gap-2 px-4 py-2 bg-green-50 text-green-700 rounded-full border border-green-200 hover:bg-green-100 transition-colors"
                  >
                    <div className="w-8 h-8 rounded-full bg-green-500 flex items-center justify-center text-white font-bold text-sm">
                      {user?.name ? user.name.charAt(0).toUpperCase() : <User className="w-4 h-4" />}
                    </div>
                    <span className="font-medium max-w-[100px] truncate">{user?.name || "User"}</span>
                    <ChevronDown className="w-4 h-4" />
                  </motion.button>

                  <AnimatePresence>
                    {profileDropdownOpen && (
                      <motion.div
                        initial={{ opacity: 0, y: 10, scale: 0.95 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        exit={{ opacity: 0, y: 10, scale: 0.95 }}
                        className="absolute right-0 mt-2 w-48 bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden py-1 z-50"
                      >
                        <Link
                          href="/profile"
                          className="flex items-center gap-2 px-4 py-3 text-sm text-gray-700 hover:bg-green-50 hover:text-green-700 transition-colors"
                          onClick={() => setProfileDropdownOpen(false)}
                        >
                          <User className="w-4 h-4" /> Profile
                        </Link>
                        <Link
                          href="/saved-tenders"
                          className="flex items-center gap-2 px-4 py-3 text-sm text-gray-700 hover:bg-green-50 hover:text-green-700 transition-colors"
                          onClick={() => setProfileDropdownOpen(false)}
                        >
                          <Bookmark className="w-4 h-4" /> Saved Tenders
                        </Link>
                        <Link
                          href="/tender-applieds"
                          className="flex items-center gap-2 px-4 py-3 text-sm text-gray-700 hover:bg-green-50 hover:text-green-700 transition-colors"
                          onClick={() => setProfileDropdownOpen(false)}
                        >
                          <CheckCircle className="w-4 h-4 text-green-600" /> My Applications
                        </Link>
                        <button
                          onClick={handleLogout}
                          className="w-full flex items-center gap-2 px-4 py-3 text-sm text-red-600 hover:bg-red-50 transition-colors text-left"
                        >
                          <LogOut className="w-4 h-4" /> Logout
                        </button>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              ) : (
                <>
                  <Link href="/login">
                    <motion.button
                      initial={{ opacity: 0, x: 20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ duration: 0.6, delay: 0.5, ease: "easeOut" }}
                      whileHover={{ scale: 1.05, y: -2 }}
                      whileTap={{ scale: 0.95 }}
                      className="px-5 py-2.5 text-green-600 font-medium hover:bg-green-50 rounded-full transition-all duration-300 border border-transparent hover:border-green-200 shadow-sm hover:shadow-md"
                    >
                      Login
                    </motion.button>
                  </Link>
                  <Link href="/register">
                    <motion.button
                      initial={{ opacity: 0, x: 20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ duration: 0.6, delay: 0.6, ease: "easeOut" }}
                      whileHover={{ scale: 1.05, y: -2, boxShadow: "0 10px 25px rgba(34, 197, 94, 0.3)" }}
                      whileTap={{ scale: 0.95 }}
                      className="px-5 py-2.5 bg-gradient-to-r from-green-600 to-green-700 text-white rounded-full font-medium transition-all duration-300 shadow-md hover:shadow-lg"
                    >
                      Register
                    </motion.button>
                  </Link>
                </>
              )}
            </div>

            {/* Mobile Menu Button */}
            <div className="lg:hidden flex items-center gap-2 ml-auto">
              {mounted && isAuthenticated && (
                <Link href="/profile" className="mr-2">
                  <div className="w-8 h-8 rounded-full bg-green-500 flex items-center justify-center text-white font-bold text-xs">
                    {user?.name ? user.name.charAt(0).toUpperCase() : 'U'}
                  </div>
                </Link>
              )}

              {/* Login Button Removed for Mobile */}

              <motion.button
                whileHover={{ scale: 1.1, rotate: 90 }}
                whileTap={{ scale: 0.9 }}
                className="p-2.5 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-full transition-colors"
                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              >
                <motion.svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  animate={{ rotate: mobileMenuOpen ? 180 : 0 }}
                  transition={{ duration: 0.3 }}
                >
                  {mobileMenuOpen ? (
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  ) : (
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                  )}
                </motion.svg>
              </motion.button>
            </div>
          </div>

          {/* Mobile Menu */}
          <AnimatePresence>
            {mobileMenuOpen && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: "auto", opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.3, ease: "easeInOut" }}
                className="lg:hidden border-t border-gray-200/50 overflow-hidden"
              >
                <nav className="flex flex-col gap-2 py-4">
                  {navLinks.map((link, index) => (
                    <Link key={link.name} href={link.href}>
                      <motion.div
                        initial={{ x: -20, opacity: 0 }}
                        animate={{ x: 0, opacity: 1 }}
                        exit={{ x: -20, opacity: 0 }}
                        transition={{ delay: index * 0.05, duration: 0.3 }}
                        whileHover={{ x: 4 }}
                        whileTap={{ scale: 0.98 }}
                        onClick={() => setMobileMenuOpen(false)}
                        className={`px-4 py-3 font-medium transition-colors duration-300 ${pathname === link.href
                          ? "text-green-600"
                          : "text-gray-700 hover:text-green-600"
                          }`}
                      >
                        {link.name}
                      </motion.div>
                    </Link>
                  ))}
                  <div className="flex gap-3 px-4 pt-2">
                    {mounted && isAuthenticated ? (
                      <div className="w-full flex flex-col gap-2">
                        <Link href="/saved-tenders">
                          <motion.button
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                            className="w-full py-3 text-gray-700 font-medium border-2 border-transparent hover:border-green-200 rounded-full transition-all duration-300 hover:bg-green-50 flex items-center justify-center gap-2"
                            onClick={() => setMobileMenuOpen(false)}
                          >
                            <Bookmark className="w-4 h-4" /> Saved Tenders
                          </motion.button>
                        </Link>
                        <Link href="/tender-applieds">
                          <motion.button
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                            className="w-full py-3 text-gray-700 font-medium border-2 border-transparent hover:border-green-200 rounded-full transition-all duration-300 hover:bg-green-50 flex items-center justify-center gap-2"
                            onClick={() => setMobileMenuOpen(false)}
                          >
                            <CheckCircle className="w-4 h-4 text-green-600" /> My Applications
                          </motion.button>
                        </Link>
                        <Link href="/profile">
                          <motion.button
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                            className="w-full py-3 text-green-600 font-medium border-2 border-green-200 hover:border-green-300 rounded-full transition-all duration-300 hover:bg-green-50 flex items-center justify-center gap-2"
                            onClick={() => setMobileMenuOpen(false)}
                          >
                            <User className="w-4 h-4" /> View Profile
                          </motion.button>
                        </Link>
                        <motion.button
                          whileHover={{ scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                          className="w-full py-3 text-red-500 font-medium border-2 border-red-100 hover:border-red-200 rounded-full transition-all duration-300 hover:bg-red-50 flex items-center justify-center gap-2"
                          onClick={handleLogout}
                        >
                          <LogOut className="w-4 h-4" /> Logout
                        </motion.button>
                      </div>
                    ) : (
                      <>
                        <Link href="/login" className="flex-1">
                          <motion.button
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                            className="w-full py-3 text-green-600 font-medium border-2 border-green-200 hover:border-green-300 rounded-full transition-all duration-300 hover:bg-green-50"
                            onClick={() => setMobileMenuOpen(false)}
                          >
                            Login
                          </motion.button>
                        </Link>
                        <Link href="/register" className="flex-1">
                          <motion.button
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                            className="w-full py-3 bg-gradient-to-r from-green-600 to-green-700 text-white rounded-full font-medium shadow-md hover:shadow-lg transition-all duration-300"
                            onClick={() => setMobileMenuOpen(false)}
                          >
                            Register
                          </motion.button>
                        </Link>
                      </>
                    )}
                  </div>
                </nav>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </motion.header>
  );
}
