"use client";

import type React from "react";
import { useEffect, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
  LayoutDashboard,
  User,
  Box,
  CreditCard,
  Car,
  ReceiptText,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { USER_DASHBOARD_LAYOUT } from "@/lib/strings/user-dashboard";
import { syncClientAuthTokenAction } from "@/features/auth/actions/auth-api-actions";

type CustomerSession = {
  userId?: string;
  email: string;
  name: string;
  role: "customer";
  loginTime: string;
};

const CUSTOMER_SESSION_KEY = "customer_session";
const AUTH_TOKEN_STORAGE_KEY = "teertham_auth_token";

function parseCustomerSession(value: string | null): CustomerSession | null {
  if (!value) return null;

  try {
    const session = JSON.parse(value) as Partial<CustomerSession>;
    if (session.email && session.role === "customer") {
      return {
        userId: session.userId,
        email: session.email,
        name: session.name || "User",
        role: "customer",
        loginTime: session.loginTime || new Date().toISOString(),
      };
    }
  } catch (error) {
    console.error("Error parsing customer session:", error);
  }

  return null;
}

function persistCustomerSession(session: CustomerSession) {
  const value = JSON.stringify(session);
  sessionStorage.setItem(CUSTOMER_SESSION_KEY, value);
  localStorage.setItem(CUSTOMER_SESSION_KEY, value);
}

export default function UserDashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [session, setSession] = useState<CustomerSession | null>(null);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    let active = true;

    const hydrateSession = async () => {
      const clientToken = localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);

      if (clientToken) {
        await syncClientAuthTokenAction(clientToken);
      }

      const storedSession = parseCustomerSession(
        sessionStorage.getItem(CUSTOMER_SESSION_KEY) ||
          localStorage.getItem(CUSTOMER_SESSION_KEY)
      );

      if (storedSession) {
        persistCustomerSession(storedSession);
        if (active) {
          setSession(storedSession);
          window.dispatchEvent(new Event("sessionUpdate"));
        }
        return;
      }

      if (!clientToken) {
        sessionStorage.removeItem(CUSTOMER_SESSION_KEY);
        localStorage.removeItem(CUSTOMER_SESSION_KEY);
        router.replace("/login");
        return;
      }

      const fallbackSession: CustomerSession = {
        email: "",
        name: "User",
        role: "customer",
        loginTime: new Date().toISOString(),
      };

      persistCustomerSession(fallbackSession);
      window.dispatchEvent(new Event("sessionUpdate"));
      setSession(fallbackSession);
    };

    void hydrateSession();

    return () => {
      active = false;
    };
  }, [router]);

  const menuItems = [
    {
      href: "/user/dashboard",
      label: USER_DASHBOARD_LAYOUT.MENU_DASHBOARD,
      icon: LayoutDashboard,
    },
    {
      href: "/user/manage-profile",
      label: USER_DASHBOARD_LAYOUT.MENU_MANAGE_PROFILE,
      icon: User,
    },
    {
      href: "/user/vehicle-bookings",
      label: "Vehicle Bookings",
      icon: Car,
    },
    { 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: USER_DASHBOARD_LAYOUT.MENU_CUSTOM_PACKAGES,
      icon: Package,
    }, */
  ];

  if (!session) {
    return null;
  }

  return (
    <div className="min-h-[calc(100vh-64px)] bg-gradient-to-br from-teal-50/50 via-white to-cyan-50/50">
      <div className="container mx-auto px-4 py-6 lg:py-8">
        <div className="flex gap-6 lg:gap-8">
          {/* Desktop sidebar only */}
          <aside className="hidden lg:block w-72 shrink-0">
            <div className="sticky top-24 bg-white rounded-2xl shadow-lg border border-border/50 overflow-hidden">
              <div className="border-b border-border/50 px-5 pb-4 pt-5 text-center">
                <Link
                  href="/"
                  className="inline-flex justify-center text-lg font-bold"
                >
                  <span className="text-[#023047]">Ameera</span>
                  <span className="ml-1 text-[#f84200]">Holidays</span>
                </Link>
              </div>
              {/* Navigation */}
              <nav className="p-4 space-y-1.5">
                {menuItems.map((item) => {
                  const Icon = item.icon;
                  const isActive = pathname === item.href;
                  return (
                    <Link key={item.href} href={item.href}>
                      <Button
                        variant={isActive ? "default" : "ghost"}
                        className={cn(
                          "w-full justify-start gap-3 h-12 transition-all duration-200",
                          isActive
                            ? "bg-gradient-to-r from-teal-600 to-cyan-600 text-white shadow-md hover:shadow-lg hover:from-teal-700 hover:to-cyan-700"
                            : "hover:bg-teal-50 text-gray-700 hover:text-teal-700"
                        )}
                      >
                        <Icon className="h-5 w-5 shrink-0" />
                        <span className="font-medium text-sm">
                          {item.label}
                        </span>
                      </Button>
                    </Link>
                  );
                })}
              </nav>
            </div>
          </aside>

          <main className="flex-1 min-w-0">
            <div className="bg-white rounded-2xl shadow-lg border border-border/50 p-6 lg:p-8">
              {children}
            </div>
          </main>
        </div>
      </div>
    </div>
  );
}
