import { useAuthStore, useKycVerification } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import { useCallback } from "react";

export type KycStatus = "verified" | "pending" | "rejected" | "required";

/**
 * Returns the current KYC status and a guard function that blocks actions
 * when KYC is not verified, showing the appropriate message and navigation.
 *
 * Usage:
 *   const { kycStatus, requireKyc } = useKycCheck();
 *   if (!requireKyc()) return; // blocks and navigates if KYC incomplete
 */
export function useKycCheck() {
  const kycEnabled = useKycVerification();
  const { user } = useAuthStore((state) => state);
  const { tran } = useTranslations();

  const getKycStatus = useCallback((): KycStatus => {
    if (!kycEnabled) return "verified";
    if (user?.is_kyc_verified || user?.kyc_status === "approved") return "verified";
    if (user?.kyc_status === "pending") return "pending";
    if (user?.kyc_status === "rejected") return "rejected";
    return "required";
  }, [kycEnabled, user?.is_kyc_verified, user?.kyc_status]);

  const kycStatus = getKycStatus();

  /**
   * Call before any KYC-protected action.
   * Returns true if the user can proceed, false if blocked.
   * When blocked, shows a toast and navigates to the appropriate screen.
   */
  const requireKyc = useCallback((): boolean => {
    const status = getKycStatus();

    if (status === "verified") return true;

    if (status === "pending") {
      showToast({
        type: "info",
        text: tran("Your KYC verification is under review. Please wait for approval."),
      });
      return false;
    }

    if (status === "rejected") {
      showToast({
        type: "error",
        text: user?.kyc?.reason
          ? tran("Your KYC was rejected:") + " " + user.kyc.reason
          : tran("Your KYC was rejected. Please resubmit your verification."),
      });
      router.push("/(auth)/kyc");
      return false;
    }

    // status === "required" — not submitted
    showToast({
      type: "error",
      text: tran("Please complete your KYC verification to proceed."),
    });
    router.push("/(auth)/kyc");
    return false;
  }, [getKycStatus, tran, user?.kyc?.reason]);

  /**
   * Handle KYC-related API error responses (403 with type kyc_pending/kyc_rejected/kyc_required).
   * Returns true if the error was a KYC error and was handled, false otherwise.
   */
  const handleKycError = useCallback(
    (err: any): boolean => {
      const response = err?.response?.data;
      const status = err?.response?.status;

      if (status !== 403) return false;

      const type = response?.type;

      if (type === "kyc_pending") {
        showToast({
          type: "info",
          text: tran(response?.message || "Your KYC verification is under review."),
        });
        return true;
      }

      if (type === "kyc_rejected") {
        showToast({
          type: "error",
          text: response?.reason
            ? tran("Your KYC was rejected:") + " " + response.reason
            : tran(response?.message || "Your KYC was rejected. Please resubmit."),
        });
        router.push("/(auth)/kyc");
        return true;
      }

      if (type === "kyc_required") {
        showToast({
          type: "error",
          text: tran(response?.message || "Please complete your KYC verification to proceed."),
        });
        router.push("/(auth)/kyc");
        return true;
      }

      return false;
    },
    [tran],
  );

  return { kycStatus, kycEnabled, requireKyc, handleKycError };
}
