/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
import { Link, usePage } from "@inertiajs/react";
import { useRef, useEffect, useState } from "react";
import { FiChevronRight } from "react-icons/fi";
import {
  MdOutlineDashboardCustomize,
  MdEventRepeat,
} from "react-icons/md";
import { BiSolidGroup, BiShield, BiUser, BiDonateHeart } from "react-icons/bi";
import { BsCalendar2EventFill } from "react-icons/bs";
import { IoWallet, IoBagCheck } from "react-icons/io5";
import { RiBubbleChartFill } from "react-icons/ri";
import { FaLayerGroup, FaUserPlus } from "react-icons/fa";

import styles from "./mobile-sidebar.module.scss";

// -------------------------------
// SidebarLink Component
// -------------------------------
interface SidebarLinkProps {
  path: string;
  label: string;
  description?: string;
  icon: React.ReactNode;
  closeBar: () => void;
}

const SidebarLink = ({ path, label, description, icon, closeBar }: SidebarLinkProps) => {
  const basePath = "/dashboard";
  const { url } = usePage();
  const currentPath = url.startsWith("/") ? url : `/${url}`;
  const fullPath = `${basePath}/${path}`;
  const isActive = currentPath.startsWith(fullPath);

  return (
    <Link
      href={fullPath}
      onClick={closeBar}
      className={isActive ? styles.active : styles.link}
    >
      <div className={isActive ? styles["icon-active"] : styles.icon}>{icon}</div>
      <div className={styles["link-text"]}>
        <span className={styles["link-label"]}>{label}</span>
        {description && <small className={styles["link-desc"]}>{description}</small>}
      </div>
      {isActive && <FiChevronRight className={styles["active-arrow"]} />}
    </Link>
  );
};

// -------------------------------
// MobileSidebar Component
// -------------------------------
interface MobileSidebarProps {
  show: boolean;
  closeBar: () => void;
}

const MobileSidebar = ({ show, closeBar }: MobileSidebarProps) => {
  const { auth } = usePage().props as any;
  const sidebarRef = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(show);

  // Show sidebar when prop changes
  useEffect(() => {
    if (show) {
      const timer = requestAnimationFrame(() => setVisible(true));
      return () => cancelAnimationFrame(timer);
    }
  }, [show]);

  // Close sidebar with animation
  const handleClose = () => {
    setVisible(false);
    setTimeout(() => closeBar(), 300); // match CSS transition
  };

  // Close sidebar when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (sidebarRef.current && !sidebarRef.current.contains(event.target as Node)) {
        handleClose();
      }
    };
    if (visible) document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [visible]);

  if (!show && !visible) return null;

  // -------------------------------
  // Link sections
  // -------------------------------
  const sections = [
    {
      title: "OVERVIEW",
      links: [
        {
          path: "home",
          label: "Dashboard",
          description: "Church overview",
          icon: <MdOutlineDashboardCustomize size="1.2rem" />,
        },
      ],
    },
    {
      title: "PEOPLE",
      links: [
        { path: "members", label: "Members", description: "Church members", icon: <BiSolidGroup size="1.2rem" /> },
        { path: "first-timers", label: "First Timers", description: "New visitors", icon: <FaUserPlus size="1.2rem" /> },
        { path: "home-cell", label: "Home Cells", description: "Home Cells", icon: <FaLayerGroup size="1.2rem" /> },
      ],
    },
    {
      title: "OPERATIONS",
      links: [
        { path: "attendance", label: "Attendance", description: "Track attendance", icon: <BsCalendar2EventFill size="1.2rem" /> },
        { path: "businesses", label: "Businesses", description: "Business profiles", icon: <RiBubbleChartFill size="1.2rem" /> },
        { path: "appointments", label: "Appointments", description: "Meetings & bookings", icon: <BsCalendar2EventFill size="1.2rem" /> },
        { path: "programs", label: "Programs", description: "Special programs", icon: <MdEventRepeat size="1.2rem" /> },
      ],
    },
    {
      title: "ADMIN",
      links: [
        { path: "donation-funds", label: "Pledges", description: "Pledges and remittances", icon: <BiDonateHeart size="1.2rem" /> },

        { path: "branch-remittances", label: "Remittances", description: "Branch Remittances", icon: <RiBubbleChartFill size="1.2rem" /> },

        { path: "finance", label: "Finance", description: "Church accounting", icon: <IoWallet size="1.2rem" /> },
        
        // { path: "equipments", label: "Equipments", description: "Assets management", icon: <FaTools size="1.2rem" /> },
        { path: "permissions", label: "Roles & Permissions", description: "Access control", icon: <IoBagCheck size="1.2rem" /> },
      ],
    },
    {
      title: "PROFILE & SECURITY",
      links: [
        { path: "my-profile", label: "Profile", description: "Account profile", icon: <BiUser size="1.2rem" /> },
        { path: "security", label: "Security", description: "Account security", icon: <BiShield size="1.2rem" /> },
      ],
    },
  ];

  return (
    <>
      {/* Overlay */}
      <div
        className={`${styles.overlay} ${show ? styles.fadeIn : styles.fadeOut}`}
        onClick={handleClose}
      />

      {/* Sidebar */}
      <aside
        ref={sidebarRef}
        className={`${styles.mobileSidebar} ${visible ? styles.slideIn : styles.slideOut}`}
      >
        {/* Admin Header */}
        <div className={styles.mobileSidebar__admin}>
          <h3>{auth?.user?.firstName || "Admin"}</h3>
          <small>{auth?.user?.email}</small>
        </div>

        {/* Sidebar Links */}
        <div className={styles.mobileSidebar__links}>
          {sections.map((section) => (
            <div key={section.title} className={styles.mobileSidebar__section}>
              <span className={styles.mobileSidebar__section__title}>{section.title}</span>
              {section.links.map((link) => (
                <SidebarLink
                  key={link.path}
                  path={link.path}
                  label={link.label}
                  description={link.description}
                  icon={link.icon}
                  closeBar={handleClose}
                />
              ))}
            </div>
          ))}
        </div>

        {/* Footer */}
        <div className={styles.mobileSidebar__footer}>
          <div className={styles.mobileSidebar__footer__avatar}>AU</div>
          <div className={styles.mobileSidebar__footer__text}>
            <h4>{auth?.user?.firstName || "Admin"} {auth?.user?.lastName || ""}</h4>
            <small>Church Lead • Censers Church</small>
          </div>
        </div>
      </aside>
    </>
  );
};

export default MobileSidebar;
