"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 PaymentRow = {
  _id: string;
  orderNumber: string;
  grandTotal: number;
  paymentMethod?: string;
  paymentStatus?: string;
  paymentReference?: string;
  paidAt?: string | null;
  createdAt?: string;
  status?: string;
};

export default function AccountPaymentsPage() {
  const { isAuthenticated, loading } = usePublicSession();
  const { openAuthModal } = useAuthModal();
  const [rows, setRows] = useState<PaymentRow[]>([]);
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    if (!isAuthenticated) return;
    setBusy(true);
    try {
      const res = await DataService.get("/user/shop/payments");
      setRows(res.data?.data || []);
    } catch {
      setRows([]);
    } 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">Payments</h1>
        <p className="mt-4 text-gray-600">Sign in to view payment history.</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">Payment history</h1>
      <p className="mt-1 text-gray-600">Payments linked to your orders.</p>
      {busy ? (
        <p className="mt-4 text-gray-500">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="mt-4 text-gray-600">No payments yet.</p>
      ) : (
        <div className="mt-6 overflow-x-auto rounded-lg border bg-white">
          <table className="w-full min-w-[520px] text-left text-sm">
            <thead className="border-b bg-gray-50 text-xs uppercase text-gray-500">
              <tr>
                <th className="px-4 py-3">Order</th>
                <th className="px-4 py-3">Method</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Amount</th>
                <th className="px-4 py-3">Date</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r._id} className="border-b last:border-0">
                  <td className="px-4 py-3">
                    <Link href={`/account/orders/${r._id}`} className="font-medium text-primary hover:underline">
                      {r.orderNumber}
                    </Link>
                  </td>
                  <td className="px-4 py-3 capitalize">
                    {r.paymentMethod === "bank_transfer" ? "Bank transfer" : r.paymentMethod || "—"}
                  </td>
                  <td className="px-4 py-3 capitalize">
                    {(r.paymentStatus || "unpaid").replace(/_/g, " ")}
                  </td>
                  <td className="px-4 py-3 font-semibold">{Number(r.grandTotal).toFixed(2)}</td>
                  <td className="px-4 py-3 text-gray-600">
                    {r.paidAt
                      ? new Date(r.paidAt).toLocaleDateString()
                      : r.createdAt
                        ? new Date(r.createdAt).toLocaleDateString()
                        : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
