import Link from "next/link";
import { Package, MapPin, User, ShoppingBag, ChevronRight, PawPrint } from "lucide-react";
import { getCustomer } from "@/lib/auth";
import { db } from "@/db";
import { orders } from "@/db/schema";
import { eq, desc, count } from "drizzle-orm";
import { redirect } from "next/navigation";

export const dynamic = "force-dynamic";

export default async function MyAccountPage() {
  const customer = await getCustomer();
  if (!customer) redirect("/giris");

  const [orderCount] = await db.select({ value: count() }).from(orders).where(eq(orders.customerId, customer.id));

  const menu = [
    { label: "Siparişlerim", href: "/hesabim/siparisler", icon: ShoppingBag, desc: `${orderCount?.value ?? 0} sipariş`, color: "bg-brand-500" },
    { label: "Adres Bilgilerim", href: "/hesabim/adresler", icon: MapPin, desc: customer.city || "Adres ekle", color: "bg-emerald-500" },
    { label: "Profil Bilgilerim", href: "/hesabim/profil", icon: User, desc: customer.email, color: "bg-violet-500" },
  ];

  return (
    <div className="mx-auto w-full max-w-4xl px-3 py-6 sm:px-6 sm:py-10">
      <div className="flex min-w-0 items-center gap-3 sm:gap-4">
        <span className="grid size-16 place-items-center rounded-2xl bg-gradient-to-br from-brand-400 to-brand-600 text-white shadow-xl shadow-brand-500/30">
          <PawPrint className="size-8" />
        </span>
        <div>
          <h1 className="break-words font-display text-2xl font-extrabold leading-tight text-ink sm:text-3xl">Merhaba, {customer.name.split(" ")[0]}! 🐾</h1>
          <p className="text-sm font-semibold text-mocha">Hesabını buradan yönetebilirsin.</p>
        </div>
      </div>

      <div className="mt-8 grid gap-4 sm:grid-cols-3">
        {menu.map((m) => (
          <Link key={m.href + m.label} href={m.href} className="group flex min-w-0 items-center gap-3 rounded-2xl bg-white p-4 sm:gap-4 sm:rounded-3xl sm:p-5 shadow-sm ring-1 ring-sand-dark/60 transition-all hover:-translate-y-1 hover:shadow-lg hover:shadow-brand-500/10">
            <span className={`grid size-12 place-items-center rounded-xl text-white shadow-md ${m.color}`}><m.icon className="size-6" /></span>
            <div className="flex-1">
              <p className="font-extrabold text-ink">{m.label}</p>
              <p className="text-xs font-bold text-mocha">{m.desc}</p>
            </div>
            <ChevronRight className="size-5 text-latte transition-transform group-hover:translate-x-1 group-hover:text-brand-500" />
          </Link>
        ))}
      </div>
    </div>
  );
}
