"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.
 */
function isActiveInternetSub(subscription: {
  groupName?: string | undefined;
  productName: string;
  status: string;
}): boolean {
  const name = String(subscription.groupName || subscription.productName || "").toLowerCase();
  return name.includes("internet") && String(subscription.status || "").toLowerCase() === "active";
}

const NON_INTERNET_STATES = {
  isLoading: false,
  isError: false,
  isNotRequested: false,
  isPending: false,
  isIneligible: false,
  isEligible: true,
  notes: null,
  requestedAt: null,
} as const;

function deriveEligibilityStates(
  isInternetOrder: boolean,
  query: { isLoading: boolean; isError: boolean; isSuccess: boolean },
  data: EligibilityData | null | undefined
) {
  if (!isInternetOrder) return { ...NON_INTERNET_STATES };
  const status = data?.status;
  const value = data?.eligibility;
  return {
    isLoading: query.isLoading,
    isError: query.isError,
    isNotRequested: query.isSuccess && status === "not_requested",
    isPending: query.isSuccess && status === "pending",
    isIneligible: query.isSuccess && status === "ineligible",
    isEligible: status === "eligible" && typeof value === "string" && value.trim().length > 0,
    notes: data?.notes ?? null,
    requestedAt: data?.requestedAt ?? null,
  };
}

export function useCheckoutEligibility({ orderType }: UseCheckoutEligibilityOptions) {
  const isInternetOrder = orderType === ORDER_TYPE.INTERNET;

  const { data: activeSubs } = useActiveSubscriptions();
  const hasActiveInternetSubscription = useMemo(() => {
    if (!Array.isArray(activeSubs)) return false;
    return activeSubs.some(isActiveInternetSub);
  }, [activeSubs]);

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

  const eligibilityQuery = useInternetEligibility({ enabled: isInternetOrder });
  const eligibilityData = eligibilityQuery.data as EligibilityData | null | undefined;
  const eligibilityRequest = useRequestInternetEligibilityCheck();

  const states = deriveEligibilityStates(isInternetOrder, eligibilityQuery, eligibilityData);

  return {
    eligibility: {
      ...states,
      refetch: () => void eligibilityQuery.refetch(),
    },
    eligibilityRequest,
    hasActiveInternetSubscription,
    activeInternetWarning,
  };
}
