import { authenticate } from "../shopify.server";
import { useLoaderData } from "react-router";
import { Page, Layout, Card, BlockStack } from "@shopify/polaris";

import { DashboardMetrics } from "../components/DashboardMetrics";
import { ReviewList } from "../components/ReviewList";
import { TechStackCard } from "../components/TechStackCard";
import { StorefrontSetupCard } from "../components/StorefrontSetupCard";

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

  // Fetch some reviews to show in the admin dashboard
  const response = await admin.graphql(`#graphql
    query {
      metaobjects(first: 50, 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 (
    <Page title="Product Reviews Dashboard">
      <Layout>
        <Layout.Section>
          <BlockStack gap="400">
            <DashboardMetrics reviews={reviews} />
            <Card padding="0">
              <ReviewList reviews={reviews} />
            </Card>
          </BlockStack>
        </Layout.Section>
        
        <Layout.Section variant="oneThird">
          <BlockStack gap="500">
            <TechStackCard />
            <StorefrontSetupCard />
          </BlockStack>
        </Layout.Section>
      </Layout>
    </Page>
  );
}
