import { Outlet, useLoaderData, useRouteError, type LoaderFunctionArgs } from "react-router";
import { useEffect } from "react";
import { AppProvider, Text, Spinner } from "@shopify/polaris";
import polarisTranslations from "@shopify/polaris/locales/en.json";
import { registerShop, getShopWithDecryptedToken } from "../services/shop.server";
import { resolveShopDomainFromRequest } from "../lib/security/tenant-context";
import prisma from "../db.server";

export const headers = () => {
  return {
    "X-Frame-Options": "ALLOWALL",
    "Content-Security-Policy": "frame-ancestors https://admin.shopify.com https://*.myshopify.com;",
  };
};

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const shopDomain = resolveShopDomainFromRequest(request);
  const url = new URL(request.url);

  let hasValidToken = true;
  try {
    const shopRecord = await getShopWithDecryptedToken(shopDomain);
    const tok = shopRecord?.decryptedAccessToken || "";
    const isUninstalled = Boolean(shopRecord?.uninstalledAt);
    
    // Consider token valid if it exists, is not uninstalled, and is not an invalid placeholder
    if (shopRecord) {
      if (isUninstalled) {
        hasValidToken = false;
      } else if (!tok || tok === "shpss_sample_token") {
        hasValidToken = false;
      } else {
        hasValidToken = true;
      }
    } else {
      hasValidToken = true;
    }
  } catch {
    hasValidToken = true;
  }

  const currentPath = url.pathname + url.search;
  const authUrl = `/auth?shop=${encodeURIComponent(shopDomain)}&returnTo=${encodeURIComponent(currentPath)}`;

  try {
    const shop = await registerShop({
      shopifyDomain: shopDomain,
      accessToken: "shpss_sample_token",
      scopes: process.env.SCOPES || "read_products,read_content,read_orders,write_orders",
    });

    const settings = await prisma.chatbotSettings.findUnique({
      where: { shopId: shop.id },
    });

    return {
      apiKey: process.env.SHOPIFY_API_KEY || "",
      shop: shop.shopifyDomain,
      storeId: shop.id,
      botName: settings?.botName || "ShopPilot AI Assistant",
      hasValidToken,
      authUrl,
    };
  } catch (e) {
    return {
      apiKey: process.env.SHOPIFY_API_KEY || "",
      shop: shopDomain,
      storeId: "local_dev_store",
      botName: "ShopPilot AI Assistant",
      hasValidToken: true,
      authUrl,
    };
  }
};

export default function App() {
  const { apiKey, hasValidToken, authUrl, shop } = useLoaderData<typeof loader>();

  useEffect(() => {
    if (!hasValidToken && authUrl) {
      if (typeof window !== "undefined") {
        try {
          if ((window as any).shopify?.open) {
            (window as any).shopify.open(authUrl, "_top");
          } else if ((window as any).shopify?.redirectTo) {
            (window as any).shopify.redirectTo(authUrl);
          }
        } catch (e) {
          console.warn("[App Auth Redirect Notice]:", e);
        }
      }
    }
  }, [hasValidToken, authUrl]);

  if (!hasValidToken && authUrl) {
    return (
      <AppProvider i18n={polarisTranslations}>
        <meta name="shopify-api-key" content={apiKey} />
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            minHeight: "60vh",
            gap: "16px",
            textAlign: "center",
            fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
            padding: "40px 20px",
          }}
        >
          <Spinner size="large" />
          <Text variant="headingMd" as="h2">
            Connecting ShopPilot AI...
          </Text>
          <Text tone="subdued" as="p">
            Authorizing permissions for {shop}. If this page does not refresh automatically, please click below:
          </Text>
          <a
            href={authUrl}
            target="_top"
            style={{
              marginTop: "12px",
              display: "inline-block",
              padding: "10px 22px",
              backgroundColor: "#4f46e5",
              color: "#ffffff",
              borderRadius: "8px",
              textDecoration: "none",
              fontWeight: 600,
              fontSize: "14px",
            }}
          >
            Authorize Store Access &rarr;
          </a>
        </div>
      </AppProvider>
    );
  }

  return (
    <AppProvider i18n={polarisTranslations}>
      <meta name="shopify-api-key" content={apiKey} />
      <Outlet />
    </AppProvider>
  );
}

export function ErrorBoundary() {
  const error: any = useRouteError();
  console.error("[App Layout ErrorBoundary]:", error);
  const errorMessage = error?.message || error?.data?.message || "An unexpected error occurred in the application.";

  return (
    <AppProvider i18n={polarisTranslations}>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          minHeight: "60vh",
          gap: "16px",
          textAlign: "center",
          fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
          padding: "40px 20px",
        }}
      >
        <div
          style={{
            width: "52px",
            height: "52px",
            borderRadius: "50%",
            backgroundColor: "#fee2e2",
            color: "#dc2626",
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: "24px",
          }}
        >
          ⚠
        </div>
        <Text variant="headingLg" as="h2">
          ShopPilot AI Assistant
        </Text>
        <Text tone="subdued" as="p">
          {errorMessage}
        </Text>
        <div style={{ marginTop: "16px", display: "flex", gap: "12px", justifyContent: "center" }}>
          <button
            type="button"
            onClick={() => {
              if (typeof window !== "undefined") {
                window.location.reload();
              }
            }}
            style={{
              padding: "10px 20px",
              backgroundColor: "#4f46e5",
              color: "#ffffff",
              border: "none",
              borderRadius: "8px",
              cursor: "pointer",
              fontWeight: 600,
              fontSize: "14px",
            }}
          >
            Reload Application
          </button>
        </div>
      </div>
    </AppProvider>
  );
}
