import { useEffect, useState } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { getAppSettings } from "@/shared/api/appSettings.js";

const DAYS_PATTERN = /^(\d+)d$/;
const HOURS_PATTERN = /^(\d+)h$/;

const DEFAULTS = {
  onlineboardSearchFrom: 2,
  onlineboardSearchTo: 14,
  scheduleSearchFrom: 30,
  scheduleSearchTo: 30,
  flightStatusAvailableFromHours: 24,
  buyTicketMinHours: 2,
  buyTicketMaxHours: 72,
} as const;

function parsePattern(
  value: string | undefined,
  pattern: RegExp,
  fallback: number,
): number {
  if (!value) return fallback;
  const match = pattern.exec(value);
  if (!match) return fallback;
  return parseInt(match[1]!, 10);
}

function parseDays(value: string | undefined, fallback: number): number {
  return parsePattern(value, DAYS_PATTERN, fallback);
}

function parseHours(value: string | undefined, fallback: number): number {
  return parsePattern(value, HOURS_PATTERN, fallback);
}

export interface UseAppSettingsResult {
  onlineboardSearchFrom: number;
  onlineboardSearchTo: number;
  scheduleSearchFrom: number;
  scheduleSearchTo: number;
  flightStatusAvailableFromHours: number;
  buyTicketMinHours: number;
  buyTicketMaxHours: number;
  loading: boolean;
  error: Error | null;
}

/**
 * Fetches the global app settings and exposes day-range and button-config numbers.
 * On error or parse failure, returns defaults.
 */
export function useAppSettings(): UseAppSettingsResult {
  const client = useApiClient();
  const [state, setState] = useState<Omit<UseAppSettingsResult, "loading" | "error">>(DEFAULTS);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;

    getAppSettings(client)
      .then((response) => {
        if (cancelled) return;
        const ob = response.uiOptions?.filter?.onlineboard;
        const sc = response.uiOptions?.filter?.schedule;
        const fs = response.uiOptions?.buttons?.flightStatus;
        const bt = response.uiOptions?.buttons?.buyTicket;

        setState({
          onlineboardSearchFrom: parseDays(ob?.searchFrom, DEFAULTS.onlineboardSearchFrom),
          onlineboardSearchTo: parseDays(ob?.searchTo, DEFAULTS.onlineboardSearchTo),
          scheduleSearchFrom: parseDays(sc?.searchFrom, DEFAULTS.scheduleSearchFrom),
          scheduleSearchTo: parseDays(sc?.searchTo, DEFAULTS.scheduleSearchTo),
          flightStatusAvailableFromHours: parseHours(
            fs?.availableFrom,
            DEFAULTS.flightStatusAvailableFromHours,
          ),
          buyTicketMinHours: parseHours(bt?.period?.min, DEFAULTS.buyTicketMinHours),
          buyTicketMaxHours: parseHours(bt?.period?.max, DEFAULTS.buyTicketMaxHours),
        });
        setLoading(false);
      })
      .catch((err: Error) => {
        if (cancelled) return;
        setError(err);
        setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [client]);

  return { ...state, loading, error };
}
