"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { apiClient } from "@/core/api";
import { paymentMethodListSchema, type PaymentMethodList } from "@customer-portal/domain/payments";
import { useAuthSession } from "@/features/auth/stores/auth.store";

type Tone = "info" | "success" | "warning" | "error";

interface UsePaymentRefreshOptions {
  refetch: () => Promise<{ data: PaymentMethodList | undefined }>;
  hasMethods?: (data?: PaymentMethodList) => boolean;
}

export function usePaymentRefresh({ refetch, hasMethods }: UsePaymentRefreshOptions) {
  const { isAuthenticated } = useAuthSession();
  const hideToastTimeout = useRef<number | null>(null);
  const lastRefreshAt = useRef<number>(0);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [toast, setToast] = useState<{ visible: boolean; text: string; tone: Tone }>({
    visible: false,
    text: "",
    tone: "info",
  });

  const clearHideToastTimeout = () => {
    if (hideToastTimeout.current) {
      clearTimeout(hideToastTimeout.current);
      hideToastTimeout.current = null;
    }
  };

  const COOLDOWN_MS = 10_000;

  const triggerRefresh = useCallback(async () => {
    const now = Date.now();
    if (!isAuthenticated || isRefreshing || now - lastRefreshAt.current < COOLDOWN_MS) return;

    lastRefreshAt.current = now;
    setIsRefreshing(true);
    setToast({ visible: true, text: "Refreshing payment methods...", tone: "info" });
    try {
      try {
        await apiClient.POST("/api/invoices/payment-methods/refresh");
      } catch {
        // Soft-fail cache refresh, still attempt refetch
      }
      const result = await refetch();
      const parsed = paymentMethodListSchema.safeParse(result.data ?? null);
      const list = parsed.success ? parsed.data : { paymentMethods: [], totalCount: 0 };
      const has =
        typeof hasMethods === "function"
          ? hasMethods(parsed.success ? parsed.data : undefined)
          : list.totalCount > 0 || list.paymentMethods.length > 0;
      setToast({
        visible: true,
        text: has ? "Payment methods updated" : "No payment method found yet",
        tone: has ? "success" : "warning",
      });
    } catch {
      setToast({ visible: true, text: "Could not refresh payment methods", tone: "warning" });
    } finally {
      setIsRefreshing(false);
      clearHideToastTimeout();
      hideToastTimeout.current = window.setTimeout(() => {
        setToast(t => ({ ...t, visible: false }));
        hideToastTimeout.current = null;
      }, 2200);
    }
  }, [isAuthenticated, isRefreshing, refetch, hasMethods]);

  useEffect(() => {
    return () => {
      clearHideToastTimeout();
    };
  }, []);

  return { toast, triggerRefresh, isRefreshing, setToast } as const;
}
