import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useNavigate } from "react-router";
import {
  Page,
  Card,
  Text,
  BlockStack,
  InlineGrid,
  Button,
  Badge,
  Banner,
  Box,
  Divider,
} from "@shopify/polaris";
import { authenticate } from "../shopify.server";

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


function themeEditorUrl(shop: string, template: string) {
  return `https://${shop}/admin/themes/current/editor?template=${template}`;
}

type Placement = {
  id: string;
  icon: string;
  title: string;
  badge?: string;
  badgeTone?: "success" | "attention" | "info";
  description: string;
  steps: string[];
  recommended?: boolean;
  getUrl: (shop: string) => string;
  buttonLabel: string;
};

const PLACEMENTS: Placement[] = [
  {
    id: "homepage",
    icon: "🏠",
    title: "Homepage",
    badge: "Most popular",
    badgeTone: "success",
    recommended: true,
    description: "Show the deal widget prominently on your store front page. Maximum visibility for all visitors.",
    steps: [
      "Click the button below to open the Theme Editor",
      "Click '+ Add section' in the left sidebar",
      "Search for 'Deal of the Hour' and select it",
      "Position the section where you want it on the page",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "index"),
    buttonLabel: "Open Theme Editor — Homepage",
  },
  {
    id: "product",
    icon: "🛍️",
    title: "Product Pages",
    badge: "High impact",
    badgeTone: "attention",
    description: "Place the widget on individual product pages. Customers browsing a product will see the active deal right where they buy.",
    steps: [
      "Click the button below to open the Theme Editor",
      "In the left sidebar choose 'Product pages'",
      "Click '+ Add block' inside the product section",
      "Select 'Deal of the Hour'",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "product"),
    buttonLabel: "Open Theme Editor — Product Pages",
  },
  {
    id: "collection",
    icon: "📦",
    title: "Collection Pages",
    badge: "Good for browsing",
    badgeTone: "info",
    description: "Add the widget to collection / category pages so shoppers see the deal while browsing your product range.",
    steps: [
      "Click the button below to open the Theme Editor",
      "In the left sidebar choose 'Collection pages'",
      "Click '+ Add section' and select 'Deal of the Hour'",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "collection"),
    buttonLabel: "Open Theme Editor — Collection Pages",
  },
  {
    id: "cart",
    icon: "🛒",
    title: "Cart Page",
    badge: "Last-minute upsell",
    badgeTone: "attention",
    description: "Show the deal in the cart — a last-chance nudge just before checkout to boost conversions.",
    steps: [
      "Click the button below to open the Theme Editor",
      "Choose 'Cart' in the left sidebar",
      "Click '+ Add block' and select 'Deal of the Hour'",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "cart"),
    buttonLabel: "Open Theme Editor — Cart Page",
  },
  {
    id: "dedicated",
    icon: "📄",
    title: "Dedicated Deal Page",
    description: "Your app already has a live deal page at /apps/deal-of-the-hour/current-deal. Link it from your navigation menu so customers can find it directly.",
    steps: [
      "Copy your live deal page URL from the box above",
      "Click the button below to open the Navigation editor",
      "Open your menu (e.g. Main menu)",
      "Click 'Add menu item', paste the URL and label it e.g. Hot Deals",
      "Click Save",
    ],
    getUrl: (shop) => `https://${shop}/admin/menus`,
    buttonLabel: "Open Navigation Menu Editor",
  },
  {
    id: "page",
    icon: "📝",
    title: "Custom Store Page",
    description: "Create a standard Shopify page (e.g. /pages/deals) and embed the widget there. Great for a permanent deals landing page.",
    steps: [
      "Click the button below to open the Theme Editor",
      "Choose 'Pages' in the template selector",
      "Add the 'Deal of the Hour' section to the page template",
      "Then go to Online Store > Pages to create the actual page",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "page"),
    buttonLabel: "Open Theme Editor — Pages",
  },
  {
    id: "announcement",
    icon: "📢",
    title: "Announcement Bar",
    description: "If your theme has an announcement bar at the top, link it to your deal page so the promo is visible on every page of your store.",
    steps: [
      "Click the button below to open the Theme Editor",
      "Click the announcement bar section in the preview",
      "Set the bar text and link it to /apps/deal-of-the-hour/current-deal",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "index"),
    buttonLabel: "Open Theme Editor — Announcement Bar",
  },
  {
    id: "blog",
    icon: "✍️",
    title: "Blog / Article Pages",
    description: "Running a blog? Add the deal widget to your article template to cross-sell while customers read your content.",
    steps: [
      "Click the button below to open the Theme Editor",
      "Switch template to 'Article'",
      "Click '+ Add section' and select 'Deal of the Hour'",
      "Click Save",
    ],
    getUrl: (shop) => themeEditorUrl(shop, "article"),
    buttonLabel: "Open Theme Editor — Article Pages",
  },
];

export default function PlacementGuide() {
  const { shop } = useLoaderData<typeof loader>();
  const navigate = useNavigate();
  const dealPageUrl = `https://${shop}/apps/deal-of-the-hour`;

  return (
    <Page
      title="Widget Placement"
      subtitle="Choose where to show your Deal of the Hour on your storefront"
      backAction={{ content: "Dashboard", onAction: () => navigate("/app") }}
    >
      <BlockStack gap="600">

        <Banner tone="info">
          <p>
            The Deal of the Hour widget is a <strong>Shopify Theme App Extension</strong> — no code needed.
            Each button below opens the Shopify Theme Editor pre-loaded at the right template so you can
            add it in under a minute.
          </p>
        </Banner>

        {/* Live deal page URL */}
        <Card>
          <BlockStack gap="300">
            <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
              <Text as="h2" variant="headingMd">Your live deal page URL</Text>
              <Badge tone="success">Already live — no setup needed</Badge>
            </div>
            <Text as="p" variant="bodySm">
              This page is <strong>automatically created by the app</strong> the moment it is installed — you do not need to create anything.
              It always shows the current active deal and updates in real time.
            </Text>
            <div style={{
              background: "#f6f6f7",
              border: "1px solid #e1e3e5",
              borderRadius: 8,
              padding: "10px 16px",
              fontFamily: "monospace",
              fontSize: 13,
              color: "#202223",
              wordBreak: "break-all",
              userSelect: "all",
            }}>
              {dealPageUrl}
            </div>
            <Text as="p" variant="bodySm" tone="subdued">
              Copy this URL and use it anywhere — navigation menus, announcement bars, email campaigns, ads, or social links.
            </Text>
            <Button
              variant="plain"
              url={dealPageUrl}
              external
            >
              Preview your deal page →
            </Button>
          </BlockStack>
        </Card>

        <Divider />

        <Text as="h2" variant="headingLg">All placement options</Text>

        <InlineGrid columns={{ xs: 1, sm: 2, md: 2 }} gap="400">
          {PLACEMENTS.map((p) => (
            <Card key={p.id}>
              <BlockStack gap="400">
                {/* Header */}
                <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                  <span style={{ fontSize: 26, lineHeight: 1 }}>{p.icon}</span>
                  <BlockStack gap="100">
                    <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                      <Text as="h3" variant="headingMd">{p.title}</Text>
                      {p.recommended && <Badge tone="success">Recommended</Badge>}
                      {p.badge && !p.recommended && (
                        <Badge tone={p.badgeTone ?? "info"}>{p.badge}</Badge>
                      )}
                    </div>
                    <Text as="p" variant="bodySm" tone="subdued">{p.description}</Text>
                  </BlockStack>
                </div>

                <Divider />

                {/* Steps */}
                <BlockStack gap="100">
                  <Text as="p" variant="bodyMd" fontWeight="semibold">How to add it:</Text>
                  <ol style={{ margin: "4px 0 0 0", paddingLeft: 18 }}>
                    {p.steps.map((step, i) => (
                      <li key={i} style={{ fontSize: 13, color: "#202223", marginBottom: 4, lineHeight: 1.5 }}>
                        {step}
                      </li>
                    ))}
                  </ol>
                </BlockStack>

                {/* CTA */}
                <Box paddingBlockStart="100">
                  <Button
                    variant={p.recommended ? "primary" : "secondary"}
                    url={p.getUrl(shop)}
                    external
                  >
                    {p.buttonLabel}
                  </Button>
                </Box>
              </BlockStack>
            </Card>
          ))}
        </InlineGrid>

        <Banner tone="success">
          <p>
            <strong>Tip:</strong> Start with the <strong>Homepage</strong> — it takes under a minute and gives
            your deal maximum visibility. You can always add more placements later.
          </p>
        </Banner>

      </BlockStack>
    </Page>
  );
}
