"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 CouponRow = {
  _id: string;
  code: string;
  type: string;
  value: number;
  applyTo?: "full_order" | "products_only";
  minOrder?: number;
  expiresAt?: string | null;
  description?: string;
};

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

  const load = useCallback(async () => {
    if (!isAuthenticated) return;
    setBusy(true);
    try {
      const res = await DataService.get("/user/shop/coupons");
      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">Coupons</h1>
        <p className="mt-4 text-gray-600">Sign in to view available coupons.</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">Coupons</h1>
      <p className="mt-1 text-gray-600">Apply a code at checkout when placing an order.</p>
      {busy ? (
        <p className="mt-4 text-gray-500">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="mt-4 text-gray-600">No active coupons right now.</p>
      ) : (
        <ul className="mt-6 space-y-3">
          {rows.map((c) => (
            <li key={c._id} className="rounded-lg border bg-white p-4">
              <p className="font-mono text-lg font-bold text-primary">{c.code}</p>
              <p className="mt-1 text-sm text-gray-700">
                {c.type === "percent" ? `${c.value}% off` : `Rs ${c.value} off`}
                {(c.applyTo || "full_order") === "products_only"
                  ? " · Products only"
                  : " · Full order"}
                {(c.minOrder || 0) > 0 ? ` · Min order ${c.minOrder}` : ""}
              </p>
              {c.description ? <p className="mt-1 text-sm text-gray-600">{c.description}</p> : null}
              {c.expiresAt ? (
                <p className="mt-1 text-xs text-gray-500">
                  Expires {new Date(c.expiresAt).toLocaleDateString()}
                </p>
              ) : null}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
