"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import { apiRequest, apiUrl } from "@/lib/api";
import { formatToday } from "@/lib/format-today";
import { useLanguage } from "@/lib/i18n";
import { DashboardSidebar } from "@/components/layout/dashboard-sidebar";
import { HeaderProfileMenu } from "@/components/layout/header-profile-menu";
import { LanguageSwitcher } from "@/components/language-switcher";
import { Button } from "@/components/ui/button";
import { Bell } from "lucide-react";

type GuideProfileUser = {
  uuid?: string | number;
  id?: string | number;
  name?: string | null;
  full_name?: string | null;
  guide_name?: string | null;
  first_name?: string | null;
  last_name?: string | null;
  email?: string | null;
};

type GuideProfileResponse = {
  success?: boolean;
  data?: {
    user?: GuideProfileUser;
  };
};

function profileName(profile?: GuideProfileUser) {
  const firstLast = [profile?.first_name, profile?.last_name]
    .filter(Boolean)
    .join(" ")
    .trim();

  return (
    profile?.name ||
    profile?.full_name ||
    profile?.guide_name ||
    firstLast ||
    ""
  ).trim();
}

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { user, token, updateUser, isAuthenticated, isGuide, isLoading } =
    useAuth();
  const { language, t } = useLanguage();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push("/auth/login");
    } else if (!isLoading && isAuthenticated && !isGuide) {
      router.push("/admin");
    }
  }, [isAuthenticated, isGuide, isLoading, router]);

  useEffect(() => {
    if (isLoading || !isAuthenticated || !isGuide) {
      return;
    }

    const activeToken = token || localStorage.getItem("auth_token");

    if (!activeToken) {
      return;
    }

    let ignore = false;

    const syncGuideProfile = async () => {
      try {
        const response = await apiRequest(apiUrl("/profile"), {
          headers: {
            Authorization: `Bearer ${activeToken}`,
            Accept: "application/json",
          },
        });
        const result = (await response.json()) as GuideProfileResponse;
        const profile = result.data?.user;
        const nextName = profileName(profile);
        const nextEmail = profile?.email || user?.email;
        const nextId = String(profile?.uuid || profile?.id || user?.id || "");

        if (
          !ignore &&
          response.ok &&
          result.success &&
          (nextName || nextEmail || nextId) &&
          (nextName !== user?.name ||
            nextEmail !== user?.email ||
            nextId !== user?.id)
        ) {
          updateUser({
            id: nextId || user?.id,
            guideId: nextId || user?.guideId,
            name: nextName || user?.name,
            email: nextEmail,
          });
        }
      } catch {
        // Keep the existing login session if the profile refresh is unavailable.
      }
    };

    syncGuideProfile();

    return () => {
      ignore = true;
    };
  }, [
    isAuthenticated,
    isGuide,
    isLoading,
    token,
    updateUser,
    user?.email,
    user?.guideId,
    user?.id,
    user?.name,
  ]);

  if (isLoading || !isAuthenticated || !isGuide) {
    return (
      <div className="flex h-screen items-center justify-center bg-[var(--theme-surface)]">
        <div className="h-10 w-10 animate-spin rounded-full border-4 border-[var(--theme-secondary)]/25 border-t-[var(--theme-primary)]" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[var(--theme-surface)]">
      <DashboardSidebar />
      <main className="flex min-h-screen flex-col pt-16 lg:ml-64 lg:pt-0">
        <header className="flex min-h-16 flex-col gap-2 border-b border-[var(--theme-border)] bg-white/95 px-4 py-2 shadow-sm backdrop-blur-xl sm:h-[65px] sm:flex-row sm:items-center sm:justify-between sm:py-0">
          <div>
            <h1 className="text-xl font-black tracking-tight text-foreground sm:text-2xl">
              {t("guide.welcomeBack")}!{" "}
              <span className="text-[var(--theme-primary)]">
                {user?.name || "Guide"}
              </span>
            </h1>
            <p className="mt-0.5 text-sm font-medium text-muted-foreground">
              {formatToday(language)}
            </p>
          </div>

          <div className="flex items-center gap-2">
            <LanguageSwitcher />
            <Button
              variant="outline"
              size="icon"
              className="relative h-11 w-11 rounded-full border-[var(--theme-border-strong)] bg-white"
              aria-label="Notifications"
            >
              <Bell className="h-5 w-5 text-[var(--theme-primary)]" />
              <span className="absolute right-2.5 top-2.5 h-2.5 w-2.5 rounded-full border-2 border-white bg-[var(--theme-accent)]" />
            </Button>

            <HeaderProfileMenu fallbackName="Guide" initial="G" />
          </div>
        </header>

        <div className="flex-1 px-3 py-4 sm:px-4">{children}</div>

        <footer className="border-t border-[var(--theme-border)] bg-white/80 px-4 py-3 text-center text-sm text-muted-foreground">
          &copy; {new Date().getFullYear()}
          <span className="ml-1">{t("common.copyright")}</span>
        </footer>
      </main>
    </div>
  );
}
