import Link from "next/link";
import { redirect } from "next/navigation";
import { desc, eq, or } from "drizzle-orm";
import { db } from "@/db";
import { orders, rewardTx, prescriptions, consultations } from "@/db/schema";
import { getCustomer } from "@/lib/auth";
import { getSettings } from "@/lib/data";
import { ugx, fmtDate } from "@/lib/format";
import { logout } from "@/app/actions";
import { ProfileForm } from "@/components/forms";
export const metadata = { title: "My Account" };
const TABS = [["", "Dashboard"], ["orders", "My Orders"], ["profile", "Profile & Addresses"], ["rewards", "Rewards"], ["health", "Prescriptions & Consultations"]];
export default async function Account({ searchParams }: { searchParams: Promise<{ tab?: string }> }) {
  const c = await getCustomer(); if (!c) redirect("/login");
  const tab = (await searchParams).tab || "";
  const s = await getSettings();
  const os = await db.select().from(orders).where(or(eq(orders.customerId, c.id), eq(orders.email, c.email))).orderBy(desc(orders.id));
  const rt = await db.select().from(rewardTx).where(eq(rewardTx.customerId, c.id)).orderBy(desc(rewardTx.id));
  const rx = await db.select({ id: prescriptions.id, status: prescriptions.status, createdAt: prescriptions.createdAt, reviewNotes: prescriptions.reviewNotes }).from(prescriptions).where(eq(prescriptions.customerId, c.id)).orderBy(desc(prescriptions.id));
  const tc = await db.select().from(consultations).where(eq(consultations.customerId, c.id)).orderBy(desc(consultations.id));
  const OrdersT = ({ list }: { list: typeof os }) => list.length ? <div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr className="text-left text-slate-500"><th className="py-2">Order</th><th>Date</th><th>Status</th><th>Payment</th><th className="text-right">Total</th></tr></thead><tbody>{list.map((o) => <tr key={o.id} className="border-t"><td className="py-3"><Link href={`/order/${o.number}`} className="text-brand font-semibold">{o.number}</Link></td><td>{fmtDate(o.createdAt)}</td><td>{o.status}</td><td>{o.paymentStatus}</td><td className="text-right font-semibold">{ugx(o.total)}</td></tr>)}</tbody></table></div> : <p className="text-sm text-slate-500">No orders yet. <Link href="/shop" className="text-brand">Start shopping</Link></p>;
  return (
    <div className="container-x py-10 grid lg:grid-cols-[240px_1fr] gap-8">
      <aside className="card p-4 h-fit">
        <div className="p-3 mb-2"><div className="font-bold">{c.name}</div><div className="text-xs text-slate-500">{c.email}</div></div>
        {TABS.map(([k, l]) => <Link key={k} href={k ? `/account?tab=${k}` : "/account"} className={`block px-3 py-2 rounded-lg text-sm font-semibold ${tab === k ? "bg-mint text-brand" : "hover:bg-cloud"}`}>{l}</Link>)}
        <Link href="/wishlist" className="block px-3 py-2 rounded-lg text-sm font-semibold hover:bg-cloud">Wishlist</Link>
        <form action={logout}><button className="w-full text-left px-3 py-2 rounded-lg text-sm font-semibold text-red-600 hover:bg-red-50">Sign out</button></form>
      </aside>
      <div className="space-y-6">
        {tab === "" && <>
          <h1 className="section-title">Hello, {c.name.split(" ")[0]} 👋</h1>
          <div className="grid sm:grid-cols-3 gap-4">{[["Orders", os.length], ["Reward points", c.points], ["Points value", ugx(c.points * s.pointValue)]].map(([l, v]) => <div key={l} className="card p-5"><div className="text-xs text-slate-500">{l}</div><div className="text-2xl font-extrabold text-brand mt-1">{v}</div></div>)}</div>
          <div className="card p-6"><h3 className="font-bold mb-3">Recent orders</h3><OrdersT list={os.slice(0, 5)} /></div>
        </>}
        {tab === "orders" && <div className="card p-6"><h1 className="font-bold text-xl mb-4">My Orders</h1><OrdersT list={os} /></div>}
        {tab === "profile" && <div className="card p-6"><h1 className="font-bold text-xl mb-4">Profile & Addresses</h1>{c.addresses.length > 0 && <div className="grid sm:grid-cols-2 gap-3 mb-6">{c.addresses.map((a) => <div key={a.label} className="border rounded-xl p-3 text-sm"><b>{a.label}</b><br />{a.address}, {a.town}, {a.district}</div>)}</div>}<ProfileForm c={c} /></div>}
        {tab === "rewards" && <div className="card p-6"><h1 className="font-bold text-xl">Rewards & Loyalty</h1><p className="text-sm text-slate-500 mb-4">Balance: <b className="text-brand">{c.points} points</b> (worth {ugx(c.points * s.pointValue)}). Redeem at checkout.</p>{rt.map((r) => <div key={r.id} className="flex justify-between border-t py-2 text-sm"><span>{r.reason}<span className="block text-xs text-slate-400">{fmtDate(r.createdAt)}</span></span><span className={r.points > 0 ? "text-brand font-bold" : "text-red-600 font-bold"}>{r.points > 0 ? "+" : ""}{r.points}</span></div>)}</div>}
        {tab === "health" && <div className="grid gap-6"><div className="card p-6"><h2 className="font-bold mb-3">Prescriptions</h2>{rx.length ? rx.map((r) => <div key={r.id} className="border-t py-2 text-sm flex justify-between"><span>RX-{r.id} · {fmtDate(r.createdAt)}{r.reviewNotes && <span className="block text-slate-500">{r.reviewNotes}</span>}</span><b>{r.status}</b></div>) : <p className="text-sm text-slate-500">None. <Link href="/prescription" className="text-brand">Upload one</Link></p>}</div><div className="card p-6"><h2 className="font-bold mb-3">Teleconsultations</h2>{tc.length ? tc.map((t) => <div key={t.id} className="border-t py-2 text-sm flex justify-between"><span>TC-{t.id} · {t.type} · {t.date} {t.time}</span><b>{t.status}</b></div>) : <p className="text-sm text-slate-500">None. <Link href="/consultation" className="text-brand">Book one</Link></p>}</div></div>}
      </div>
    </div>
  );
}
