// app/routes/test-add-sample-product.jsx

import { json } from "@remix-run/node";
import { useLoaderData, useActionData, Form } from "@remix-run/react";
import {
  Page,
  Layout,
  Card,
  Banner,
  Button,
  InlineError,
} from "@shopify/polaris";
import { authenticate } from "../shopify.server";

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

  // Fetch the first manual collection in the store
  const resp = await admin.graphql(`
    {
      collections(first: 1, query: "collection_type:manual") {
        nodes {
          id
          title
        }
      }
    }
  `);
  const result = await resp.json();
  const collection = result.data.collections.nodes[0] || null;

  return json({ collection });
};

export const action = async ({ request }) => {
  const formData = await request.formData();
  const collectionId = formData.get("collectionId");
  const { admin } = await authenticate.admin(request);

  // 1️⃣ Create a dummy product
  const createRes = await admin.graphql(
    `#graphql
      mutation CreateDummyProduct($product: ProductCreateInput!) {
        productCreate(product: $product) {
          product {
            id
            title
          }
          userErrors {
            field
            message
          }
        }
      }
    `,
    {
      variables: {
        product: {
          title: "Dummy Test Product",
          descriptionHtml: "<p>This is a dummy product for testing.</p>",
        },
      },
    }
  );
  const createJson = await createRes.json();
  const createErrors = createJson.data.productCreate.userErrors;
  if (createErrors.length) {
    return json(
      { errors: createErrors.map((e) => e.message) },
      { status: 400 }
    );
  }
  const newProduct = createJson.data.productCreate.product;

  // 2️⃣ Add the new product to the selected collection
  const addRes = await admin.graphql(
    `#graphql
      mutation AddToCollection($id: ID!, $productIds: [ID!]!) {
        collectionAddProducts(id: $id, productIds: $productIds) {
          collection {
            id
            title
          }
          userErrors {
            field
            message
          }
        }
      }
    `,
    {
      variables: {
        id: collectionId,
        productIds: [newProduct.id],
      },
    }
  );
  const addJson = await addRes.json();
  const addErrors = addJson.data.collectionAddProducts.userErrors;
  if (addErrors.length) {
    return json(
      { errors: addErrors.map((e) => e.message) },
      { status: 400 }
    );
  }
  const updatedCollection = addJson.data.collectionAddProducts.collection;

  return json({
    success: true,
    product: newProduct,
    collection: updatedCollection,
  });
};

export default function TestAddSampleProduct() {
  const { collection } = useLoaderData();
  const actionData = useActionData();

  return (
    <Page title="Test: Add Sample Product">
      <Layout>
        <Layout.Section>
          <Card sectioned title="Create & Add Dummy Product">
            {!collection && (
              <Banner title="No manual collections found" status="warning">
                <p>
                  Please create at least one manual (non-smart) collection in
                  your store first.
                </p>
              </Banner>
            )}

            {actionData?.success && (
              <Banner title="✅ Success!" status="success">
                <p>
                  Product “{actionData.product.title}” (
                  {actionData.product.id}) was created and added to “
                  {actionData.collection.title}” (
                  {actionData.collection.id}).
                </p>
              </Banner>
            )}

            {actionData?.errors && (
              <Banner title="🚨 Error" status="critical">
                <ul>
                  {actionData.errors.map((msg, i) => (
                    <li key={i}>
                      <InlineError message={msg} />
                    </li>
                  ))}
                </ul>
              </Banner>
            )}

            {collection && !actionData?.success && (
              <Form method="post">
                <input
                  type="hidden"
                  name="collectionId"
                  value={collection.id}
                />
                <Button submit primary>
                  Create Dummy Product in “{collection.title}”
                </Button>
              </Form>
            )}
          </Card>
        </Layout.Section>
      </Layout>
    </Page>
  );
}
