import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from 'react';
import systemSettingsService from '../../features/system/services/systemSettingsService';

type CompanySettings = {
  company_name: string;
  company_tagline: string;
  company_logo_url: string;
  company_favicon_url: string;
  company_phone: string;
  company_email: string;
  company_address: string;
  chat_working_hours_start: number;
  chat_working_hours_end: number;
  bank_name?: string;
  bank_account_number?: string;
  bank_account_holder?: string;
  bank_code?: string;
};

type CompanySettingsContextValue = {
  settings: CompanySettings;
  isLoading: boolean;
  refreshSettings: () => Promise<void>;
};

const defaultSettings: CompanySettings = {
  company_name: 'Luxury Hotel',
  company_tagline: 'Excellence Redefined',
  company_logo_url: '',
  company_favicon_url: '',
  company_phone: '',
  company_email: '',
  company_address: '',
  chat_working_hours_start: 9,
  chat_working_hours_end: 17,
  bank_name: '',
  bank_account_number: '',
  bank_account_holder: '',
  bank_code: '',
};

const CompanySettingsContext = createContext<CompanySettingsContextValue | undefined>(undefined);

// eslint-disable-next-line react-refresh/only-export-components
export const useCompanySettings = () => {
  const context = useContext(CompanySettingsContext);
  if (!context) {
    throw new Error('useCompanySettings must be used within CompanySettingsProvider');
  }
  return context;
};

interface CompanySettingsProviderProps {
  children: ReactNode;
}

export const CompanySettingsProvider: React.FC<CompanySettingsProviderProps> = ({ children }) => {
  const [settings, setSettings] = useState<CompanySettings>(defaultSettings);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  
  const loadSettings = async () => {
    try {
      setIsLoading(true);
      const response = await systemSettingsService.getCompanySettings();
      if (response.data) {
        setSettings({
          company_name: response.data.company_name || defaultSettings.company_name,
          company_tagline: response.data.company_tagline || defaultSettings.company_tagline,
          company_logo_url: response.data.company_logo_url || defaultSettings.company_logo_url,
          company_favicon_url: response.data.company_favicon_url || defaultSettings.company_favicon_url,
          company_phone: response.data.company_phone || defaultSettings.company_phone,
          company_email: response.data.company_email || defaultSettings.company_email,
          company_address: response.data.company_address || defaultSettings.company_address,
          chat_working_hours_start: response.data.chat_working_hours_start || defaultSettings.chat_working_hours_start,
          chat_working_hours_end: response.data.chat_working_hours_end || defaultSettings.chat_working_hours_end,
          bank_name: response.data.bank_name || defaultSettings.bank_name,
          bank_account_number: response.data.bank_account_number || defaultSettings.bank_account_number,
          bank_account_holder: response.data.bank_account_holder || defaultSettings.bank_account_holder,
          bank_code: response.data.bank_code || defaultSettings.bank_code,
        });

        
        if (response.data.company_favicon_url) {
          const baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
          const faviconUrl = response.data.company_favicon_url.startsWith('http')
            ? response.data.company_favicon_url
            : `${baseUrl}${response.data.company_favicon_url}`;
          
          const existingLinks = document.querySelectorAll("link[rel~='icon']");
          existingLinks.forEach(link => link.remove());
          
          
          const link = document.createElement('link');
          link.rel = 'icon';
          link.href = faviconUrl;
          document.head.appendChild(link);
        }

        
        if (response.data.company_name) {
          document.title = response.data.company_name;
        }
      }
    } catch (error) {
      console.error('Error loading company settings:', error);
      
      setSettings(defaultSettings);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadSettings();
    
    
    const handleRefresh = () => {
      loadSettings();
    };
    
    if (typeof window !== 'undefined') {
      window.addEventListener('refreshCompanySettings', handleRefresh);
      return () => {
        window.removeEventListener('refreshCompanySettings', handleRefresh);
      };
    }
  }, []);

  const refreshSettings = async () => {
    await loadSettings();
  };

  return (
    <CompanySettingsContext.Provider
      value={{
        settings,
        isLoading,
        refreshSettings,
      }}
    >
      {children}
    </CompanySettingsContext.Provider>
  );
};

