import { useEffect, useState } from "react";
import { apiClient } from "@/lib/api";
import type {
  SimTopUpPricing,
  SimTopUpPricingPreviewResponse,
} from "@customer-portal/domain/sim";

interface UseSimTopUpPricingResult {
  pricing: SimTopUpPricing | null;
  loading: boolean;
  error: string | null;
  calculatePreview: (quotaMb: number) => Promise<SimTopUpPricingPreviewResponse | null>;
}

export function useSimTopUpPricing(): UseSimTopUpPricingResult {
  const [pricing, setPricing] = useState<SimTopUpPricing | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;

    const fetchPricing = async () => {
      try {
        setLoading(true);
        const response = await apiClient.GET("/api/subscriptions/sim/top-up/pricing");
        
        if (mounted && response.data) {
          const data = response.data as { success: boolean; data: SimTopUpPricing };
          setPricing(data.data);
          setError(null);
        }
      } catch (err) {
        if (mounted) {
          setError(err instanceof Error ? err.message : "Failed to load pricing");
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    };

    void fetchPricing();

    return () => {
      mounted = false;
    };
  }, []);

  const calculatePreview = async (
    quotaMb: number
  ): Promise<SimTopUpPricingPreviewResponse | null> => {
    try {
      const response = await apiClient.GET("/api/subscriptions/sim/top-up/pricing/preview", {
        params: { query: { quotaMb: quotaMb.toString() } },
      });

      const data = response.data as { success: boolean; data: SimTopUpPricingPreviewResponse };
      return data.data;
    } catch (err) {
      console.error("Failed to calculate pricing preview:", err);
      return null;
    }
  };

  return { pricing, loading, error, calculatePreview };
}

