'use client'

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { AppSettings } from '../types';

const defaultSettings: AppSettings = {
  opencodeApiKey: '',
  opencodeModel: 'minimax-m2.5-free',
  api34aiKey: '',
  api34aiBaseUrl: 'https://api.34ai.net/api/v1',
  imageModel: 'banana_pro_2',
  videoModel: 'veo3.1',
  defaultDuration: 4,
  defaultAspectRatio: '16:9',
  tiktokCookies: '',
};

interface SettingsContextType {
  settings: AppSettings;
  updateSettings: (newSettings: Partial<AppSettings>) => void;
  isLoaded: boolean;
  isMounted: boolean;
}

const SettingsContext = createContext<SettingsContextType>({
  settings: defaultSettings,
  updateSettings: () => {},
  isLoaded: false,
  isMounted: false,
});

export function SettingsProvider({ children }: { children: ReactNode }) {
  const [settings, setSettings] = useState<AppSettings>(defaultSettings);
  const [isLoaded, setIsLoaded] = useState(false);
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
    const saved = localStorage.getItem('ai-video-flow-settings');
    if (saved && saved !== 'undefined' && saved !== 'null') {
      try {
        const parsed = JSON.parse(saved);
        setSettings({ ...defaultSettings, ...parsed });
      } catch (e) {
        console.error('Failed to parse settings:', e);
      }
    }
    setIsLoaded(true);
  }, []);

const updateSettings = (newSettings: Partial<AppSettings>) => {
    const sanitized: Partial<AppSettings> = {}
    for (const [key, value] of Object.entries(newSettings)) {
      if (value !== undefined && value !== 'undefined') {
        (sanitized as any)[key] = value
      }
    }
    const updated = { ...settings, ...sanitized }
    setSettings(updated)
    localStorage.setItem('ai-video-flow-settings', JSON.stringify(updated))
  };

  return (
    <SettingsContext.Provider value={{ settings, updateSettings, isLoaded, isMounted }}>
      {children}
    </SettingsContext.Provider>
  );
}

export function useSettings() {
  return useContext(SettingsContext);
}