"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api-client";
import type { ReferenceOptionType } from "@/lib/api-types";
import type { WizardLocale } from "@/lib/i18n/wizard-labels";

export interface ReferenceOption {
  value: string;
  label: string;
  metadata?: Record<string, unknown>;
}

export interface UseReferenceOptionsParams {
  region?: string;
  locale?: WizardLocale;
}

export function useReferenceOptions(
  optionType: ReferenceOptionType | string,
  countryCode = "UZ",
  params?: UseReferenceOptionsParams,
) {
  const region = params?.region;
  const locale = params?.locale;
  const [options, setOptions] = useState<ReferenceOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    (async () => {
      setLoading(true);
      try {
        const data = await api.reference.options(optionType, countryCode, {
          region,
          locale,
        });
        if (cancelled) return;
        setOptions(
          Array.isArray(data)
            ? data.map((o: ReferenceOption) => ({
                value: o.value,
                label: o.label,
                metadata: o.metadata,
              }))
            : [],
        );
        setError(null);
      } catch (e: unknown) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : "Failed to load options");
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [optionType, countryCode, region, locale]);

  return { options, loading, error };
}
