import { authenticate } from "../shopify.server";
import { useLoaderData } from "react-router";

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

  // Fetch some reviews to show in the admin dashboard
  const response = await admin.graphql(`#graphql
    query {
      metaobjects(first: 10, type: "custom_product_review") {
        edges {
          node {
            id
            fields { key value }
          }
        }
      }
    }
  `);
  const data = await response.json();
  const reviews = (data.data?.metaobjects?.edges || []).map(edge => {
    const fields = {};
    edge.node.fields.forEach(f => { fields[f.key] = f.value; });
    return { id: edge.node.id, ...fields };
  });

  return { reviews };
};

export default function Index() {
  const { reviews } = useLoaderData();

  return (
    <s-page heading="Product Reviews Dashboard">
      <s-section heading="Manage your reviews">
        <s-paragraph>
          All reviews are stored directly in Shopify Metaobjects. You can view, edit, or delete them here.
        </s-paragraph>

        {reviews.length === 0 ? (
          <s-paragraph>No reviews found yet. Try adding one from your store!</s-paragraph>
        ) : (
          <s-stack direction="block" gap="base">
            {reviews.map((r) => (
              <s-box padding="base" borderWidth="base" borderRadius="base" background="subdued" key={r.id}>
                <s-stack direction="block" gap="small">
                  <s-text style={{ fontWeight: 'bold' }}>{r.customer_name || 'Anonymous'}</s-text>
                  <s-text>{r.content}</s-text>
                  <s-text style={{ color: '#666', fontSize: '0.8em' }}>Product ID: {r.product_id}</s-text>
                </s-stack>
              </s-box>
            ))}
          </s-stack>
        )}
      </s-section>

      <s-section slot="aside" heading="Tech Stack">
        <s-paragraph>
          This app is 100% database-less.
        </s-paragraph>
        <s-unordered-list>
          <s-list-item>Storage: Shopify Metaobjects</s-list-item>
          <s-list-item>Auth: App Proxy & Admin API</s-list-item>
          <s-list-item>Framework: React Router</s-list-item>
        </s-unordered-list>
      </s-section>
    </s-page>
  );
}
