import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { Plus, Pencil, Trash2, Star, ExternalLink } from "lucide-react";

export const dynamic = "force-dynamic";

export default async function AdminProductsPage() {
  const session = await getSession();
  if (!session.isLoggedIn) redirect("/admin/login");
  const products = await prisma.product.findMany({ orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }] });

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">محصولات</h1>
          <p className="text-sm text-text-secondary mt-1">{products.length} محصول</p>
        </div>
        <a href="/admin/products/new" className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-background hover:bg-accent-hover transition-colors">
          <Plus size={16} /> محصول جدید
        </a>
      </div>

      {products.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-20 text-center">
          <p className="text-text-secondary">هنوز محصولی ندارید</p>
          <a href="/admin/products/new" className="mt-4 text-sm text-accent">اولین محصول را اضافه کنید →</a>
        </div>
      ) : (
        <div className="rounded-xl border border-border bg-surface overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-surface-hover text-right">
                <th className="px-4 py-3 font-medium text-text-secondary">عنوان</th>
                <th className="hidden px-4 py-3 font-medium text-text-secondary md:table-cell">نوع</th>
                <th className="hidden px-4 py-3 font-medium text-text-secondary md:table-cell">قیمت</th>
                <th className="px-4 py-3 font-medium text-text-secondary">عملیات</th>
              </tr>
            </thead>
            <tbody>
              {products.map((p) => (
                <tr key={p.id} className="border-b border-border/50 hover:bg-surface-hover transition-colors">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      {p.featured && <Star size={12} className="text-accent shrink-0" />}
                      <span className="font-medium text-text-primary">{p.title}</span>
                    </div>
                  </td>
                  <td className="hidden px-4 py-3 md:table-cell">
                    <span className="font-mono text-xs text-text-secondary">{p.productType}</span>
                  </td>
                  <td className="hidden px-4 py-3 md:table-cell">
                    <span className="font-mono text-xs text-accent">
                      {p.price !== null && p.price !== undefined ? (p.price === 0 ? "رایگان" : `${p.price} ${p.currency}`) : "—"}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <a href={`/admin/products/${p.id}`} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-accent/40 hover:text-accent transition-colors">
                        <Pencil size={14} />
                      </a>
                      {p.purchaseUrl && (
                        <a href={p.purchaseUrl} target="_blank" rel="noopener noreferrer" className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-accent/40 hover:text-accent transition-colors">
                          <ExternalLink size={14} />
                        </a>
                      )}
                      <button type="button" onClick={async () => { if (!confirm("حذف شود؟")) return; await fetch(`/api/admin/products/${p.id}`, { method: "DELETE" }); window.location.reload(); }} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-danger/40 hover:text-danger transition-colors">
                        <Trash2 size={14} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
