import { Link, useRouterState } from "@tanstack/react-router";
import { type ReactNode } from "react";
import { Moon, Sun, Settings } from "lucide-react";
import { bottomNav, categoryNav, desktopNav } from "./nav-config";
import { useTheme } from "@/lib/theme";
import { cn } from "@/lib/utils";
import { useUserProfile } from "@/lib/user-profile";
import { useUiSettings, t } from "@/lib/ui-settings";
import { OnboardingScreen } from "./onboarding-screen";
import { SplashScreen } from "./splash-screen";
import { svgs } from "@/assets/svgMap";

function ThemeToggle({ compact = false }: { compact?: boolean }) {
  const { theme, toggle } = useTheme();
  const dark = theme === "dark";
  return (
    <button
      type="button"
      onClick={toggle}
      aria-label={dark ? "Switch to light theme" : "Switch to dark theme"}
      className={cn(
        "press relative grid place-items-center rounded-xl border border-border bg-card text-foreground hover:border-emerald-500/40 shadow-xs transition-all",
        compact ? "h-8.5 w-8.5" : "h-9.5 w-9.5",
      )}
    >
      <Sun
        className={cn(
          "absolute h-4 w-4 text-amber-500 transition-all duration-300",
          dark ? "scale-50 rotate-90 opacity-0" : "scale-100 rotate-0 opacity-100",
        )}
      />
      <Moon
        className={cn(
          "absolute h-4 w-4 text-emerald-400 transition-all duration-300",
          dark ? "scale-100 rotate-0 opacity-100" : "scale-50 -rotate-90 opacity-0",
        )}
      />
    </button>
  );
}

export function AppShell({ children }: { children: ReactNode }) {
  const profile = useUserProfile();
  const uiSettings = useUiSettings();
  const pathname = useRouterState({ select: (s) => s.location.pathname });

  const getNavLabel = (to: string, fallback: string) => {
    switch (to) {
      case "/companion":
        return t("nav_ai_voice", uiSettings.language);
      case "/yoga":
        return t("nav_ai_yoga", uiSettings.language);
      case "/activities":
        return t("nav_games", uiSettings.language);
      case "/memory":
        return t("nav_memories", uiSettings.language);
      case "/reminders":
        return t("nav_dawai", uiSettings.language);
      case "/family":
        return t("nav_parivaar", uiSettings.language);
      case "/progress":
        return t("nav_progress", uiSettings.language);
      case "/profile":
        return t("nav_settings", uiSettings.language);
      default:
        return fallback;
    }
  };

  const isCompanionPage = pathname.startsWith("/companion");

  if (isCompanionPage) {
    return (
      <div
        className="h-screen w-screen bg-background text-foreground flex flex-col antialiased overflow-hidden transition-colors duration-200"
        style={{ backgroundImage: "var(--app-bg-gradient)" }}
      >
        <main className="h-full w-full flex flex-col flex-1">{children}</main>
        <OnboardingScreen />
      </div>
    );
  }

  return (
    <div
      className="min-h-screen bg-background text-foreground flex flex-col antialiased selection:bg-emerald-500/30 selection:text-emerald-700 dark:selection:text-emerald-200 transition-colors duration-200"
      style={{ backgroundImage: "var(--app-bg-gradient)" }}
    >
      {/* Animated Made-in-India Splash Screen */}
      <SplashScreen />

      {/* Grounded Senior-Friendly Top Header */}
      <header className="sticky top-0 z-40 w-full border-b border-border/80 bg-background/95 backdrop-blur-md px-3 sm:px-6 py-2.5 shadow-xs">
        <div className="mx-auto flex max-w-5xl items-center justify-between gap-3">
          {/* Logo & Clean Title */}
          <Link to="/" className="flex items-center gap-2.5 group">
            <div className="grid h-10 w-10 place-items-center rounded-2xl bg-card border border-border/80 p-1 shadow-xs group-hover:scale-105 transition-transform">
              <img src={svgs.miscLogo} alt="NeuroSaathi" className="h-7 w-7 object-contain" />
            </div>
            <span className="font-display text-lg sm:text-xl font-black tracking-tight text-foreground leading-tight">
              NeuroSaathi
            </span>
          </Link>

          {/* Desktop Navigation Links */}
          <nav className="hidden md:flex items-center gap-1.5 bg-muted/60 p-1.5 rounded-2xl border border-border/60">
            {desktopNav.map((item) => {
              return (
                <Link
                  key={item.to}
                  to={item.to}
                  activeOptions={{ exact: item.to === "/" }}
                  className="press flex items-center gap-2 rounded-xl px-3 py-1.5 text-xs sm:text-sm font-extrabold text-muted-foreground transition-all hover:text-foreground hover:bg-card/80 data-[status=active]:bg-card data-[status=active]:text-emerald-600 dark:data-[status=active]:text-emerald-400 data-[status=active]:border data-[status=active]:border-emerald-500/30 data-[status=active]:shadow-xs"
                >
                  <img src={item.iconSrc} alt={item.label} className="h-4.5 w-4.5 object-contain" />
                  <span>{item.label}</span>
                  {item.badge ? (
                    <span className="grid h-4 min-w-4 place-items-center rounded-full bg-emerald-500 px-1 text-[9px] font-bold text-white">
                      {item.badge}
                    </span>
                  ) : null}
                </Link>
              );
            })}
          </nav>

          {/* Header Right Action Shortcuts */}
          <div className="flex items-center gap-2">
            <ThemeToggle />

            {/* Settings Quick Access Button */}
            <Link
              to="/profile"
              aria-label="Settings & Customization"
              title="Settings & Customization"
              className="press grid h-10 w-10 place-items-center rounded-2xl border border-emerald-500/40 bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 font-extrabold text-sm shadow-xs hover:border-emerald-500 hover:bg-emerald-500/25 transition-all"
            >
              <Settings className="h-5 w-5" />
            </Link>
          </div>
        </div>
      </header>

      {/* Airtel Thanks Style Top Bar: Icon Tile Box at Top + Text Label Below + Active Underline Bar */}
      <div className="w-full border-b border-border/80 bg-card/90 backdrop-blur-md pt-2.5 pb-2 px-3 sm:px-6 shadow-xs">
        <div className="mx-auto max-w-5xl">
          <div className="no-scrollbar flex items-center justify-between sm:justify-start gap-3 sm:gap-5 overflow-x-auto py-1 px-1 scroll-smooth">
            {categoryNav.map((cat) => {
              const isActive = pathname.startsWith(cat.to);
              return (
                <Link
                  key={cat.to}
                  to={cat.to}
                  className="press shrink-0 flex flex-col items-center gap-1.5 group select-none"
                >
                  {/* Rounded Icon Tile Box */}
                  <div
                    className={cn(
                      "relative grid h-13 w-13 sm:h-15 sm:w-15 place-items-center rounded-2xl transition-all duration-200 shadow-xs p-2.5",
                      isActive
                        ? "bg-card border-2 border-emerald-500 text-emerald-600 dark:text-emerald-400 shadow-md shadow-emerald-500/15 scale-105 ring-2 ring-emerald-500/20"
                        : "bg-muted/70 hover:bg-card border border-border/80 text-muted-foreground hover:border-emerald-500/40",
                    )}
                  >
                    <img
                      src={cat.iconSrc}
                      alt={cat.label}
                      className="h-7 w-7 sm:h-8 sm:w-8 object-contain transition-transform group-hover:scale-110"
                    />
                    {cat.badge ? (
                      <span className="absolute -top-1.5 -right-1.5 grid h-4 min-w-4 place-items-center rounded-full bg-emerald-500 px-1 text-[9px] font-extrabold text-white shadow-xs border border-white dark:border-gray-900">
                        {cat.badge}
                      </span>
                    ) : null}
                  </div>

                  {/* Label Below Icon Tile Box */}
                  <span
                    className={cn(
                      "text-xs sm:text-sm font-extrabold tracking-tight transition-colors whitespace-nowrap",
                      isActive
                        ? "text-emerald-700 dark:text-emerald-300 font-black"
                        : "text-muted-foreground group-hover:text-foreground",
                    )}
                  >
                    {getNavLabel(cat.to, cat.label)}
                  </span>

                  {/* Active Underline Indicator Line (Airtel Thanks Style) */}
                  <div
                    className={cn(
                      "h-1 rounded-full transition-all duration-300",
                      isActive
                        ? "w-7 sm:w-9 bg-emerald-500 shadow-xs shadow-emerald-500/40"
                        : "w-0 bg-transparent",
                    )}
                  />
                </Link>
              );
            })}
          </div>
        </div>
      </div>

      {/* Main Content View */}
      <main
        key={pathname}
        className="mx-auto w-full max-w-md md:max-w-3xl lg:max-w-5xl px-3 sm:px-6 md:px-8 pb-28 sm:pb-32 pt-3 flex-1"
      >
        {children}
      </main>

      {/* Grounded Fixed Bottom Navigation Bar for Mobile (Bigger Senior Buttons) */}
      <nav className="md:hidden fixed inset-x-0 bottom-0 z-50 border-t border-border/80 bg-card/95 backdrop-blur-xl px-2 py-1.5 pb-[max(0.6rem,env(safe-area-inset-bottom))] shadow-2xl">
        <div className="mx-auto grid max-w-md grid-cols-5 items-center justify-between gap-1">
          {bottomNav.map((item) => {
            return (
              <Link
                key={item.to}
                to={item.to}
                activeOptions={{ exact: item.to === "/" }}
                className="press group relative flex flex-col items-center justify-center py-1.5 px-1 rounded-2xl text-muted-foreground transition-all duration-200 min-h-[54px] data-[status=active]:text-emerald-600 dark:data-[status=active]:text-emerald-400 data-[status=active]:bg-emerald-500/15 data-[status=active]:border data-[status=active]:border-emerald-500/40 data-[status=active]:shadow-xs"
              >
                <span className="relative">
                  <img
                    src={item.iconSrc}
                    alt={item.label}
                    className="h-6 w-6 object-contain transition-transform duration-200 group-data-[status=active]:scale-110"
                  />
                  {item.badge ? (
                    <span className="absolute -right-2 -top-1 grid h-4 min-w-4 place-items-center rounded-full bg-emerald-500 px-1 text-[9px] font-bold text-white shadow-xs ring-2 ring-background">
                      {item.badge}
                    </span>
                  ) : null}
                </span>
                <span className="text-xs font-extrabold tracking-tight mt-1 transition-all">
                  {item.label}
                </span>
              </Link>
            );
          })}
        </div>
      </nav>

      {/* Full-Screen God-Level Animated Onboarding Page */}
      <OnboardingScreen />
    </div>
  );
}
