"use client";

import { useState, useEffect } from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import Link from "next/link";
import {
  Car,
  Hotel,
  Sparkles,
  Package,
  LogIn,
  UserPlus,
  LogOut,
  LayoutDashboard,
  User,
  Box,
  CreditCard,
  Home,
  HelpCircle,
  Info,
  Shield,
  Mail,
  ReceiptText,
} from "lucide-react";

interface MobileSidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

export function MobileSidebar({ isOpen, onClose }: MobileSidebarProps) {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    const customerSession =
      sessionStorage.getItem("customer_session") ||
      localStorage.getItem("customer_session");
    setIsLoggedIn(!!customerSession);

    const handleSessionUpdate = () => {
      const session =
        sessionStorage.getItem("customer_session") ||
        localStorage.getItem("customer_session");
      setIsLoggedIn(!!session);
    };

    window.addEventListener("sessionUpdate", handleSessionUpdate);
    return () =>
      window.removeEventListener("sessionUpdate", handleSessionUpdate);
  }, []);

  const handleLogout = () => {
    sessionStorage.removeItem("customer_session");
    localStorage.removeItem("customer_session");
    localStorage.removeItem("teertham_auth_token");
    window.dispatchEvent(new Event("sessionUpdate"));
    onClose();
    window.location.href = "/";
  };

  const navLinks = [
    { href: "/", label: "Home", icon: Home },
    { href: "/vehicle-booking", label: "Vehicles", icon: Car },
    { href: "/fixed-packages", label: "Fix Packages", icon: Package },
    { href: "/faq", label: "FAQ", icon: HelpCircle },
    { href: "/about-us", label: "About Us", icon: Info },
    { href: "/privacy-policy", label: "Privacy Policy", icon: Shield },
    { href: "/contact-us", label: "Contact Us", icon: Mail },
  ];

  const userMenuItems = [
    { href: "/user/dashboard", label: "Dashboard", icon: LayoutDashboard },
    { href: "/user/manage-profile", label: "Manage Profile", icon: User },
    { href: "/user/vehicle-bookings", label: "Vehicle Bookings", icon: Car },
    { href: "/user/hotel-bookings", label: "Hotel Bookings", icon: Hotel },
    { href: "/user/fixed-bookings", label: "Fixed Bookings", icon: Box },
    {
      href: "/user/payment-methods",
      label: "Payment Methods",
      icon: CreditCard,
    },
    {
      href: "/user/my-transactions",
      label: "My transactions",
      icon: ReceiptText,
    },
    {
      href: "/user/spiritual-bookings",
      label: "Spiritual Bookings",
      icon: Sparkles,
    },
    { href: "/user/custom-packages", label: "Custom Packages", icon: Package },
  ];

  return (
    <>
      {/* Backdrop */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-background/80 backdrop-blur-sm z-40"
          onClick={onClose}
          aria-hidden="true"
        />
      )}

      {/* Sidebar */}
      <aside
        className={cn(
          "fixed right-0 top-0 z-50 flex h-screen w-80 flex-col",
          "bg-card border-l border-border/40 shadow-2xl",
          "transition-transform duration-300 ease-in-out",
          isOpen ? "translate-x-0" : "translate-x-full"
        )}
        aria-label="Mobile navigation"
        aria-hidden={!isOpen}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border/40 px-4 py-4 bg-gradient-to-br from-primary/5 to-transparent shrink-0">
          <div className="flex items-center gap-2">
            <div className="relative flex h-8 w-8 items-center justify-center rounded-lg frontend-gradient-primary shadow-md">
              <Sparkles className="h-4 w-4 text-white" aria-hidden="true" />
            </div>
            <span className="text-lg font-bold frontend-text-gradient">
              Ameera Holidays
            </span>
          </div>
          <Button
            variant="ghost"
            size="icon"
            onClick={onClose}
            className="h-8 w-8"
            aria-label="Close navigation menu"
          >
            <X className="h-5 w-5" aria-hidden="true" />
          </Button>
        </div>

        {/* Navigation */}
        <div className="flex-1 overflow-y-auto px-4 py-4 space-y-1">
          {/* Main Navigation Links */}
          <div className="space-y-1">
            {navLinks.map((link) => {
              const Icon = link.icon;
              return (
                <Link
                  key={link.href}
                  href={link.href}
                  onClick={onClose}
                  className="flex items-center gap-3 h-11 px-3 rounded-md hover:bg-primary/10 hover:text-primary transition-colors font-medium"
                >
                  <Icon className="h-5 w-5" aria-hidden="true" />
                  <span>{link.label}</span>
                </Link>
              );
            })}
          </div>

          {isLoggedIn && (
            <>
              <div className="my-4 border-t border-border/40" />
              <div className="space-y-1">
                <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  My Account
                </p>
                {userMenuItems.map((item) => {
                  const Icon = item.icon;
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={onClose}
                      className="flex items-center gap-3 h-11 px-3 rounded-md hover:bg-primary/10 hover:text-primary transition-colors font-medium"
                    >
                      <Icon className="h-5 w-5" aria-hidden="true" />
                      <span>{item.label}</span>
                    </Link>
                  );
                })}
              </div>
            </>
          )}
        </div>

        {/* Footer Actions */}
        <div className="border-t border-border/40 p-4 space-y-2 shrink-0">
          {isLoggedIn ? (
            <Button
              variant="outline"
              className="w-full gap-2 h-11 hover:bg-red-50 hover:text-red-600 hover:border-red-300 transition-all bg-transparent"
              onClick={handleLogout}
            >
              <LogOut className="h-5 w-5" aria-hidden="true" />
              <span className="font-medium">Logout</span>
            </Button>
          ) : (
            <>
              <Button
                asChild
                variant="outline"
                className="w-full gap-2 h-11 bg-transparent hover:bg-primary/10 hover:text-primary hover:border-primary transition-all"
              >
                <Link href="/login" onClick={onClose}>
                  <LogIn className="h-5 w-5" aria-hidden="true" />
                  <span className="font-medium">Login</span>
                </Link>
              </Button>

              <Button
                asChild
                className="w-full gap-2 h-11 frontend-gradient-primary hover:opacity-90 transition-opacity shadow-md"
              >
                <Link href="/create-account" onClick={onClose}>
                  <UserPlus className="h-5 w-5" aria-hidden="true" />
                  <span className="font-medium">Create Account</span>
                </Link>
              </Button>
            </>
          )}
        </div>
      </aside>
    </>
  );
}
