"use client";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSelector, useDispatch } from "react-redux";
import {
  Sun,
  Moon,
  ChevronDown,
  Menu,
  X,
  ArrowRight,
  User,
  LogOut,
  Phone,
} from "lucide-react";
import { useTheme } from "../contexts/ThemeContext";
import { selectCurrentUser, selectIsAuthenticated, logout } from "@/redux/slices/authSlice";
import { useLogoutMutation } from "@/redux/apis/authApi";

export default function Navbar() {
  const router = useRouter();
  const dispatch = useDispatch();
  const [logoutMutation] = useLogoutMutation();
  const [mounted, setMounted] = useState(false);
  const user = useSelector(selectCurrentUser);
  const isAuthenticated = useSelector(selectIsAuthenticated);
  const [isOpen, setIsOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [profileDropdown, setProfileDropdown] = useState(false);
  const [mobileDropdownOpen, setMobileDropdownOpen] = useState<string | null>(null);
  const { theme, toggleTheme } = useTheme();

  // Prevent hydration mismatch by only showing auth-dependent UI after mount
  useEffect(() => {
    setMounted(true);
  }, []);

  const handleLogout = async () => {
    try {
      // Try to call logout API, but don't fail if it errors
      const result = await logoutMutation();
      if ('error' in result) {
        console.warn("Logout API call failed, but continuing with local logout:", result.error);
      }
    } catch (error: any) {
      // Log detailed error information for debugging
      console.warn("Logout error (non-blocking):", error);
      if (error?.data) {
        console.warn("Logout error data:", error.data);
      }
      if (error?.status) {
        console.warn("Logout error status:", error.status);
      }
    } finally {
      // Always logout locally regardless of API response
      // This ensures the user is logged out even if the API call fails
      dispatch(logout());
      setProfileDropdown(false);
      router.push("/");
    }
  };

  // Close dropdowns when clicking outside
  useEffect(() => {
    if (!profileDropdown) return;

    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest(".profile-dropdown-container")) {
        setProfileDropdown(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [profileDropdown]);

  const navLinks = [
    { name: "Home", href: "#home" },
    {
      name: "Products",
      href: "#products",
      dropdown: [
        { name: "B2B", href: "/b2b" },
        { name: "B2C", href: "/b2c" },
        { name: "CRM", href: "/crm" },
        { name: "DailyPost App", href: "/dailypost-app" },
        { name: "Finance", href: "/finance" },
        { name: "Tender", href: "/tender" },
        { name: "EV Charging", href: "/ev-charging" }
      ]
    },
    {
      name: "Services",
      href: "#services",
      dropdown: [
        "Solar Projects",
        "Wind Projects",
        "EV Charging",
        "Solar Street Lights",
        "Branding & Marketing"
      ]
    },
    { name: "Partners", href: "#partners" },
    { name: "Tender Winner", href: "/tender-winner" },
    { name: "Blogs", href: "/blogs" },
    { name: "About", href: "#about" },
    { name: "Contact", href: "#contact" },
  ];

  return (
    <motion.nav
      initial={{ y: -100 }}
      animate={{ y: 0 }}
      transition={{ duration: 0.5 }}
      className="fixed top-0 left-0 right-0 z-50 bg-theme-nav backdrop-blur-lg border-b border-primary-500/10"
    >
      <div className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-12">
        <div className="flex items-center justify-between h-20">
          {/* Logo */}
          <Link href="/">
            <motion.div
              className="flex items-center gap-3 cursor-pointer"
              whileHover={{ scale: 1.02 }}
            >
              <Image
                src="/Maharashtra Solar.png"
                alt="Maharashtra Solar Business Syndicate"
                width={200}
                height={60}
                className="h-14 w-auto object-contain"
                priority
              />
            </motion.div>
          </Link>

          {/* Desktop Navigation */}
          <div className="hidden lg:flex items-center gap-4">
            {navLinks.map((link) => (
              <div
                key={link.name}
                className="relative"
                onMouseEnter={() => link.dropdown && setActiveDropdown(link.name)}
                onMouseLeave={() => setActiveDropdown(null)}
              >
                <a
                  href={link.href}
                  className="px-4 py-2 text-theme-secondary hover:text-primary-500 transition-colors flex items-center gap-1 text-sm font-medium"
                >
                  {link.name}
                  {link.dropdown && <ChevronDown className="w-4 h-4" />}
                </a>
                {link.dropdown && activeDropdown === link.name && (
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="absolute top-full left-0 mt-1 w-56 bg-white dark:bg-[#111827] backdrop-blur-xl border border-primary-500/20 dark:border-primary-500/30 rounded-xl py-2 shadow-xl"
                    style={{
                      zIndex: 2000,
                      backgroundColor: theme === "dark" ? "rgba(17, 24, 39, 1)" : "rgba(255, 255, 255, 1)",
                    }}
                  >
                    {link.dropdown.map((item) => (
                      <Link
                        key={typeof item === 'string' ? item : item.name}
                        href={typeof item === 'string' ? '#' : item.href}
                        className="block px-4 py-2 text-sm text-theme-secondary hover:text-primary-500 hover:bg-primary-500/10 dark:hover:bg-primary-500/20 transition-colors"
                      >
                        {typeof item === 'string' ? item : item.name}
                      </Link>
                    ))}
                  </motion.div>
                )}
              </div>
            ))}
          </div>

          {/* CTA Buttons & Theme Toggle */}
          <div className="hidden lg:flex items-center gap-3">
            <motion.button
              onClick={toggleTheme}
              className="theme-toggle"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              aria-label="Toggle theme"
            >
              {theme === "dark" ? (
                <Sun className="w-5 h-5 text-solar-400" />
              ) : (
                <Moon className="w-5 h-5 text-primary-600" />
              )}
            </motion.button>
            {mounted && isAuthenticated && user ? (
              <div className="relative profile-dropdown-container">
                <motion.button
                  onClick={() => setProfileDropdown(!profileDropdown)}
                  className="flex items-center gap-2 px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 hover:border-primary-500 transition-colors"
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <div className="w-8 h-8 rounded-full bg-primary-500 flex items-center justify-center text-white font-semibold">
                    {user.name.charAt(0).toUpperCase()}
                  </div>
                  <span className="text-sm font-medium text-theme-primary hidden md:block">
                    {user.name.split(" ")[0]}
                  </span>
                  <ChevronDown className="w-4 h-4 text-theme-muted" />
                </motion.button>
                {profileDropdown && (
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="absolute top-full right-0 mt-2 w-56 bg-white dark:bg-[#111827] backdrop-blur-xl border border-primary-500/20 dark:border-primary-500/30 rounded-xl py-2 shadow-xl z-50"
                    style={{
                      backgroundColor: theme === "dark" ? "rgba(17, 24, 39, 1)" : "rgba(255, 255, 255, 1)",
                    }}
                  >
                    <Link
                      href="/profile"
                      className="flex items-center gap-3 px-4 py-2 text-sm text-theme-secondary hover:text-primary-500 hover:bg-primary-500/10 dark:hover:bg-primary-500/20 transition-colors"
                      onClick={() => setProfileDropdown(false)}
                    >
                      <User className="w-4 h-4" />
                      View Profile
                    </Link>
                    <button
                      onClick={handleLogout}
                      className="w-full flex items-center gap-3 px-4 py-2 text-sm text-red-500 hover:text-red-400 hover:bg-red-500/10 dark:hover:bg-red-500/20 transition-colors"
                    >
                      <LogOut className="w-4 h-4" />
                      Logout
                    </button>
                  </motion.div>
                )}
              </div>
            ) : mounted ? (
              <>
                <Link href="/login" className="btn-secondary text-sm">
                  Login
                </Link>
                <Link href="/register" className="btn-primary text-sm">
                  Register
                  <ArrowRight className="w-4 h-4" />
                </Link>
              </>
            ) : (
              // Placeholder during SSR to prevent hydration mismatch
              <>
                <div className="btn-secondary text-sm opacity-0 pointer-events-none">
                  Login
                </div>
                <div className="btn-primary text-sm opacity-0 pointer-events-none">
                  Register
                </div>
              </>
            )}


          </div>

          {/* Mobile Menu Button & Theme Toggle */}
          <div className="lg:hidden flex items-center gap-2">
            <motion.button
              onClick={toggleTheme}
              className="theme-toggle"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              aria-label="Toggle theme"
            >
              {theme === "dark" ? (
                <Sun className="w-5 h-5 text-solar-400" />
              ) : (
                <Moon className="w-5 h-5 text-primary-600" />
              )}
            </motion.button>
            <button
              className="p-2 text-theme-secondary"
              onClick={() => setIsOpen(!isOpen)}
            >
              {isOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
            </button>
          </div>
        </div>

        {/* Mobile Menu */}
        <AnimatePresence>
          {isOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              className="lg:hidden py-4 border-t border-primary-500/10"
            >
              {navLinks.map((link) => (
                <div key={link.name}>
                  {link.dropdown ? (
                    <>
                      <button
                        onClick={() => {
                          setMobileDropdownOpen(
                            mobileDropdownOpen === link.name ? null : link.name
                          );
                        }}
                        className="w-full flex items-center justify-between px-4 py-3 text-theme-secondary hover:text-primary-500 transition-colors"
                      >
                        <span>{link.name}</span>
                        <ChevronDown
                          className={`w-4 h-4 transition-transform ${mobileDropdownOpen === link.name ? "rotate-180" : ""
                            }`}
                        />
                      </button>
                      <AnimatePresence>
                        {mobileDropdownOpen === link.name && (
                          <motion.div
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: "auto" }}
                            exit={{ opacity: 0, height: 0 }}
                            className="overflow-hidden"
                          >
                            <div className="pl-6 bg-theme-input/50">
                              {link.dropdown.map((item) => (
                                <Link
                                  key={typeof item === 'string' ? item : item.name}
                                  href={typeof item === 'string' ? '#' : item.href}
                                  className="block px-4 py-2 text-sm text-theme-secondary hover:text-primary-500 transition-colors"
                                  onClick={() => {
                                    setIsOpen(false);
                                    setMobileDropdownOpen(null);
                                  }}
                                >
                                  {typeof item === 'string' ? item : item.name}
                                </Link>
                              ))}
                            </div>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </>
                  ) : (
                    <a
                      href={link.href}
                      className="block px-4 py-3 text-theme-secondary hover:text-primary-500 transition-colors"
                      onClick={() => setIsOpen(false)}
                    >
                      {link.name}
                    </a>
                  )}
                </div>
              ))}
              <div className="flex gap-3 mt-4 px-4">
                {mounted && isAuthenticated && user ? (
                  <>
                    <Link href="/profile" className="btn-secondary text-sm flex-1 justify-center" onClick={() => setIsOpen(false)}>
                      <User className="w-4 h-4 mr-2" />
                      Profile
                    </Link>
                    <button
                      onClick={() => {
                        handleLogout();
                        setIsOpen(false);
                      }}
                      className="btn-primary text-sm flex-1 justify-center bg-red-500 hover:bg-red-600"
                    >
                      <LogOut className="w-4 h-4 mr-2" />
                      Logout
                    </button>
                  </>
                ) : mounted ? (
                  <>
                    <Link href="/login" className="btn-secondary text-sm flex-1 justify-center" onClick={() => setIsOpen(false)}>
                      Login
                    </Link>
                    <Link href="/register" className="btn-primary text-sm flex-1 justify-center" onClick={() => setIsOpen(false)}>
                      Get Started
                    </Link>
                  </>
                ) : (
                  // Placeholder during SSR to prevent hydration mismatch
                  <>
                    <div className="btn-secondary text-sm flex-1 justify-center opacity-0 pointer-events-none">
                      Login
                    </div>
                    <div className="btn-primary text-sm flex-1 justify-center opacity-0 pointer-events-none">
                      Get Started
                    </div>
                  </>
                )}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </motion.nav>
  );
}

