import Link from "next/link";
import { redirect } from "next/navigation";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import { requestRefund } from "@/lib/actions/customer-account";
import StatusBadge from "@/components/admin/StatusBadge";
import AccountDateFilter from "@/components/AccountDateFilter";

export const metadata = { title: "My Account — Iniyaval Return Gifts" };

const REFUNDABLE_STATUSES = ["paid", "shipped", "delivered"];

const STATUS_TABS = [
  { key: "", label: "All" },
  { key: "pending", label: "Pending Payment" },
  { key: "shipped", label: "On the way" },
  { key: "delivered", label: "Delivered" },
  { key: "cancelled", label: "Cancelled" },
  { key: "returned", label: "Returned" },
];

const RANGE_MS: Record<string, number> = {
  "30d": 30 * 24 * 60 * 60 * 1000,
  "6m": 182 * 24 * 60 * 60 * 1000,
  "1y": 365 * 24 * 60 * 60 * 1000,
};

function withParams(base: Record<string, string | undefined>, overrides: Record<string, string | undefined>) {
  const merged = { ...base, ...overrides };
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries(merged)) {
    if (value) params.set(key, value);
  }
  const qs = params.toString();
  return qs ? `/account?${qs}` : "/account";
}

export default async function AccountPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string; q?: string; status?: string; range?: string }>;
}) {
  const customerId = await getCurrentCustomerId();
  if (!customerId) redirect("/account/login");
  const { error, q, status, range } = await searchParams;

  const customer = await prisma.customer.findUnique({
    where: { id: customerId },
    include: {
      orders: {
        orderBy: { createdAt: "desc" },
        include: { items: { include: { product: { select: { name: true } } } } },
      },
    },
  });
  if (!customer) redirect("/account/login");

  let orders = customer.orders;
  if (status === "returned") orders = orders.filter((o) => o.refundedAmount > 0);
  else if (status) orders = orders.filter((o) => o.status === status);
  if (range && RANGE_MS[range]) {
    const cutoff = Date.now() - RANGE_MS[range];
    orders = orders.filter((o) => o.createdAt.getTime() >= cutoff);
  }
  if (q?.trim()) {
    const query = q.trim().toLowerCase();
    orders = orders.filter((o) => o.items.some((i) => i.product.name.toLowerCase().includes(query)));
  }

  const currentParams = { q, status, range };

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-rose-800">My Orders</h1>

      <form action="/account" method="GET" className="relative mt-4">
        {status && <input type="hidden" name="status" value={status} />}
        {range && <input type="hidden" name="range" value={range} />}
        <svg xmlns="http://www.w3.org/2000/svg" className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-stone-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
        </svg>
        <input
          type="search"
          name="q"
          defaultValue={q ?? ""}
          placeholder="Search by product name..."
          className="w-full rounded-md border border-stone-300 py-2 pl-9 pr-3 text-sm focus:border-rose-400 focus:outline-none"
        />
      </form>

      <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap gap-1">
          {STATUS_TABS.map((tab) => {
            const isActive = (status ?? "") === tab.key;
            return (
              <Link
                key={tab.key}
                href={withParams(currentParams, { status: tab.key || undefined })}
                className={`rounded-full px-3 py-1.5 text-sm font-medium transition-colors ${
                  isActive ? "bg-rose-700 text-white" : "text-stone-600 hover:bg-stone-100"
                }`}
              >
                {tab.label}
              </Link>
            );
          })}
        </div>
        <AccountDateFilter />
      </div>

      {error && <p className="mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      {orders.length === 0 ? (
        <div className="mt-10 flex flex-col items-center rounded-lg border border-rose-100 bg-white px-6 py-16 text-center">
          <svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12 text-stone-300" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75M3.75 4.5h16.5v15a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-15zM3.75 4.5L5.25 3h13.5l1.5 1.5" />
          </svg>
          <p className="mt-4 text-sm text-stone-500">No orders yet.</p>
          <Link href="/shop" className="mt-4 inline-block rounded-md bg-rose-700 px-5 py-2.5 text-sm font-semibold text-white hover:bg-rose-800">
            Start Shopping
          </Link>
        </div>
      ) : (
        <div className="mt-5 space-y-3">
          {orders.map((o) => (
            <div key={o.id} className="overflow-hidden rounded-lg border border-rose-100 bg-white">
              <div className="flex items-center justify-between p-3">
                <div>
                  <Link href={`/order/${o.orderNumber}?email=${encodeURIComponent(o.email)}`} className="font-medium text-rose-700 hover:underline">
                    {o.orderNumber}
                  </Link>
                  <div className="text-xs text-stone-400">{o.createdAt.toLocaleDateString("en-IN")}</div>
                </div>
                <div className="text-right">
                  <div className="text-stone-600">{formatPaise(o.total)}</div>
                  <StatusBadge status={o.status} />
                </div>
              </div>
              {o.status === "paid" && (
                <div className="border-t border-rose-50 px-3 py-2">
                  <Link
                    href={`/order/${o.orderNumber}/invoice?email=${encodeURIComponent(o.email)}`}
                    className="text-xs font-medium text-rose-700 hover:underline"
                  >
                    View invoice →
                  </Link>
                </div>
              )}
              {REFUNDABLE_STATUSES.includes(o.status) && (
                <div className="border-t border-rose-50 bg-stone-50/60 px-3 py-2">
                  {o.refundRequestStatus === "pending" ? (
                    <p className="text-xs text-amber-700">
                      Refund requested {o.refundRequestedAt ? formatDate(o.refundRequestedAt) : ""} — pending review.
                    </p>
                  ) : o.refundRequestStatus === "declined" ? (
                    <p className="text-xs text-stone-500">
                      Refund request declined. Contact us on WhatsApp if you&apos;d like to discuss it.
                    </p>
                  ) : o.refundedAmount > 0 ? (
                    <p className="text-xs text-emerald-700">Refunded {formatPaise(o.refundedAmount)}.</p>
                  ) : (
                    <details>
                      <summary className="cursor-pointer text-xs font-medium text-stone-500 hover:text-rose-700">
                        Request a return / refund
                      </summary>
                      <form action={requestRefund.bind(null, o.id)} className="mt-2 flex gap-2">
                        <input
                          name="reason"
                          required
                          maxLength={2000}
                          placeholder="What's the issue with this order?"
                          className="flex-1 rounded-md border border-stone-300 px-2 py-1.5 text-xs"
                        />
                        <button type="submit" className="whitespace-nowrap rounded-md bg-stone-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-stone-800">
                          Submit
                        </button>
                      </form>
                    </details>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      <div className="mt-8 rounded-lg border border-rose-100 bg-white p-4">
        <p className="text-sm text-stone-500">
          Wishlist items are currently saved on this device/browser rather than tied to your account — check the{" "}
          <Link href="/wishlist" className="text-rose-700 hover:underline">
            wishlist page
          </Link>{" "}
          from the same browser you added items on.
        </p>
      </div>
    </div>
  );
}
