import { useState, useEffect } from 'react';
import jwtAxios from '../api/axiosInstance';
import { ENDPOINTS } from '../api/endpoints';

export interface InvoiceLanguage {
  code: string;
  name: string;
}

// Fallback list in case the API call fails
const FALLBACK_LANGUAGES: InvoiceLanguage[] = [
  { code: 'en', name: 'English' },
  { code: 'ta', name: 'Tamil (தமிழ்)' },
  { code: 'hi', name: 'Hindi (हिंदी)' },
  { code: 'kn', name: 'Kannada (ಕನ್ನಡ)' },
  { code: 'ml', name: 'Malayalam (മലയാളം)' },
  { code: 'te', name: 'Telugu (తెలుగు)' },
];

export const useInvoiceLanguages = () => {
  const [languages, setLanguages] = useState<InvoiceLanguage[]>(FALLBACK_LANGUAGES);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchLanguages = async () => {
      setLoading(true);
      try {
        const res = await jwtAxios.get(ENDPOINTS.INVOICE_LANGUAGES);
        const result: InvoiceLanguage[] = res.data?.InvoiceLanguages || [];
        if (result.length > 0) {
          // Append native script labels for display
          const labelMap: Record<string, string> = {
            ta: 'Tamil (தமிழ்)',
            hi: 'Hindi (हिंदी)',
            kn: 'Kannada (ಕನ್ನಡ)',
            ml: 'Malayalam (മലയാളം)',
            te: 'Telugu (తెలుగు)',
            en: 'English',
          };
          setLanguages(
            result.map((l) => ({
              code: l.code,
              name: labelMap[l.code] ?? l.name,
            }))
          );
        }
      } catch {
        // Keep fallback list on error
      } finally {
        setLoading(false);
      }
    };

    fetchLanguages();
  }, []);

  return { languages, loading };
};
