import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, useSubmit, useNavigation, useActionData } from "react-router";
import { authenticate } from "../shopify.server";
import { ALL_PLANS, PLAN_STARTER, PLAN_ADVANCED, PLAN_PLUS } from "../plans";
import { Page, BlockStack, Text, InlineGrid, Badge, Button, Divider, Banner } from "@shopify/polaris";

// ── Plan metadata ─────────────────────────────────────────────────────────────

const PLANS = [
  {
    key:         PLAN_STARTER,
    name:        "Starter Plan",
    price:       19.99,
    badge:       null,
    description: "Perfect for small stores getting started with flash deals.",
    features: [
      "Unlimited deal slots",
      "Hourly deal scheduling",
      "Storefront countdown widget",
      "Basic analytics",
      "Email support",
    ],
  },
  {
    key:         PLAN_ADVANCED,
    name:        "Advanced Plan",
    price:       29.99,
    badge:       "Most Popular",
    description: "For growing stores that want more control and insights.",
    features: [
      "Everything in Starter",
      "Date-specific deals",
      "Promotion quantity caps",
      "Advanced analytics & CSV export",
      "Priority support",
    ],
  },
  {
    key:         PLAN_PLUS,
    name:        "Shopify Plus Plan",
    price:       39.99,
    badge:       null,
    description: "Built for high-volume Shopify Plus merchants.",
    features: [
      "Everything in Advanced",
      "Multi-location support",
      "Dedicated onboarding",
      "SLA-backed uptime",
      "Phone & chat support",
    ],
  },
];

// ── Loader ────────────────────────────────────────────────────────────────────

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { billing } = await authenticate.admin(request);

  try {
    const { hasActivePayment, appSubscriptions } = await billing.check({
      plans: [...ALL_PLANS],
      isTest: true, // ← set to false in production
    });
    const activePlan = appSubscriptions?.[0]?.name ?? null;
    return { hasActivePayment, activePlan };
  } catch {
    return { hasActivePayment: false, activePlan: null };
  }
};

// ── Action — merchant picks a plan ───────────────────────────────────────────

export const action = async ({ request }: ActionFunctionArgs) => {
  const { billing } = await authenticate.admin(request);
  const formData = await request.formData();
  const plan = String(formData.get("plan"));

  if (!(ALL_PLANS as readonly string[]).includes(plan)) {
    return { error: "Invalid plan selected." };
  }

  // Use the actual request origin so the returnUrl always matches the live domain
  const origin = new URL(request.url).origin;

  try {
    return await billing.request({
      plan,
      isTest: true, // ← set to false in production
      trialDays: 14,
      returnUrl: `${origin}/app`,
    });
  } catch (e: any) {
    const detail = e?.message ?? e?.toString() ?? JSON.stringify(e);
    console.error("[billing] request failed:", detail, e);
    return { error: `Could not start billing: ${detail}` };
  }
};

// ── UI ────────────────────────────────────────────────────────────────────────

export default function BillingPage() {
  const { activePlan }   = useLoaderData<typeof loader>();
  const actionData       = useActionData<typeof action>() as any;
  const submit           = useSubmit();
  const nav              = useNavigation();
  const loading          = nav.state === "submitting";
  const selecting        = nav.formData?.get("plan") as string | undefined;

  const handleSelect = (planKey: string) => {
    const fd = new FormData();
    fd.append("plan", planKey);
    submit(fd, { method: "post" });
  };

  return (
    <Page
      title="Choose your plan"
      subtitle="All plans include a 14-day free trial. No credit card charged until the trial ends."
    >
      <BlockStack gap="500">

        {/* Error from action */}
        {actionData?.error && (
          <Banner tone="critical" title="Something went wrong">
            <p>{actionData.error}</p>
          </Banner>
        )}

        {/* Currently active plan notice */}
        {activePlan && (
          <Banner tone="success">
            <p>You are currently on the <strong>{activePlan}</strong>. Selecting a new plan will replace it.</p>
          </Banner>
        )}

        <InlineGrid columns={{ xs: 1, sm: 1, md: 3 }} gap="400">
          {PLANS.map((plan) => {
            const isActive  = activePlan === plan.key;
            const isLoading = loading && selecting === plan.key;

            return (
              <div
                key={plan.key}
                style={{
                  position:      "relative",
                  borderRadius:  12,
                  border:        isActive ? "2px solid #008060" : "1px solid #e1e3e5",
                  background:    "#fff",
                  display:       "flex",
                  flexDirection: "column",
                  overflow:      "hidden",
                }}
              >
                {/* Most Popular badge — visual only, not a selection indicator */}
                {plan.badge && (
                  <div style={{
                    background:    "#f1faf7",
                    color:         "#008060",
                    fontSize:      11,
                    fontWeight:    700,
                    textAlign:     "center",
                    padding:       "5px 0",
                    letterSpacing: "0.06em",
                    borderBottom:  "1px solid #b5e3d0",
                  }}>
                    ★ {plan.badge.toUpperCase()}
                  </div>
                )}

                <div style={{ padding: "24px 24px 20px", flex: 1 }}>
                  {/* Name + active badge */}
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                    <Text as="h2" variant="headingMd">{plan.name}</Text>
                    {isActive && <Badge tone="success">Current plan</Badge>}
                  </div>

                  {/* Price */}
                  <div style={{ marginBottom: 12 }}>
                    <span style={{ fontSize: 32, fontWeight: 700, color: "#202223" }}>
                      ${plan.price.toFixed(2)}
                    </span>
                    <span style={{ fontSize: 14, color: "#6d7175" }}> / month</span>
                  </div>

                  <Text as="p" variant="bodySm" tone="subdued">{plan.description}</Text>

                  <div style={{ margin: "20px 0" }}>
                    <Divider />
                  </div>

                  {/* Features */}
                  <BlockStack gap="150">
                    {plan.features.map((f) => (
                      <div key={f} style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 13 }}>
                        <span style={{ color: "#008060", fontWeight: 700, flexShrink: 0, marginTop: 1 }}>✓</span>
                        <span style={{ color: "#3d4045" }}>{f}</span>
                      </div>
                    ))}
                  </BlockStack>
                </div>

                {/* CTA */}
                <div style={{ padding: "0 24px 24px" }}>
                  <Button
                    variant="primary"
                    fullWidth
                    loading={isLoading}
                    disabled={loading && !isLoading}
                    onClick={() => handleSelect(plan.key)}
                  >
                    {isActive ? "Switch to this plan" : "Start 14-day free trial"}
                  </Button>
                </div>
              </div>
            );
          })}
        </InlineGrid>

        <div style={{ textAlign: "center", fontSize: 13, color: "#6d7175", paddingBottom: 8 }}>
          You can cancel or switch plans at any time from your Shopify billing settings.
        </div>

      </BlockStack>
    </Page>
  );
}
