// --- Sidebar.tsx (MODIFIED: added approval check) ---

"use client";

import {
  Box,
  Divider,
  Drawer,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Toolbar,
  Typography,
  useMediaQuery,
} from "@mui/material";
import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";

import CloseIcon from "@mui/icons-material/Close";
import Image from "next/image";
import Link from "next/link";
import MenuIcon from "@mui/icons-material/Menu";
import { NAVIGATION } from "./navigation";
import { useTheme } from "@mui/material/styles";

const drawerWidth = 260;

export default function Sidebar() {
  const [role, setRole] = useState<string | null>(null);
  const [approved, setApproved] = useState<boolean>(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  const pathname = usePathname();
  const router = useRouter();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));

  useEffect(() => {
    const storedRole = localStorage.getItem("role") || "user";
    const isApproved = localStorage.getItem("approved") === "true";
    setRole(storedRole);
    setApproved(isApproved);
  }, []);

  const handleLogout = async () => {
    try {
      await fetch(
        "https://milimanibackend.sigraelfasolutions.com/api/auth/logout",
        {
          method: "POST",
          credentials: "include",
        }
      );
      localStorage.clear();
      router.push("/");
    } catch (err) {
      console.error("Logout failed:", err);
    }
  };

  const toggleDrawer = () => {
    setMobileOpen((prev) => !prev);
  };

  if (role === null) return null;

  if (!approved) {
    return (
      <Box className="p-6 text-center">
        <h2 className="text-xl font-semibold text-red-500">
          Awaiting Admin Approval
        </h2>
        <p className="text-gray-600 mt-2">
          You will gain access once your account is approved.
        </p>
      </Box>
    );
  }

  const drawerContent = (
    <Box
      sx={{
        width: drawerWidth,
        height: "100vh",
        backgroundColor: "#f3f4f6",
        overflowY: "auto",
      }}
    >
      <Box className="flex items-center justify-between px-4 py-3">
        <Link href="/dashboard/admin" className="flex items-center gap-2">
          <Image src="/aic_logo.png" alt="logo" width={50} height={50} />
          <div className="flex flex-col leading-tight">
            <span className="text-lg font-bold">Milimani</span>
            <span className="text-sm self-end">Church, KE</span>
          </div>
        </Link>
        {isMobile && (
          <IconButton onClick={toggleDrawer}>
            <CloseIcon />
          </IconButton>
        )}
      </Box>
      <Toolbar>
        <Typography
          variant="h6"
          noWrap
          sx={{ fontSize: "17px", fontFamily: "'Poppins', sans-serif" }}
        >
          Admin Panel
        </Typography>
      </Toolbar>
      <Divider />
      <Box sx={{ overflow: "auto" }}>
        {NAVIGATION.map((section) => (
          <Box key={section.title}>
            <Typography
              variant="subtitle2"
              sx={{
                pl: 2,
                mt: 2,
                mb: 1,
                fontSize: "17px",
                fontFamily: "'Poppins', sans-serif",
              }}
            >
              {section.title}
            </Typography>
            <List disablePadding>
              {section.items.map((item) => {
                if (!item.visible.includes(role)) return null;

                if (item.logout) {
                  return (
                    <ListItemButton key={item.label} onClick={handleLogout}>
                      <ListItemIcon>{item.icon}</ListItemIcon>
                      <Typography
                        sx={{
                          fontFamily: "'Poppins', sans-serif",
                          fontSize: "13px",
                          fontWeight: 500,
                        }}
                      >
                        {item.label}
                      </Typography>
                    </ListItemButton>
                  );
                }

                return (
                  <Link
                    key={item.label}
                    href={item.href!}
                    passHref
                    legacyBehavior
                  >
                    <ListItemButton
                      selected={pathname === item.href}
                      component="a"
                      sx={{
                        "&:hover": {
                          backgroundColor: "#e0e7ff",
                        },
                        "&.Mui-selected": {
                          backgroundColor: "#c7d2fe",
                          "&:hover": {
                            backgroundColor: "#a5b4fc",
                          },
                        },
                      }}
                    >
                      <ListItemIcon>{item.icon}</ListItemIcon>
                      <Typography
                        sx={{
                          fontFamily: "'Poppins', sans-serif",
                          fontSize: "13px",
                          fontWeight: 500,
                        }}
                      >
                        {item.label}
                      </Typography>
                    </ListItemButton>
                  </Link>
                );
              })}
            </List>
            <Divider />
          </Box>
        ))}
      </Box>
    </Box>
  );

  return (
    <>
      {isMobile && (
        <Box sx={{ p: 2 }}>
          <IconButton onClick={toggleDrawer}>
            <MenuIcon fontSize="large" />
          </IconButton>
        </Box>
      )}

      {isMobile ? (
        <Drawer
          anchor="left"
          open={mobileOpen}
          onClose={toggleDrawer}
          ModalProps={{ keepMounted: true }}
          sx={{ "& .MuiDrawer-paper": { width: drawerWidth } }}
        >
          {drawerContent}
        </Drawer>
      ) : (
        <Box
          sx={{
            width: drawerWidth,
            flexShrink: 0,
            display: { xs: "none", md: "block" },
          }}
        >
          {drawerContent}
        </Box>
      )}
    </>
  );
}
