"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { usePublicSession } from "@/components/shop/public-session-context";
import { useAuthModal } from "@/components/shop/auth-modal-context";
import DataService from "@/config/axios";

type OrderRow = {
  _id: string;
  orderNumber: string;
  grandTotal: number;
  status: string;
  paymentStatus?: string;
  paymentMethod?: string;
  createdAt?: string;
};

export default function AccountDashboardPage() {
  const { isAuthenticated, loading, user, wishlistCount } = usePublicSession();
  const { openAuthModal } = useAuthModal();
  const [orders, setOrders] = useState<OrderRow[]>([]);
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    if (!isAuthenticated) return;
    setBusy(true);
    try {
      const res = await DataService.get("/user/shop/orders");
      setOrders(res.data?.data || []);
    } catch {
      setOrders([]);
    } finally {
      setBusy(false);
    }
  }, [isAuthenticated]);

  useEffect(() => {
    if (!loading && isAuthenticated) load();
  }, [loading, isAuthenticated, load]);

  if (loading) return <p className="text-gray-500">Loading…</p>;

  if (!isAuthenticated) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-slate-900">My account</h1>
        <p className="mt-4 text-gray-600">Sign in to manage orders, returns, and more.</p>
        <Button className="mt-4" type="button" onClick={() => openAuthModal("login")}>
          Log in
        </Button>
      </div>
    );
  }

  const recent = orders.slice(0, 5);
  const needsPay = orders.filter(
    (o) =>
      o.paymentMethod === "bank_transfer" &&
      ["unpaid", "awaiting_confirmation"].includes(o.paymentStatus || "unpaid") &&
      o.status !== "cancelled"
  );

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">
        Hello{user?.firstName ? `, ${user.firstName}` : ""}
      </h1>
      <p className="mt-1 text-gray-600">Manage your orders and account from here.</p>

      <div className="mt-6 grid gap-4 sm:grid-cols-3">
        <div className="rounded-lg border bg-white p-4">
          <p className="text-xs uppercase text-gray-500">Orders</p>
          <p className="mt-1 text-2xl font-bold text-slate-900">{busy ? "…" : orders.length}</p>
        </div>
        <div className="rounded-lg border bg-white p-4">
          <p className="text-xs uppercase text-gray-500">Wishlist</p>
          <p className="mt-1 text-2xl font-bold text-slate-900">{wishlistCount}</p>
        </div>
        <div className="rounded-lg border bg-white p-4">
          <p className="text-xs uppercase text-gray-500">Awaiting payment</p>
          <p className="mt-1 text-2xl font-bold text-slate-900">{needsPay.length}</p>
        </div>
      </div>

      {needsPay.length > 0 ? (
        <div className="mt-6 rounded-lg border border-amber-200 bg-amber-50 p-4">
          <p className="font-semibold text-slate-900">Bank transfer pending</p>
          <p className="mt-1 text-sm text-gray-700">
            Submit a reference or payment proof so we can confirm your payment.
          </p>
          <ul className="mt-3 space-y-2">
            {needsPay.slice(0, 3).map((o) => (
              <li key={o._id}>
                <Link href={`/account/orders/${o._id}`} className="text-sm font-medium text-primary hover:underline">
                  {o.orderNumber} — Rs {Number(o.grandTotal).toFixed(2)}
                </Link>
              </li>
            ))}
          </ul>
        </div>
      ) : null}

      <div className="mt-8">
        <div className="flex items-center justify-between gap-2">
          <h2 className="text-lg font-semibold text-slate-900">Recent orders</h2>
          <Button asChild variant="outline" size="sm">
            <Link href="/account/orders">View all</Link>
          </Button>
        </div>
        {busy ? (
          <p className="mt-4 text-gray-500">Loading…</p>
        ) : recent.length === 0 ? (
          <p className="mt-4 text-gray-600">No orders yet.</p>
        ) : (
          <ul className="mt-4 space-y-3">
            {recent.map((o) => (
              <li key={o._id} className="flex flex-wrap items-center justify-between gap-2 rounded-lg border bg-white p-3">
                <div>
                  <Link href={`/account/orders/${o._id}`} className="font-semibold text-slate-900 hover:text-primary">
                    {o.orderNumber}
                  </Link>
                  <p className="text-xs capitalize text-gray-500">
                    {o.status} · {o.paymentStatus || "unpaid"}
                  </p>
                </div>
                <p className="font-semibold text-primary">{Number(o.grandTotal).toFixed(2)}</p>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
