import { useEffect, useState } from "react";
import { apiClient, getDataOrDefault } from "@/core/api";
import { logger } from "@/core/logger";
import {
  simTopUpPricingPreviewResponseSchema,
  simTopUpPricingSchema,
  type SimTopUpPricing,
  type 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);
  const fallbackPricing: SimTopUpPricing = {
    pricePerGbJpy: 500,
    minQuotaMb: 1000,
    maxQuotaMb: 51200,
    currency: "JPY",
  };

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

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

    void fetchPricing();

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

  const calculatePreview = async (
    quotaMb: number
  ): Promise<SimTopUpPricingPreviewResponse | null> => {
    try {
      const response = await apiClient.GET<SimTopUpPricingPreviewResponse>(
        "/api/subscriptions/sim/top-up/pricing/preview",
        {
          params: { query: { quotaMb: quotaMb.toString() } },
        }
      );
      const data = getDataOrDefault(response, null);
      return data ? simTopUpPricingPreviewResponseSchema.parse(data) : null;
    } catch (err) {
      logger.error("Failed to calculate pricing preview", err);
      return null;
    }
  };

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