"use client";

import { useMemo } from "react";
import {
  useInternetEligibility,
  useRequestInternetEligibilityCheck,
} from "@/features/services/hooks/useInternetEligibility";
import { useActiveSubscriptions } from "@/features/subscriptions/hooks/useSubscriptions";
import { ACTIVE_INTERNET_SUBSCRIPTION_WARNING } from "@/features/checkout/constants";
import type { OrderTypeValue } from "@customer-portal/domain/orders";
import { ORDER_TYPE } from "@customer-portal/domain/orders";

interface UseCheckoutEligibilityOptions {
  orderType: OrderTypeValue | null;
}

interface EligibilityData {
  eligibility?: string;
  status?: string;
  requestedAt?: string;
  notes?: string;
}

/**
 * Hook that consolidates all eligibility-related state for checkout.
 * Handles internet eligibility checks and active subscription warnings.
 */
export function useCheckoutEligibility({ orderType }: UseCheckoutEligibilityOptions) {
  const isInternetOrder = orderType === ORDER_TYPE.INTERNET;

  // Active subscriptions check
  const { data: activeSubs } = useActiveSubscriptions();
  const hasActiveInternetSubscription = useMemo(() => {
    if (!Array.isArray(activeSubs)) return false;
    return activeSubs.some(
      subscription =>
        String(subscription.groupName || subscription.productName || "")
          .toLowerCase()
          .includes("internet") && String(subscription.status || "").toLowerCase() === "active"
    );
  }, [activeSubs]);

  const activeInternetWarning =
    isInternetOrder && hasActiveInternetSubscription ? ACTIVE_INTERNET_SUBSCRIPTION_WARNING : null;

  // Internet eligibility
  const eligibilityQuery = useInternetEligibility({ enabled: isInternetOrder });
  const eligibilityData = eligibilityQuery.data as EligibilityData | null | undefined;
  const eligibilityValue = eligibilityData?.eligibility;
  const eligibilityStatus = eligibilityData?.status;
  const eligibilityRequestedAt = eligibilityData?.requestedAt;
  const eligibilityNotes = eligibilityData?.notes;
  const eligibilityRequest = useRequestInternetEligibilityCheck();

  // Derived eligibility states
  const isLoading = Boolean(isInternetOrder && eligibilityQuery.isLoading);
  const isError = Boolean(isInternetOrder && eligibilityQuery.isError);
  const isNotRequested = Boolean(
    isInternetOrder && eligibilityQuery.isSuccess && eligibilityStatus === "not_requested"
  );
  const isPending = Boolean(
    isInternetOrder && eligibilityQuery.isSuccess && eligibilityStatus === "pending"
  );
  const isIneligible = Boolean(
    isInternetOrder && eligibilityQuery.isSuccess && eligibilityStatus === "ineligible"
  );
  const isEligible =
    !isInternetOrder ||
    (eligibilityStatus === "eligible" &&
      typeof eligibilityValue === "string" &&
      eligibilityValue.trim().length > 0);

  return {
    /** Consolidated eligibility state */
    eligibility: {
      isLoading,
      isError,
      isPending,
      isNotRequested,
      isIneligible,
      isEligible,
      notes: eligibilityNotes ?? null,
      requestedAt: eligibilityRequestedAt ?? null,
      refetch: () => void eligibilityQuery.refetch(),
    },
    /** Eligibility request mutation */
    eligibilityRequest,
    /** Whether user has active internet subscription */
    hasActiveInternetSubscription,
    /** Warning message if user has active internet subscription and is ordering internet */
    activeInternetWarning,
  };
}
