import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from "react-router";
import { Form, Link, useActionData, useLoaderData } from "react-router";
import { boundary } from "@shopify/shopify-app-react-router/server";
import { authenticate } from "../shopify.server";
import db from "../db.server";
import { moneyInr } from "../utils";
import { registerDeliveryOrder } from "../order.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { session } = await authenticate.admin(request);
  const url = new URL(request.url);
  const status = url.searchParams.get("status") || "ALL";
  const orders = await db.deliveryOrder.findMany({
    where: { shop: session.shop, ...(status !== "ALL" ? { status } : {}) },
    orderBy: { createdAt: "desc" },
    take: 200,
  });
  return { orders, status };
};

export const action = async ({ request }: ActionFunctionArgs) => {
  const { admin, session } = await authenticate.admin(request);
  const form = await request.formData();
  const intent = String(form.get("intent") || "");
  if (intent === "sync") {
    const response = await admin.graphql(`#graphql
      query DeliveryOrdersSync {
        orders(first: 250, sortKey: CREATED_AT, reverse: true) {
          nodes {
            id legacyResourceId name email createdAt currencyCode totalPriceSet { shopMoney { amount currencyCode } }
            shippingAddress { zip city province countryCode }
            customer { firstName lastName email }
            shippingLines(first: 10) { nodes { title discountedPriceSet { shopMoney { amount currencyCode } } } }
          }
        }
      }
    `);
    const data = await response.json();
    let processed = 0;
    for (const order of data?.data?.orders?.nodes || []) {
      const normalized = {
        id: Number(order.legacyResourceId),
        admin_graphql_api_id: order.id,
        name: order.name,
        email: order.email,
        created_at: order.createdAt,
        currency: order.currencyCode,
        total_price: order.totalPriceSet?.shopMoney?.amount,
        shipping_address: order.shippingAddress ? { zip: order.shippingAddress.zip, city: order.shippingAddress.city, province: order.shippingAddress.province, country: order.shippingAddress.countryCode } : null,
        customer: order.customer ? { first_name: order.customer.firstName, last_name: order.customer.lastName, email: order.customer.email } : null,
        shipping_lines: order.shippingLines?.nodes?.map((line: any) => ({ title: line.title, price: line.discountedPriceSet?.shopMoney?.amount })) || [],
      };
      const item = await registerDeliveryOrder(session.shop, normalized, session.accessToken);
      if (item) processed++;
    }
    return { ok: true, message: `Sync complete. ${processed} applicable delivery orders processed.` };
  }
  return { ok: false, message: "Unknown action." };
};

export default function Orders() {
  const { orders, status } = useLoaderData<typeof loader>();
  const action = useActionData<typeof action>();
  return (
    <div className="sb-page">
      <div className="sb-toolbar">
        <div><s-heading>Delivery Orders</s-heading><p className="sb-muted">Orders using the SweetBengal handover-charge shipping method. The manual sync imports the latest 250 Shopify orders; future orders are captured by webhook.</p></div>
        <Form method="post"><input type="hidden" name="intent" value="sync" /><s-button type="submit">Sync latest Shopify orders</s-button></Form>
      </div>
      {action?.message ? <s-banner tone={action.ok ? "success" : "critical"}>{action.message}</s-banner> : null}
      <div className="sb-row" style={{marginBottom: 14}}>
        {[
          ["ALL", "All"], ["PENDING", "Pending"], ["COLLECTED", "Collected"], ["WAIVED", "Waived"],
        ].map(([value, label]) => <s-button key={value} href={`/app/orders?status=${value}`} variant={status === value ? "primary" : "tertiary"}>{label}</s-button>)}
      </div>
      <div className="sb-card" style={{padding: 0, overflow: "hidden"}}>
        {orders.length === 0 ? <div style={{padding: 24}}><p className="sb-muted">No delivery-charge orders have been captured yet.</p></div> : (
          <table className="sb-table"><thead><tr><th>Order</th><th>Customer</th><th>PIN</th><th>Charge</th><th>Status</th><th>Created</th></tr></thead><tbody>
            {orders.map((order) => <tr key={order.id}><td><Link to={`/app/orders/${order.id}`}>{order.orderName}</Link></td><td>{order.customerName || "—"}</td><td>{order.pincode || "—"}</td><td>{moneyInr(order.chargePaise)}</td><td><span className={`sb-badge sb-badge-${order.status.toLowerCase()}`}>{order.status}</span></td><td>{new Date(order.createdAt).toLocaleString("en-IN")}</td></tr>)}
          </tbody></table>
        )}
      </div>
    </div>
  );
}

export const headers: HeadersFunction = (headersArgs) => boundary.headers(headersArgs);
