"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  LayoutDashboard,
  CalendarDays,
  Users,
  Award,
  FileBadge,
  Bell,
  MessageSquareText,
  UserCircle,
  FileText,
  LogOut,
} from "lucide-react";
import { useEffect, useState } from "react";
import { createClient } from "@/lib/supabase/client";
import Modal from "@/components/ui/Modal";
import Button from "@/components/ui/Button";

type MobileAppShellProps = {
  role: "admin" | "volunteer";
  children: React.ReactNode;
  profileName: string;
  profileEmail: string;
};

export default function MobileAppShell({
  role,
  children,
  profileName,
  profileEmail,
}: MobileAppShellProps) {
  const path = usePathname();
  const router = useRouter();
  const supabase = createClient();
  const [unreadNotifsCount, setUnreadNotifsCount] = useState(0);
  const [showConfirm, setShowConfirm] = useState(false);

  const initials = profileName
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase() || "V";

  useEffect(() => {
    (async () => {
      if (role === "volunteer") {
        const { data: userRes } = await supabase.auth.getUser();
        if (userRes.user) {
          const { count } = await supabase
            .from("notifications")
            .select("id", { count: "exact", head: true })
            .eq("volunteer_id", userRes.user.id)
            .eq("is_read", false);
          setUnreadNotifsCount(count || 0);
        }
      }
    })();
  }, [role, supabase, path]);

  async function handleSignOut() {
    await supabase.auth.signOut();
    setShowConfirm(false);
    router.push("/login");
    router.refresh();
  }

  // Define navigation items based on role
  const volunteerNavItems = [
    { href: "/", label: "Home", icon: LayoutDashboard },
    { href: "/programs", label: "Programs", icon: CalendarDays },
    { href: "/applications", label: "Activity", icon: FileText },
    { href: "/profile", label: "Profile", icon: UserCircle },
  ];

  const adminNavItems = [
    { href: "/", label: "Dashboard", icon: LayoutDashboard },
    { href: "/programs", label: "Programs", icon: CalendarDays },
    { href: "/volunteers", label: "Volunteers", icon: Users },
    { href: "/merit", label: "Merit", icon: Award },
    { href: "/profile", label: "Profile", icon: UserCircle },
  ];

  const navItems = role === "admin" ? adminNavItems : volunteerNavItems;

  return (
    <div className="flex h-full w-full flex-col bg-sand-light font-sans shadow-inner">
      {/* Mobile Top Header */}
      <header className="sticky top-0 z-30 flex h-14 items-center justify-between border-b border-sand-dark bg-white px-4">
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-card bg-emerald text-[11px] font-extrabold text-white">
            PI
          </div>
          <div className="leading-tight">
            <h1 className="text-xs font-bold text-ink">PUSAT ISLAM</h1>
            <p className="text-[9px] font-medium text-emerald uppercase tracking-wider">
              {role === "admin" ? "Admin App" : "Volunteer App"}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          {role === "volunteer" && (
            <Link href="/inbox" className="relative p-1 text-muted hover:text-emerald">
              <Bell size={20} />
              {unreadNotifsCount > 0 && (
                <span className="absolute -right-0.5 -top-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-error text-[8px] font-bold text-white">
                  {unreadNotifsCount}
                </span>
              )}
            </Link>
          )}
          <Link href="/profile" className="flex h-8 w-8 items-center justify-center rounded-full bg-emerald text-[11px] font-bold text-white hover:opacity-90">
            {initials}
          </Link>
          <button onClick={() => setShowConfirm(true)} title="Sign Out" className="p-1 text-muted hover:text-error">
            <LogOut size={18} />
          </button>
        </div>
      </header>

      {/* Main Content Area */}
      <main className="flex-1 overflow-y-auto px-4 py-4 pb-20">
        {children}
      </main>

      {/* Mobile Bottom Navigation */}
      <nav className="fixed bottom-0 left-0 right-0 z-30 flex h-14 border-t border-sand-dark bg-white pb-safe shadow-lg md:absolute">
        {navItems.map(({ href, label, icon: Icon }) => {
          const active = href === "/" ? path === "/" : path.startsWith(href);
          return (
            <Link
              key={href}
              href={href}
              className={`flex flex-1 flex-col items-center justify-center gap-0.5 py-1 text-center transition-colors ${
                active
                  ? "text-emerald font-bold"
                  : "text-muted hover:text-ink"
              }`}
            >
              <Icon size={18} className={active ? "stroke-[2.5]" : "stroke-[2]"} />
              <span className="text-[10px] tracking-tight">{label}</span>
            </Link>
          );
        })}
      </nav>

      {/* Logout Confirmation Modal */}
      <Modal open={showConfirm} onClose={() => setShowConfirm(false)} title="Confirm Sign Out">
        <div className="space-y-4 p-1">
          <p className="text-xs text-muted">
            Are you sure you want to sign out? This will end your current session.
          </p>
          <div className="flex justify-end gap-2 border-t border-sand-light pt-3">
            <Button variant="secondary" onClick={() => setShowConfirm(false)}>
              Cancel
            </Button>
            <Button variant="danger" onClick={handleSignOut}>
              Sign Out
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
