import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import {
  Outlet, Link, createRootRouteWithContext, useRouter,
  HeadContent, Scripts, useRouterState,
} from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { BrandSplash } from "@/components/AppLogo";
import { Toaster } from "@/components/ui/sonner";
import { supabase } from "@/integrations/supabase/client";
import { useAuthStore } from "@/stores/auth";
import appCss from "../styles.css?url";
import { ThemeProvider } from "@/components/ThemeProvider";
import { ThemePalette } from "@/components/ThemePalette";
import { registerPwa } from "@/lib/pwa";

function NotFoundComponent() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="text-7xl font-bold text-primary">404</h1>
        <h2 className="mt-4 text-xl font-semibold">Page not found</h2>
        <p className="mt-2 text-sm text-muted-foreground">This page doesn't exist.</p>
        <Link to="/" className="mt-6 inline-flex rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground">Go home</Link>
      </div>
    </div>
  );
}

function ErrorComponent({ error, reset }: { error: Error; reset: () => void }) {
  const router = useRouter();
  console.error(error);
  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="text-xl font-semibold">Something went wrong</h1>
        <p className="mt-2 text-sm text-muted-foreground">{error.message}</p>
        <button onClick={() => { router.invalidate(); reset(); }}
          className="mt-6 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground">
          Try again
        </button>
      </div>
    </div>
  );
}

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  head: () => ({
    meta: [
      { charSet: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1, viewport-fit=cover" },
      { name: "theme-color", content: "#0A2540" },
      { title: "Billsline — Pay Bills, Buy Airtime & Data Instantly" },
      { name: "description", content: "Billsline is Nigeria's fastest bill payment platform. Buy airtime, data, cable TV, electricity, and transfer money instantly." },
      { property: "og:title", content: "Billsline — Pay Bills, Buy Airtime & Data Instantly" },
      { property: "og:description", content: "Billsline is Nigeria's fastest bill payment platform. Buy airtime, data, cable TV, electricity, and transfer money instantly." },
      { property: "og:type", content: "website" },
      { name: "twitter:title", content: "Billsline — Pay Bills, Buy Airtime & Data Instantly" },
      { name: "twitter:description", content: "Billsline is Nigeria's fastest bill payment platform. Buy airtime, data, cable TV, electricity, and transfer money instantly." },
      { property: "og:image", content: "https://storage.googleapis.com/gpt-engineer-file-uploads/attachments/og-images/362e3d56-617c-4f9d-82a7-9a392e2bcda9" },
      { name: "twitter:image", content: "https://storage.googleapis.com/gpt-engineer-file-uploads/attachments/og-images/362e3d56-617c-4f9d-82a7-9a392e2bcda9" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    links: [
      { rel: "stylesheet", href: appCss },
      { rel: "manifest", href: "/manifest.webmanifest" },
      { rel: "icon", type: "image/png", href: "/favicon.png" },
      { rel: "apple-touch-icon", href: "/apple-touch-icon.png" },
    ],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Organization",
          name: "Billsline",
          url: "https://billslinepay.lovable.app",
          logo: "https://billslinepay.lovable.app/favicon.ico",
          description: "Nigeria's fast bill-payment platform for airtime, data, cable TV, electricity, and money transfers.",
        }),
      },
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "WebSite",
          name: "Billsline",
          url: "https://billslinepay.lovable.app",
        }),
      },
    ],
  }),
  shellComponent: RootShell,
  component: RootComponent,
  notFoundComponent: NotFoundComponent,
  errorComponent: ErrorComponent,
});

function RootShell({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head><HeadContent /></head>
      <body suppressHydrationWarning>{children}<Scripts /></body>
    </html>
  );
}

function AuthSync() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const setSession = useAuthStore((s) => s.setSession);
  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => setSession(data.session));
    const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => {
      setSession(session);
      if (event !== "SIGNED_IN" && event !== "SIGNED_OUT" && event !== "USER_UPDATED") return;

      router.invalidate();
      if (event === "SIGNED_OUT") {
        void queryClient.cancelQueries().finally(() => queryClient.clear());
        return;
      }
      void queryClient.invalidateQueries();
    });
    return () => subscription.unsubscribe();
  }, [router, queryClient, setSession]);
  return null;
}

function RouteTransitionLoader() {
  const isLoading = useRouterState({ select: (s) => s.status === "pending" || s.isLoading || s.isTransitioning });
  const [show, setShow] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (isLoading) {
      if (timer.current) clearTimeout(timer.current);
      timer.current = setTimeout(() => setShow(true), 120);
    } else {
      if (timer.current) clearTimeout(timer.current);
      setShow(false);
    }
    return () => { if (timer.current) clearTimeout(timer.current); };
  }, [isLoading]);
  if (!show) return null;
  return <BrandSplash label="Loading" />;
}

function RootComponent() {
  const { queryClient } = Route.useRouteContext();
  useEffect(() => {
    registerPwa();
  }, []);
  return (
    <ThemeProvider>
      <QueryClientProvider client={queryClient}>
        <ThemePalette />
        <AuthSync />
        <RouteTransitionLoader />
        <Outlet />
        <Toaster richColors position="top-center" />
      </QueryClientProvider>
    </ThemeProvider>
  );
}
