import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';

import API from '../services/API';
import type { Radio } from '../types/radio.types';

interface RadiosContextValue {
  radios: Radio[];
  loading: boolean;
  error: string | null;
}

const RadiosContext = createContext<RadiosContextValue | null>(null);

export const RadiosProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [radios, setRadios] = useState<Radio[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchRadios = async () => {
      try {
        setLoading(true);
        setError(null);
        const data = await API.fetchAllRadios();
        setRadios(data || []);
      } catch (err) {
        console.error('Failed to fetch radios:', err);
        setError(err instanceof Error ? err.message : 'Failed to fetch radios');
      } finally {
        setLoading(false);
      }
    };

    fetchRadios();
  }, []);

  const value = useMemo<RadiosContextValue>(
    () => ({
      radios,
      loading,
      error,
    }),
    [radios, loading, error]
  );

  return <RadiosContext.Provider value={value}>{children}</RadiosContext.Provider>;
};

export const useRadios = (): RadiosContextValue => {
  const ctx = useContext(RadiosContext);
  if (!ctx) {
    throw new Error('useRadios must be used within RadiosProvider');
  }
  return ctx;
};

export const useRadiosByProtocol = (protocol: string): Radio[] => {
  const { radios } = useRadios();
  return useMemo(() => radios.filter((radio) => radio.protocol === protocol), [radios, protocol]);
};
