"use client";

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;
  paymentMethod?: string;
  createdAt?: string;
  items?: {
    title: string;
    quantity: number;
    unitPrice: number;
    lineSubtotal: number;
  }[];
};

export default function AccountOrdersPage() {
  const { isAuthenticated, loading } = 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">Orders</h1>
        <p className="mt-4 text-gray-600">Sign in to view your orders.</p>
        <Button className="mt-4" type="button" onClick={() => openAuthModal("login")}>
          Log in
        </Button>
      </div>
    );
  }

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">Orders</h1>
      {busy ? (
        <p className="mt-4 text-gray-500">Loading…</p>
      ) : orders.length === 0 ? (
        <p className="mt-4 text-gray-600">No orders yet.</p>
      ) : (
        <ul className="mt-6 space-y-6">
          {orders.map((o) => (
            <li key={o._id} className="rounded-lg border bg-white p-4">
              <div className="flex flex-wrap items-baseline justify-between gap-2">
                <div>
                  <p className="font-semibold text-slate-900">{o.orderNumber}</p>
                  <p className="text-xs text-gray-500">
                    {o.createdAt ? new Date(o.createdAt).toLocaleString() : ""}
                  </p>
                </div>
                <div className="text-right">
                  <p className="font-bold text-primary">{o.grandTotal.toFixed(2)}</p>
                  <p className="text-xs capitalize text-gray-600">{o.status}</p>
                </div>
              </div>
              <ul className="mt-3 space-y-1 border-t pt-3 text-sm">
                {(o.items || []).map((it, i) => (
                  <li key={i} className="flex justify-between gap-4">
                    <span>
                      {it.title} × {it.quantity}
                    </span>
                    <span>{it.lineSubtotal.toFixed(2)}</span>
                  </li>
                ))}
              </ul>
              <p className="mt-2 text-xs text-gray-600">
                Payment: {o.paymentMethod === "cod" ? "Cash on delivery" : o.paymentMethod}
              </p>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
