import type { Metadata } from "next";
import Image from "next/image";
import { getTranslations } from "next-intl/server";
import { ExternalLink } from "lucide-react";
import { SectionHeader } from "@/components/shared/SectionHeader";
import { AnimatedSection } from "@/components/shared/AnimatedSection";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { getAllProducts } from "@/lib/db/products";
import type { Product } from "@prisma/client";

interface Props {
  params: Promise<{ locale: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: "shop" });
  return { title: t("title"), description: t("subtitle") };
}

export const dynamic = "force-dynamic";

export default async function ShopPage({ params }: Props) {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: "shop" });
  const isRtl = locale === "fa";

  const products = await getAllProducts(locale);

  function formatPrice(price: number | null, currency: string) {
    if (price === null || price === undefined) return null;
    if (price === 0) return isRtl ? t("free") : "Free";
    if (currency === "IRR") return new Intl.NumberFormat("fa-IR").format(price) + " تومان";
    return `$${price}`;
  }

  return (
    <div className="relative z-10 mx-auto max-w-6xl px-6 py-24 pt-32">
      <SectionHeader label="shop" />
      <AnimatedSection className="mb-12">
        <h1 className="text-4xl font-bold text-text-primary md:text-5xl">{t("title")}</h1>
        <p className="mt-4 max-w-2xl text-text-secondary">{t("subtitle")}</p>
      </AnimatedSection>

      {products.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 text-center">
          <p className="text-text-secondary">به زودی محصولات اضافه می‌شود.</p>
        </div>
      ) : (
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {products.map((product: Product, i) => {
            const priceStr = formatPrice(product.price, product.currency);

            return (
              <AnimatedSection key={product.id} delay={i * 0.07}>
                <div className="flex h-full flex-col overflow-hidden rounded-xl border border-border bg-surface transition-all hover:border-accent/20 hover:bg-surface-hover">
                  {/* Image */}
                  {product.coverImage ? (
                    <div className="relative h-44 overflow-hidden">
                      <Image src={product.coverImage} alt={product.title} fill className="object-cover" />
                    </div>
                  ) : (
                    <div className="flex h-44 items-center justify-center bg-surface-hover">
                      <span className="font-mono text-3xl text-accent opacity-20">//</span>
                    </div>
                  )}

                  <div className="flex flex-1 flex-col p-5">
                    <div className="mb-3 flex items-center gap-2">
                      <Badge variant={product.productType === "node-product" ? "default" : "secondary"}>
                        {product.productType === "node-product" ? t("node_product") : t("digital")}
                      </Badge>
                      {product.featured && <span className="font-mono text-xs text-accent">★</span>}
                    </div>

                    <h3 className="mb-2 font-semibold text-text-primary">{product.title}</h3>

                    {product.description && (
                      <p className="mb-4 flex-1 text-sm text-text-secondary leading-relaxed line-clamp-3">
                        {product.description}
                      </p>
                    )}

                    <div className="mt-auto flex items-center justify-between gap-3">
                      {priceStr && (
                        <span className="font-mono text-sm font-semibold text-accent">{priceStr}</span>
                      )}
                      {product.purchaseUrl ? (
                        <Button asChild size="sm" className="ms-auto">
                          <a href={product.purchaseUrl} target="_blank" rel="noopener noreferrer">
                            <ExternalLink size={13} />
                            {t("buy")}
                          </a>
                        </Button>
                      ) : (
                        <Button size="sm" className="ms-auto">{t("buy")}</Button>
                      )}
                    </div>
                  </div>
                </div>
              </AnimatedSection>
            );
          })}
        </div>
      )}
    </div>
  );
}
