"use client";

import { type ReactNode, useEffect, useState } from "react";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";

import { BedDouble, Bell, Command, CreditCard, Home, LogOut, Luggage, Package, Plane, User } from "lucide-react";

import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { APP_CONFIG } from "@/config/app-config";
import { type AuthUser, getAuthUser, logout, ROLE_COLORS, ROLE_LABELS } from "@/lib/auth";
import { getBookingsByGuest, getGuestByEmail, getGuestByUserId } from "@/lib/cruise-store";
import { cn, getInitials } from "@/lib/utils";

const navItems = [
  { label: "Portal Home", href: "/portal", icon: Home, exact: true },
  { label: "Booking", href: "/portal/booking", icon: Luggage, dynamicBooking: true },
  { label: "Payments", href: "/portal/payments", icon: CreditCard },
  { label: "Cabin", href: "/portal/cabin", icon: BedDouble },
  { label: "Add-ons", href: "/portal/add-ons", icon: Package },
  { label: "Travel", href: "/portal/travel", icon: Plane },
  { label: "Notifications", href: "/portal/notifications", icon: Bell },
  { label: "Profile", href: "/portal/profile", icon: User },
];

export function ClientPortalShell({ children }: { children: ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [user, setUser] = useState<AuthUser | null>(null);
  const [bookingHref, setBookingHref] = useState("/portal");
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const u = getAuthUser();
    if (!u) {
      router.replace("/login");
      return;
    }
    if (u.role !== "client") {
      router.replace("/dashboard");
      return;
    }
    setUser(u);

    const guest = getGuestByUserId(u.id) ?? getGuestByEmail(u.email);
    if (guest) {
      const bookings = getBookingsByGuest(guest.id);
      if (bookings[0]) {
        setBookingHref(`/portal/booking/${bookings[0].id}`);
      }
    }

    setReady(true);
  }, [router]);

  const handleLogout = () => {
    logout();
    router.replace("/login");
  };

  if (!ready) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <div className="size-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-50 border-b bg-background/80 backdrop-blur-md">
        <div className="mx-auto flex h-14 max-w-6xl items-center justify-between px-4">
          <div className="flex items-center gap-2.5">
            <Command className="size-5 shrink-0" />
            <span className="font-bold text-base">{APP_CONFIG.name}</span>
            <span className="hidden text-muted-foreground text-xs sm:inline">· Client Portal</span>
          </div>

          {user && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-auto gap-2 px-2 py-1.5">
                  <Avatar className="size-7 rounded-full">
                    <AvatarFallback className="rounded-full text-xs">{getInitials(user.name)}</AvatarFallback>
                  </Avatar>
                  <div className="hidden text-left sm:block">
                    <p className="font-medium text-sm leading-none">{user.name}</p>
                    <p className="text-muted-foreground text-xs">{user.email}</p>
                  </div>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-52">
                <DropdownMenuLabel className="font-normal">
                  <div className="flex flex-col gap-0.5">
                    <span className="font-medium">{user.name}</span>
                    <span className="text-muted-foreground text-xs">{user.email}</span>
                    <span
                      className={`mt-1 inline-flex w-fit items-center rounded border px-1.5 py-0 font-medium text-[10px] ${ROLE_COLORS[user.role]}`}
                    >
                      {ROLE_LABELS[user.role]}
                    </span>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
                  <LogOut className="size-4" /> Log out
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      </header>

      <div className="mx-auto flex max-w-6xl gap-8 px-4 py-8">
        <aside className="hidden w-52 shrink-0 md:block">
          <nav className="flex flex-col gap-1">
            {navItems.map((item) => {
              const href = item.dynamicBooking ? bookingHref : item.href;
              const isActive = item.exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);

              return (
                <Link
                  key={item.label}
                  href={href}
                  className={cn(
                    "flex items-center gap-2.5 rounded-md px-3 py-2 text-sm transition-colors",
                    isActive
                      ? "bg-primary/10 font-medium text-primary"
                      : "text-muted-foreground hover:bg-muted hover:text-foreground",
                  )}
                >
                  <item.icon className="size-4 shrink-0" />
                  {item.label}
                </Link>
              );
            })}
          </nav>
        </aside>

        <main className="min-w-0 flex-1 pb-20 md:pb-0">{children}</main>
      </div>

      {/* Mobile bottom navigation */}
      <nav className="fixed inset-x-0 bottom-0 z-50 border-t bg-background/95 backdrop-blur md:hidden">
        <div className="mx-auto flex max-w-lg justify-around px-1 py-1">
          {navItems.slice(0, 5).map((item) => {
            const href = item.dynamicBooking ? bookingHref : item.href;
            const isActive = item.exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
            return (
              <Link
                key={item.label}
                href={href}
                className={cn(
                  "flex flex-1 flex-col items-center gap-0.5 py-2 text-[10px]",
                  isActive ? "text-primary" : "text-muted-foreground",
                )}
              >
                <item.icon className="size-5" />
                <span className="truncate">{item.label.split(" ")[0]}</span>
              </Link>
            );
          })}
        </div>
      </nav>
    </div>
  );
}
