import React, { useState, useEffect, useRef, useCallback } from "react";
import { Link, useNavigate, useLocation } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import { useSocket } from "../contexts/SocketContext";
import { rentalAPI, messageAPI } from "../services/api";
import Avatar from "./Avatar";

const Navbar: React.FC = () => {
  const { user, logout, openAuthModal } = useAuth();
  const { onNewMessage, onMessageRead } = useSocket();
  const navigate = useNavigate();
  const location = useLocation();
  const [searchTerm, setSearchTerm] = useState("");
  const [pendingRequestsCount, setPendingRequestsCount] = useState(0);
  const [unreadMessagesCount, setUnreadMessagesCount] = useState(0);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const mobileMenuRef = useRef<HTMLDivElement>(null);
  const mobileToggleRef = useRef<HTMLButtonElement>(null);

  const closeDropdown = useCallback(() => {
    setIsDropdownOpen(false);
  }, []);

  const closeMobileMenu = useCallback(() => {
    setIsMobileMenuOpen(false);
  }, []);

  // Close menus when route changes
  useEffect(() => {
    closeDropdown();
    closeMobileMenu();
  }, [location.pathname, closeDropdown, closeMobileMenu]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      // Desktop dropdown
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
      // Mobile menu
      if (
        isMobileMenuOpen &&
        mobileMenuRef.current &&
        mobileToggleRef.current &&
        !mobileMenuRef.current.contains(event.target as Node) &&
        !mobileToggleRef.current.contains(event.target as Node)
      ) {
        setIsMobileMenuOpen(false);
      }
    };

    document.addEventListener("click", handleClickOutside, true);

    return () => {
      document.removeEventListener("click", handleClickOutside, true);
    };
  }, [isMobileMenuOpen]);

  // Fetch pending rental requests count when user logs in
  useEffect(() => {
    const fetchPendingCount = async () => {
      if (user) {
        try {
          const response = await rentalAPI.getPendingRequestsCount();
          setPendingRequestsCount(response.data.count);
        } catch (error) {
          console.error("Failed to fetch pending requests count:", error);
        }
      } else {
        setPendingRequestsCount(0);
      }
    };

    fetchPendingCount();

    // Listen for rental status changes to refresh count
    const handleRentalStatusChange = () => {
      fetchPendingCount();
    };

    window.addEventListener("rentalStatusChanged", handleRentalStatusChange);

    return () => {
      window.removeEventListener(
        "rentalStatusChanged",
        handleRentalStatusChange
      );
    };
  }, [user]);

  // Fetch unread messages count when user logs in
  useEffect(() => {
    const fetchUnreadCount = async () => {
      if (user) {
        try {
          const response = await messageAPI.getUnreadCount();
          setUnreadMessagesCount(response.data.count);
        } catch (error) {
          console.error("Failed to fetch unread message count:", error);
        }
      } else {
        setUnreadMessagesCount(0);
      }
    };

    fetchUnreadCount();
  }, [user]);

  // Listen for real-time message updates via socket
  useEffect(() => {
    if (!user) return;

    // Listen for new messages
    const cleanupNewMessage = onNewMessage((message: any) => {
      if (message.receiverId === user.id) {
        setUnreadMessagesCount((prev) => prev + 1);
      }
    });

    // Listen for messages being read
    const cleanupMessageRead = onMessageRead(() => {
      setUnreadMessagesCount((prev) => Math.max(0, prev - 1));
    });

    return () => {
      cleanupNewMessage();
      cleanupMessageRead();
    };
  }, [user, onNewMessage, onMessageRead]);

  const handleLogout = () => {
    logout();
    navigate("/");
  };

  const handleSearch = (e?: React.FormEvent | React.MouseEvent) => {
    e?.preventDefault();
    const params = new URLSearchParams();

    if (searchTerm.trim()) {
      params.append("search", searchTerm.trim());
    }

    // Location is handled in ItemList
    navigate(`/items${params.toString() ? `?${params.toString()}` : ""}`);

    // Clear search after navigating
    setSearchTerm("");
  };

  return (
    <>
      <style>
        {`
          #navbarNav .mobile-menu {
            padding: 0;
          }
          #navbarNav .dropdown-item {
            padding: 0.25rem 1rem;
          }
          #navbarNav .dropdown-divider {
            margin: 0.5rem 0;
            border-top: 1px solid rgba(0,0,0,.15);
            opacity: 1;
          }
        `}
      </style>
      <nav className="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
        <div className="container-fluid" style={{ maxWidth: "1800px" }}>
          <Link className="navbar-brand fw-bold" to="/">
            Village Share
          </Link>

          {/* Search bar - always visible, centered */}
          <div className="navbar-search">
            <div className="input-group">
              <input
                type="text"
                className="form-control"
                placeholder="Search items..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    handleSearch(e);
                  }
                }}
              />
              <button
                className="btn btn-outline-secondary"
                type="button"
                onClick={handleSearch}
              >
                <i className="bi bi-search"></i>
              </button>
            </div>
          </div>

          {/* Mobile menu toggle */}
          <button
            ref={mobileToggleRef}
            className="navbar-toggler border-0 p-0 d-lg-none"
            type="button"
            aria-controls="navbarNav"
            aria-expanded={isMobileMenuOpen}
            aria-label="Toggle navigation"
            onClick={(e) => {
              e.stopPropagation();
              setIsMobileMenuOpen((prev) => !prev);
            }}
          >
            {user ? (
              <span
                style={{
                  display: "flex",
                  alignItems: "center",
                  position: "relative",
                }}
              >
                {(pendingRequestsCount > 0 || unreadMessagesCount > 0) && (
                  <span
                    className="mobile-notification-badge"
                    style={{
                      position: "absolute",
                      right: "-5px",
                      top: "-5px",
                      backgroundColor: "#dc3545",
                      color: "white",
                      borderRadius: "50%",
                      width: "1.2em",
                      height: "1.2em",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: "0.7em",
                      fontWeight: "bold",
                      border: "2px solid white",
                      zIndex: 1,
                    }}
                  >
                    {pendingRequestsCount + unreadMessagesCount}
                  </span>
                )}
                <Avatar user={user} size="sm" />
              </span>
            ) : (
              <i
                className="bi bi-list"
                style={{ fontSize: "1.5rem", color: "#333" }}
              ></i>
            )}
          </button>
          {/* Mobile menu dropdown */}
          <div
            ref={mobileMenuRef}
            id="navbarNav"
            className="d-lg-none"
            style={{
              display: isMobileMenuOpen ? "block" : "none",
              position: "absolute",
              top: "calc(100% - 8px)",
              right: "0.5rem",
              left: "auto",
              zIndex: 1000,
              minWidth: "10rem",
              padding: 0,
              backgroundColor: "#fff",
              border: "1px solid rgba(0,0,0,.15)",
              borderRadius: "0.375rem",
              boxShadow: "0 0.5rem 1rem rgba(0,0,0,.175)",
            }}
          >
            <div
              className="d-flex align-items-center justify-content-center w-100 py-3 mobile-menu"
            >
              <ul className="navbar-nav flex-column">
                {user ? (
                  <>
                    <li>
                      <Link className="dropdown-item" to="/profile" onClick={closeMobileMenu}>
                        <i className="bi bi-person me-2"></i>Profile
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/renting" onClick={closeMobileMenu}>
                        <i className="bi bi-calendar-check me-2"></i>Renting
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/owning" onClick={closeMobileMenu}>
                        <i className="bi bi-list-ul me-2"></i>Owning
                        {pendingRequestsCount > 0 && (
                          <span className="badge bg-danger rounded-pill ms-2">
                            {pendingRequestsCount}
                          </span>
                        )}
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/forum" onClick={closeMobileMenu}>
                        <i className="bi bi-chat-dots me-2"></i>Forum
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/earnings" onClick={closeMobileMenu}>
                        <i className="bi bi-cash-coin me-2"></i>Earnings
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/messages" onClick={closeMobileMenu}>
                        <i className="bi bi-envelope me-2"></i>Messages
                        {unreadMessagesCount > 0 && (
                          <span className="badge bg-danger rounded-pill ms-2">
                            {unreadMessagesCount}
                          </span>
                        )}
                      </Link>
                    </li>
                    <li>
                      <hr className="dropdown-divider" />
                    </li>
                    <li>
                      <button
                        className="dropdown-item"
                        onClick={() => {
                          closeMobileMenu();
                          handleLogout();
                        }}
                      >
                        <i className="bi bi-box-arrow-right me-2"></i>Logout
                      </button>
                    </li>
                  </>
                ) : (
                  <>
                    <li>
                      <Link className="dropdown-item" to="/forum" onClick={closeMobileMenu}>
                        <i className="bi bi-chat-dots me-2"></i>Forum
                      </Link>
                    </li>
                    <li>
                      <button
                        className="dropdown-item fw-bold"
                        style={{ color: "#000000" }}
                        onClick={() => {
                          closeMobileMenu();
                          openAuthModal("login");
                        }}
                      >
                        <i className="bi bi-box-arrow-in-right me-2"></i>Login or Sign Up
                      </button>
                    </li>
                  </>
                )}
              </ul>
            </div>
          </div>

          {/* Desktop navigation - outside mobile menu container */}
          <div className="d-none d-lg-flex align-items-center">
            {user ? (
              <div ref={dropdownRef} style={{ position: "relative" }}>
                <button
                  type="button"
                  className="nav-link btn btn-link p-0"
                  aria-expanded={isDropdownOpen}
                  onClick={(e) => {
                    e.stopPropagation();
                    setIsDropdownOpen((prev) => !prev);
                  }}
                  style={{ cursor: "pointer", border: "none", background: "none" }}
                >
                  <span
                    style={{
                      display: "flex",
                      alignItems: "center",
                      position: "relative",
                    }}
                  >
                    {(pendingRequestsCount > 0 || unreadMessagesCount > 0) && (
                      <span
                        style={{
                          position: "absolute",
                          right: "-5px",
                          top: "-5px",
                          backgroundColor: "#dc3545",
                          color: "white",
                          borderRadius: "50%",
                          width: "1.2em",
                          height: "1.2em",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          fontSize: "0.7em",
                          fontWeight: "bold",
                          border: "2px solid white",
                          zIndex: 1,
                        }}
                      >
                        {pendingRequestsCount + unreadMessagesCount}
                      </span>
                    )}
                    <Avatar user={user} size="sm" />
                  </span>
                </button>
                {isDropdownOpen && (
                  <ul
                    className="dropdown-menu show"
                    style={{
                      position: "absolute",
                      right: 0,
                      top: "100%",
                      zIndex: 1000,
                    }}
                  >
                    <li>
                      <Link className="dropdown-item" to="/profile" onClick={() => setIsDropdownOpen(false)}>
                        <i className="bi bi-person me-2"></i>Profile
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/renting" onClick={() => setIsDropdownOpen(false)}>
                        <i className="bi bi-calendar-check me-2"></i>
                        Renting
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/owning" onClick={() => setIsDropdownOpen(false)}>
                        <i className="bi bi-list-ul me-2"></i>Owning
                        {pendingRequestsCount > 0 && (
                          <span className="badge bg-danger rounded-pill ms-2">
                            {pendingRequestsCount}
                          </span>
                        )}
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/forum" onClick={() => setIsDropdownOpen(false)}>
                        <i className="bi bi-chat-dots me-2"></i>
                        Forum
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/earnings" onClick={() => setIsDropdownOpen(false)}>
                        <i className="bi bi-cash-coin me-2"></i>
                        Earnings
                      </Link>
                    </li>
                    <li>
                      <Link className="dropdown-item" to="/messages" onClick={() => setIsDropdownOpen(false)}>
                        <i className="bi bi-envelope me-2"></i>Messages
                        {unreadMessagesCount > 0 && (
                          <span className="badge bg-danger rounded-pill ms-2">
                            {unreadMessagesCount}
                          </span>
                        )}
                      </Link>
                    </li>
                    <li>
                      <hr className="dropdown-divider" />
                    </li>
                    <li>
                      <button
                        className="dropdown-item"
                        onClick={() => {
                          setIsDropdownOpen(false);
                          handleLogout();
                        }}
                      >
                        <i className="bi bi-box-arrow-right me-2"></i>
                        Logout
                      </button>
                    </li>
                  </ul>
                )}
              </div>
            ) : (
              <>
                <Link
                  className="btn btn-outline-primary btn-sm text-nowrap me-2"
                  to="/forum"
                >
                  Forum
                </Link>
                <button
                  className="btn btn-primary btn-sm text-nowrap"
                  onClick={() => openAuthModal("login")}
                >
                  Login or Sign Up
                </button>
              </>
            )}
          </div>
        </div>
      </nav>
    </>
  );
};

export default Navbar;
