import { redirect } from "next/navigation";
import { ExternalLink, Package, Plus, ShoppingBag } from "lucide-react";
import { getDashboardUser } from "@/lib/view-as";
import { getProductSales, getShopByOrganizer, listProducts } from "@db/queries/merch";
import { formatPrice } from "@/lib/format";
import { PageHeader, LinkButton, EmptyState, StatusPill, TableShell, Card } from "@/components/ui";
import ShopForm from "./shop-form";
import ShopOpenToggle from "./shop-open-toggle";

export const metadata = { title: "Merch · Dashboard" };

export default async function MerchPage() {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const shop = await getShopByOrganizer(user.id);

  if (!shop) {
    return (
      <div className="space-y-6">
        <PageHeader
          icon={ShoppingBag}
          title="Merch shop"
          description="Sell T-shirts, caps and more to promote your events. Set up your shop to get started."
        />
        <Card className="max-w-xl">
          <ShopForm
            isNew
            initial={{
              slug: "",
              name: "",
              description: "",
              bannerUrl: "",
              pickupInstructions: "",
              pickupEnabled: true,
              deliveryEnabled: false,
              deliveryFeeKes: "0",
              open: true,
            }}
          />
        </Card>
      </div>
    );
  }

  const [products, sales] = await Promise.all([listProducts(shop.id), getProductSales(shop.id)]);
  const totalRevenue = [...sales.values()].reduce((s, x) => s + x.revenueCents, 0);
  const totalUnits = [...sales.values()].reduce((s, x) => s + x.units, 0);

  return (
    <div className="space-y-6">
      <PageHeader
        icon={ShoppingBag}
        title={shop.name}
        description={shop.open ? "Your shop is open to buyers." : "Your shop is closed — buyers can't see it yet."}
        actions={
          <>
            <LinkButton href="/dashboard/merch/orders" variant="secondary" icon={Package}>
              Orders
            </LinkButton>
            <LinkButton href={`/shop/${shop.slug}`} variant="secondary" icon={ExternalLink}>
              View shop
            </LinkButton>
            <LinkButton href="/dashboard/merch/products/new" icon={Plus}>
              New product
            </LinkButton>
          </>
        }
      />

      <ShopOpenToggle open={shop.open} liveProducts={products.filter((p) => p.active).length} slug={shop.slug} />

      {totalUnits > 0 && (
        <p className="text-sm text-be-muted">
          Sold so far: <span className="font-semibold text-be-text">{totalUnits} item{totalUnits === 1 ? "" : "s"}</span> ·{" "}
          <span className="font-semibold text-be-text">{formatPrice(totalRevenue, "kes")}</span> (paid orders, before
          coupons and delivery). Open a product for its sales by day and by size.
        </p>
      )}

      {products.length === 0 ? (
        <EmptyState
          icon={ShoppingBag}
          title="No products yet"
          body="Add your first item — give it a photo, a price and the sizes or colours you have in stock."
          action={
            <LinkButton href="/dashboard/merch/products/new" icon={Plus}>
              New product
            </LinkButton>
          }
        />
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Product</th>
              <th>Price</th>
              <th className="text-right">In stock</th>
              <th className="text-right">Sold</th>
              <th className="text-right">Revenue</th>
              <th>Status</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {products.map((p) => {
              const stock = p.variants.reduce((s, v) => s + v.stock, 0);
              const sold = p.variants.reduce((s, v) => s + v.sold, 0);
              return (
                <tr key={p.id}>
                  <td className="font-medium text-be-text">
                    {p.name}
                    <span className="ml-2 text-xs font-normal text-be-muted">
                      {p.variants.length} option{p.variants.length === 1 ? "" : "s"}
                    </span>
                  </td>
                  <td className="text-be-text">{formatPrice(p.priceCents, "kes")}</td>
                  <td className="text-right tabular-nums text-be-text">{stock}</td>
                  <td className="text-right tabular-nums text-be-muted">{sold}</td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(sales.get(p.id)?.revenueCents ?? 0, "kes")}
                  </td>
                  <td>
                    {!p.active ? (
                      <StatusPill tone="muted">Hidden</StatusPill>
                    ) : stock === 0 ? (
                      <StatusPill tone="warn">Sold out</StatusPill>
                    ) : (
                      <StatusPill tone="ok">Live</StatusPill>
                    )}
                  </td>
                  <td className="text-right">
                    <LinkButton href={`/dashboard/merch/products/${p.id}`} variant="ghost">
                      Edit
                    </LinkButton>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </TableShell>
      )}

      <Card className="max-w-xl">
        <h2 className="mb-4 text-lg font-semibold text-be-text">Shop settings</h2>
        <ShopForm
          isNew={false}
          initial={{
            slug: shop.slug,
            name: shop.name,
            description: shop.description ?? "",
            bannerUrl: shop.bannerUrl ?? "",
            pickupInstructions: shop.pickupInstructions ?? "",
            pickupEnabled: shop.pickupEnabled,
            deliveryEnabled: shop.deliveryEnabled,
            deliveryFeeKes: String(shop.deliveryFeeCents / 100),
            open: shop.open,
          }}
        />
      </Card>
    </div>
  );
}
