import Link from "next/link";
import Image, { StaticImageData } from "next/image";
import React, { useEffect, useState } from "react";
import { useSession, signOut } from "next-auth/react";
import { useRouter } from "next/router";
import { Nav, NavDropdown, Navbar } from "react-bootstrap";
import { updateTheme } from "@/services/public";
import { customerLogoGet, carrierLogoGet, adminLogoGet, notificationCount, seenStatus, seenAllStatus,AllseenStatus } from "@/services/profile";
import { useUser } from "@/components/Context/UserContext";
import SubscriptionPlansModal from "@/components/ui/modal/SubscriptionPlansModal";
import { Session } from "next-auth";

interface UserMenuProps {
  userName: any;
  userAvtar: string | StaticImageData;
  toggleLightMode: () => void;
  toggleDarkMode: () => void;
}

interface AvatarProps {
  userLogo: string;
  userAvtar: string | StaticImageData;
  status?: number;
}

const Avatar = ({ userLogo, userAvtar, status }: AvatarProps) => {
  return (
    <div className="user-img c-pointer position-relative" data-toggle="dropdown">
      <img
        src={status === 0 || (status === undefined || null) ? 
          (typeof userAvtar === "object" ? userAvtar.src : userAvtar) : 
          userLogo}
        className="rounded-circle"
        height="36"
        width="36.69"
        alt="User Avatar"
      />
    </div>
  )
};

const UserDropdown = ({
  userName,
  updatedUserName,
  uname,
  handleLogout,
  handleThemeToggle,
  sunButton,
  moonButton,
}: {
  userName: any;
  updatedUserName: string;
  uname: string;
  handleLogout: () => void;
  handleThemeToggle: (theme: string) => void;
  sunButton: string;
  moonButton: string;
}) => (
  <NavDropdown
    id="nav-dropdown"
    title={
      updatedUserName?.length > 1
        ? `${updatedUserName?.slice(0, 10)}...`
        : uname
    }
    menuVariant="light"
    className="user-img c-pointer position-relative"
  >
    <Nav.Link as={Link} className="nav-link-dropdown" href="/">
      Home
    </Nav.Link>
    <Nav.Link as={Link} className="nav-link-dropdown" href="/dashboard">
      Dashboard
    </Nav.Link>
    <Nav.Link as={Link} className="nav-link-dropdown" href="/my-profile">
      My Profile
    </Nav.Link>
    <NavDropdown.Divider />
    <NavDropdown.Item onClick={handleLogout}>Logout</NavDropdown.Item>
    <div>
      <div className="header-left user-menu-new">
        <NavDropdown.Divider />
        <div className="theme theme-new-css">
          <div
            className={`dark ${moonButton}`}
            onClick={() => handleThemeToggle("dark")}
          >
            <i className="bi bi-moon"></i>
          </div>
          <div
            className={`light ${sunButton}`}
            onClick={() => handleThemeToggle("light")}
          >
            <i className="bi bi-sun-fill"></i>
          </div>
        </div>
      </div>
    </div>
  </NavDropdown>
);

const UserSubscrptionDropdown = ({
  userDetails,
  handleLoggedinUser,
}: {
  userDetails: any;
  handleLoggedinUser: () => void;
}) => (
  <NavDropdown
    disabled={userDetails?.is_premium ? true : false}
    id="nav-dropdown"
    title={`Subscription: ${userDetails?.is_premium ? "Premium" : "Free"}`}
    menuVariant="light"
    className="subscription_status c-pointer position-relative"
  >
    {(!userDetails?.is_premium) ? (
      <NavDropdown.Item onClick={handleLoggedinUser}>Upgrade to Draydex Premium</NavDropdown.Item>
    ) : (
      <NavDropdown.Item>Manage Billing Account</NavDropdown.Item>
    )}
  </NavDropdown>

);

const UserMenu: React.FC<UserMenuProps> = ({ userName, userAvtar, notify, setNotify }) => {
  const router = useRouter();
  const { data } = useSession();
  const { updateUserName, updatelastName, UpdateUserLogo, userLogo, status } =
    useUser();

  const [sunButton, setSunButton] = useState("");
  const [moonButton, setMoonButton] = useState("active");
  const [uname, setUname] = useState<any>();
  const [updatedUserName] = useState("");
  const carrierId = data?.user?.carrier_id;
  const customerId = data?.user?.customer_id;
  const customerUser = data?.user?.group_type === "customers";
  const carrierUser = data?.user?.group_type === "carriers";
  const [modalStatus, SetModalStatus] = useState(false);

  const handleLogout = async () => {
    updateUserName("");
    updatelastName("");
    UpdateUserLogo("");
    signOut({ redirect: false }).then(() => {
      router.push("/login");
    });
  };
  const truncateText = (text: string, length: number) => {
    return text?.length > length ? `${text.slice(0, length)}...` : text;
  };

  useEffect(() => {
    setUname(truncateText(userName, 10));
  }, [userName]);

  let logoGetFunction;

  logoGetFunction = customerUserModMultiple(customerUser, logoGetFunction, carrierUser);
  const userId = userIdModScope(customerUser, customerId, carrierId);

  const updateLogo = async () => {
    const response = await logoGetFunction(data?.user?.image, userId);
    UpdateUserLogoScopeMod(response, UpdateUserLogo);
  };

  useEffect(() => {
    updateLogo();
  }, [customerId, carrierId, customerUser, data?.user?.image, UpdateUserLogo]);

  useEffect(() => {
    const theme = themeFunctionSunButton(data, setSunButton, setMoonButton);
    document.body.classList.toggle("darkMode", theme === "dark");
  }, [data]);

  const handleThemeToggle = async (theme: string) => {
    handleThemeToggleMod(setSunButton, theme, setMoonButton);
    document.body.classList.toggle("darkMode", theme === "dark");
    await updateTheme(data?.user?.image, { theme });
  };

  const handleLoggedinUser = () => {
    SetModalStatus(true);
  }


  const [showModal, setShowModal] = useState(false);
  const [notificationData, setNotificationData] = useState();
  const [Undo, setUndo] = useState(false)
  const toggleModal = () => {
    setShowModal(!showModal);
  };


  const fetchNotifications = async () => {
    let res = await notificationCount(data?.user?.image);


    fetchNotificationsModCount(setNotify);

    setNotificationData(res);
  };

  useEffect(() => {
    fetchNotifications()
  }, [notify, data])


  const seenNotify = async (id) => {
    setUndo(true)
    let payload = {
      id: id
    }
    let res = await seenStatus(data?.user?.image, payload);
    if (res?.status === "success") {
      setUndo(false)
    }


    fetchNotifications()
  }
  const seenAllNotify = async (id) => {
    setUndo(true)
    let payload = {
      quote_id: id
    }
    let res = await seenAllStatus(data?.user?.image, payload);
    if (res?.status === "success") {
      setUndo(false)
    }


    fetchNotifications()
  }

  const renderMessage = (message: string, id: any, rateId: any,is_seen:any) => {


    if (!message) return null;

    // Regex to match "quote" followed by a number
    const quoteRegex = /quote (\d+)/g;

    const parts = [];
    let lastIndex = 0;
    let match;
    
    while ((match = quoteRegex.exec(message)) !== null) {
      // Check if match exists and has a valid numeric value at match[1]
      whileMod({ match, lastIndex, parts, message, seenAllNotify, id, router, rateId,is_seen });

      // Update the last index to continue processing
      lastIndex = quoteRegex.lastIndex;
    }

    // Add any remaining text after the last match
    lastIndexMod(lastIndex, message, parts);

    return parts;
  };
  const [filter, setFilter] = useState<'unread' | 'all'>('unread'); // Default to 'unread'

  // Function to toggle the filter between 'unread' and 'all'
  const handleFilterChange = (filterType: 'unread' | 'all') => {
    setFilter(filterType);
  };

  const filteredNotifications = unreadFilterMod(notificationData, filter);
  const AllseenStatusUpdate = AllseenStatusUpdateMod(data, fetchNotifications)
  return (
    <>
      <Navbar.Toggle aria-controls="navbar-dark" />
      {
        (data?.user?.group_type !== "super_admin") && (
          (data?.user?.parent_id === null) && (
            <UserSubscrptionDropdown
              userDetails={data?.user}
              handleLoggedinUser={handleLoggedinUser}
            />
          )
        )
      }
      <div className="container mt-4">

        <div className="position-relative">

          <div className="position-relative">
            <button
              className="btn btn-light"
              style={{ border: "none", background: "none", marginBottom: "17px" }}
              onClick={toggleModal}
            >
              <i className="bi bi-bell" style={{ fontSize: "24px", color: "white", marginBottom: "31px" }}></i>
              <span
                className="badge bg-danger rounded-circle"
                style={{
                  position: "absolute",
                  // top: "-5px",
                  right: "-5px",
                  width: "20px",
                  height: "20px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: "12px",
                }}
              >
                {notificationData?.count}
              </span>
            </button>
          </div>

          {/* Notification Modal */}
          {showModal && (
            <div
              className="notification-panel"

            >
              <div className="card-header d-flex justify-content-between align-items-center">
                <div className="table-header-not">  <h3 className="mb-0 ">Notifications</h3></div>

                <button
                  className="btn-close"
                  aria-label="Close"
                  onClick={() => {
                    toggleModal();
                    setFilter("unread");
                  }}
                ></button>
              </div>
              <div style={{ display: "flex", gap: "10px" }} className="noti-btns">
                <div>
                  <p
                    onClick={() => handleFilterChange('unread')}
                    style={{ cursor: 'pointer', fontWeight: filter === 'unread' ? 'bold' : 'normal' }}
                  >
                    Unread Notifications
                  </p>
                  <p
                    onClick={() => handleFilterChange('all')}
                    style={{ cursor: 'pointer', fontWeight: filter === 'all' ? 'bold' : 'normal' }}
                  >
                    All Notifications
                  </p>
                </div>
                <div>
                  <button onClick={() => AllseenStatusUpdate()} type="button" className="btn btn-success mark-read-btn">Mark All Read</button>
                </div>
              </div>
              <div className="notification-list">
                <ul className="list-group list-group-flush">


                  {/* Conditionally render notifications based on the filter */}
                  {filteredNotificationsModData(filteredNotifications, renderMessage, Undo, seenNotify)}
                </ul>
              </div>

            </div>
          )}
        </div>
      </div>
      <Avatar userLogo={userLogo} userAvtar={userAvtar} status={status} />
      <UserDropdown
        userName={userName}
        updatedUserName={updatedUserName}
        uname={uname}
        handleLogout={handleLogout}
        handleThemeToggle={handleThemeToggle}
        sunButton={sunButton}
        moonButton={moonButton}
      />

      <SubscriptionPlansModal
        modalStatus={modalStatus}
        SetModalStatus={SetModalStatus}
        userDetails={data?.user}
      />
    </>
  );
};
export default UserMenu;
function unreadFilterMod(notificationData: undefined, filter: string) {
  return notificationData?.data?.filter(item => filter === 'unread' ? item?.is_seen === 0 : item?.is_seen === 0 || 1
  );
}

function AllseenStatusUpdateMod(data: Session | null, fetchNotifications: () => Promise<void>){
  return async () => {
    let res = await AllseenStatus(data?.user?.image);
    if (res?.status === "success") {
      fetchNotifications();
    }
  };
}

function filteredNotificationsModData(filteredNotifications: any, renderMessage: (message: string, id: any, rateId: any) => any[] | null, Undo: boolean, seenNotify: (id: any) => Promise<void>): React.ReactNode {
  return filteredNotifications?.length === 0 ? (
    <div className="no-new-notifications">No data available</div>
  ) : (
    filteredNotifications?.map((item: any) => (
      <li style={{ backgroundColor: item?.is_seen === 1 ? "rgba(182, 183, 184, 0.4)" : "rgba(48, 183, 247, 0.4)", borderLeftColor: item?.is_seen === 1 ? "rgb(182, 183, 184)" : "rgb(48, 183, 247)" }}
        className="list-group-item d-flex align-items-start" key={item?.id}>
        <div className="notification-container">
          <p className="mb-1 message-notification">
            {renderMessage(item?.message, item?.id, item?.rate_id,item?.is_seen)}
          </p>
          <button
            disabled={Undo}
            onClick={() => seenNotify(item?.id)}
            className={`mark-btn ${item?.is_seen === 1 ? "unread" : "read"} ${item?.is_seen !== 1 && "mark-btn1"}`}
          >
          </button>
        </div>
        <div style={{ display: "flex", gap: "150px" }}>
          <div><small className="text-muted created_at">{item?.created_at}</small></div>
        </div>
      </li>
    ))
  );
}

function fetchNotificationsModCount(setNotify: any) {
  if (typeof setNotify === "function") {
    setNotify(false);
  } else {
    console.warn("setNotify is not defined or is not a function");
  }
}

function UpdateUserLogoScopeMod(response: any, UpdateUserLogo: any) {
  if (response?.status === "success") {
    UpdateUserLogo(response?.data);
  }
}

function userIdModScope(customerUser: boolean, customerId: any, carrierId: any) {
  return customerUser ? customerId : carrierId;
}

function handleThemeToggleMod(setSunButton: React.Dispatch<React.SetStateAction<string>>, theme: string, setMoonButton: React.Dispatch<React.SetStateAction<string>>) {
  setSunButton(theme === "light" ? "active" : "");
  setMoonButton(theme === "dark" ? "active" : "");
}

function lastIndexMod(lastIndex: number, message: string, parts: any[]) {
  if (lastIndex < message.length) {
    parts.push(<span key={`end-${lastIndex}`}>{message.slice(lastIndex)}</span>);
  }
}

function whileMod({ match, lastIndex, parts, message, seenAllNotify, id, router, rateId,is_seen }: { match: RegExpExecArray; lastIndex: number; parts: any[]; message: string; seenAllNotify: (id: any) => Promise<void>; id: any; router; rateId: any;is_seen:any }) {
  if (match && match[1]) {
    const quoteId = match[1]; // Get the quoteId from match[1]


    // Add the text before the match
    if (match.index > lastIndex) {
      parts.push(
        <span key={`text-${lastIndex}`}>{message.slice(lastIndex, match.index)}</span>
      );
    }

    // Add the word "quote" (not clickable)
    parts.push(<span key={`quote-${match.index}`}>quote </span>);

    // Add the clickable numeric ID
    parts.push(
      <strong
        key={`link-${match.index}`}
        onClick={() => {
          if (quoteId) {
            // Make sure quoteId is valid before navigating
            if(is_seen ==0){
              seenAllNotify(quoteId);
              setTimeout(function(){
                window.location.href = `/rate-quotes/${quoteId}?rateId=${rateId}`;
            },2000); 
            }else{
              setTimeout(function(){
                window.location.href = `/rate-quotes/${quoteId}?rateId=${rateId}`;
            },2000);
            }   

          } else {
            console.error('Invalid quoteId:', quoteId);
          }
        }}
        style={{ cursor: 'pointer', color: 'blue', textDecoration: 'underline' }}
      >
        {quoteId} {/* Numeric part only */}
      </strong>
    );
  } else {
    // Log an error if match[1] is not found
    console.error('No valid match[1] found for match:', match);
  }
}

function customerUserModMultiple(customerUser: boolean, logoGetFunction: any, carrierUser: boolean) {
  if (customerUser) {
    logoGetFunction = customerLogoGet;
  } else if (carrierUser) {
    logoGetFunction = carrierLogoGet;
  } else {
    logoGetFunction = adminLogoGet;
  }
  return logoGetFunction;
}

function themeFunctionSunButton(data: Session | null, setSunButton: React.Dispatch<React.SetStateAction<string>>, setMoonButton: React.Dispatch<React.SetStateAction<string>>) {
  const theme = data?.user?.theme;
  setSunButton(theme === "light" ? "active" : "");
  setMoonButton(theme === "dark" ? "active" : "");
  return theme;
}

