import type { LoaderFunctionArgs } from "react-router";
import prisma from "../db.server";
import { canUseFeature, PLAN_CONFIGS } from "../lib/billing-plans";
import { parseWidgetSettings } from "../services/widget-settings.server";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, DELETE",
  "Access-Control-Allow-Headers": "*, Content-Type, Authorization, X-Requested-With, Cache-Control, Pragma, Accept, Origin",
  "Access-Control-Max-Age": "86400",
  "Content-Type": "application/json",
  "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
  "Pragma": "no-cache",
  "Expires": "0",
};

export const loader = async ({ request }: LoaderFunctionArgs) => {
  if (request.method === "OPTIONS") {
    return new Response(null, { status: 204, headers: corsHeaders });
  }

  const url = new URL(request.url);
  let rawShop = url.searchParams.get("shop");

  if (!rawShop && request.method === "POST") {
    try {
      const cloned = request.clone();
      const body = await cloned.json().catch(() => ({}));
      rawShop = body?.shop;
    } catch (e) {}
  }

  const shop = (rawShop || "").toLowerCase().trim();

  let shopRecord = null;
  if (shop) {
    shopRecord = await prisma.shop.findUnique({
      where: { shopifyDomain: shop },
      include: {
        chatbotSettings: true,
        subscriptions: {
          where: { status: "ACTIVE" },
          orderBy: { createdAt: "desc" },
          take: 1,
        },
      },
    });
  }

  if (!shopRecord || shopRecord.uninstalledAt !== null) {

    return new Response(
      JSON.stringify({
        isEnabled: false,
        isUninstalled: true,
        error: "Chatbot is disabled because this store is currently uninstalled or inactive.",
      }),
      { status: 403, headers: corsHeaders }
    );
  }

  const settings = shopRecord?.chatbotSettings;
  const activeSub = shopRecord?.subscriptions?.[0];
  const planTier = (activeSub?.plan || "FREE") as string;
  const isFreePlan = planTier === "FREE";
  let dbPlan: any = null;
  try {
    const { getPlanByIdOrKey } = await import("../services/plan-config.server");
    dbPlan = await getPlanByIdOrKey(planTier);
  } catch (e) {}
  const planConfig = dbPlan || PLAN_CONFIGS[planTier as keyof typeof PLAN_CONFIGS] || PLAN_CONFIGS.FREE;

  const { widgetTexts } = parseWidgetSettings(settings);
  const isChatbotAdminDisabled = widgetTexts.adminDisabled === true;
  const isEnabled = isChatbotAdminDisabled ? false : (settings?.enabled ?? true);

  let helplines: any[] = [];
  try {
    const { getActiveHelplines } = await import("../services/helpline-config.server");
    helplines = await getActiveHelplines();
  } catch (e) {}

  const config = {
    botName: widgetTexts.botName || settings?.botName || "ShopPilot AI Assistant",
    headerSubtext: widgetTexts.headerSubtext,
    headerInputPlaceholder: widgetTexts.headerInputPlaceholder,
    startHeading: widgetTexts.startHeading,
    startSubheading: widgetTexts.startSubheading,
    starterPrompts: widgetTexts.starterPrompts,
    disclaimerText: widgetTexts.disclaimerText,
    disclaimerLinkText: widgetTexts.disclaimerLinkText,
    disclaimerUrl: widgetTexts.disclaimerUrl,
    chatInputPlaceholder: widgetTexts.chatInputPlaceholder,
    footerTermsText: widgetTexts.footerTermsText,
    supportMenuItemText: widgetTexts.supportMenuItemText,
    clearMenuItemText: widgetTexts.clearMenuItemText,

    primaryColor: settings?.primaryColor || "#4F46E5",
    secondaryColor: settings?.secondaryColor || "#4338CA",
    textColor: settings?.textColor || "#FFFFFF",
    botTextColor: settings?.botTextColor || "#1F2937",
    showPoweredBy: isFreePlan ? true : (settings?.showPoweredBy ?? true),
    showCartSummary: widgetTexts.showCartSummary !== false,
    planTier,
    planDisplayName: dbPlan?.displayName || planConfig.displayName,
    canUseProducts: canUseFeature(planTier, "shopify.products", dbPlan?.featureFlags),
    canUseCart: canUseFeature(planTier, "shopify.cart", dbPlan?.featureFlags),
    canUseCheckout: canUseFeature(planTier, "shopify.checkout", dbPlan?.featureFlags),
    canUseCustomerAuth: canUseFeature(planTier, "shopify.customer_auth", dbPlan?.featureFlags),
    customerAuthEnabled: canUseFeature(planTier, "shopify.customer_auth", dbPlan?.featureFlags) && (widgetTexts.customerAuthEnabled === true),
    canUseAI: canUseFeature(planTier, "openai", dbPlan?.featureFlags),
    welcomeMessage: settings?.welcomeMessage || "Hi! How can I help you find products, calculate shipping, or track orders today?",
    position: settings?.position || "bottom-right",
    isEnabled,
    adminDisabled: isChatbotAdminDisabled,
    storeContact: {
      email: widgetTexts.storeSupportEmail || `support@${shop}`,
      phone: widgetTexts.storeSupportPhone || "",
      hours: widgetTexts.storeSupportHours || "",
      address: widgetTexts.storeAddress || "",
      contactUrl: widgetTexts.storeContactUrl || "/pages/contact",
    },
    storeSupportEmail: widgetTexts.storeSupportEmail || `support@${shop}`,
    storeSupportPhone: widgetTexts.storeSupportPhone || "",
    storeSupportHours: widgetTexts.storeSupportHours || "",
    storeAddress: widgetTexts.storeAddress || "",
    storeContactUrl: widgetTexts.storeContactUrl || "/pages/contact",
    helplines,
  };

  return new Response(JSON.stringify(config), {
    headers: corsHeaders,
  });
};

export const action = async ({ request }: LoaderFunctionArgs) => {
  if (request.method === "OPTIONS") {
    return new Response(null, { status: 204, headers: corsHeaders });
  }
  return loader({ request } as LoaderFunctionArgs);
};
