import { useLoaderData } from "react-router";
import { Page, Card, IndexTable, Text, Badge, InlineStack } from "@shopify/polaris";
import { authenticate } from "../shopify.server";

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

  const query = `
    query Orders($first: Int!) {
      orders(first: $first, sortKey: CREATED_AT, reverse: true) {
        edges {
          node {
            id
            name
            createdAt
            displayFinancialStatus
            displayFulfillmentStatus
            totalPriceSet { shopMoney { amount currencyCode } }
            customer { firstName lastName email }
          }
        }
      }
    }
  `;

  const resp = await admin.graphql(query, { variables: { first: 25 } });
  const data = await resp.json();
  const orders = (data?.data?.orders?.edges || []).map((e) => e.node);

  return { orders };
};

export default function OrdersPage() {
  const { orders } = useLoaderData();

  return (
    <Page title="Pedidos">
      <Card padding="0">
        <IndexTable
          resourceName={{ singular: "pedido", plural: "pedidos" }}
          itemCount={orders.length}
          selectable={false}
          headings={[
            { title: "Pedido" },
            { title: "Cliente" },
            { title: "Total" },
            { title: "Pago" },
            { title: "Despacho" },
            { title: "Fecha" },
          ]}
        >
          {orders.map((o, index) => {
            const money = o.totalPriceSet?.shopMoney;
            const total = money ? `${money.amount} ${money.currencyCode}` : "—";
            const customerName = o.customer
              ? `${o.customer.firstName || ""} ${o.customer.lastName || ""}`.trim()
              : "—";

            return (
              <IndexTable.Row id={o.id} key={o.id} position={index}>
                <IndexTable.Cell>
                  <Text as="span" fontWeight="semibold">{o.name}</Text>
                </IndexTable.Cell>

                <IndexTable.Cell>
                  <InlineStack gap="200" wrap={false}>
                    <Text as="span">{customerName || "—"}</Text>
                    <Text as="span" tone="subdued">{o.customer?.email || ""}</Text>
                  </InlineStack>
                </IndexTable.Cell>

                <IndexTable.Cell>{total}</IndexTable.Cell>
                <IndexTable.Cell><Badge>{o.displayFinancialStatus || "—"}</Badge></IndexTable.Cell>
                <IndexTable.Cell><Badge>{o.displayFulfillmentStatus || "—"}</Badge></IndexTable.Cell>
                <IndexTable.Cell>{o.createdAt ? new Date(o.createdAt).toLocaleString() : "—"}</IndexTable.Cell>
              </IndexTable.Row>
            );
          })}
        </IndexTable>
      </Card>
    </Page>
  );
}
