import axios from 'axios';
import { API_BASE_URL, API_CONFIG } from './apiConfig';

export interface SettingDto {
  key: string;
  value: string;
  type: string;
  category: string;
  description?: string;
  isActive?: boolean;
}

// 사용자 설정 관련 인터페이스
export interface UserSettings {
  userId: number;
  username: string;
  buyAlertEnabled: boolean;
  dataUpdateIntervalMinutes?: number;
}

export interface UpdateUserSettingsRequest {
  buyAlertEnabled?: boolean;
  dataUpdateIntervalMinutes?: number;
}

export interface BuySignalStatus {
  hasSignal: boolean;
  lastSignalTime: number;
  timestamp: number;
}

// 사용자 설정 API 인스턴스
const userSettingsApi = axios.create({
  ...API_CONFIG,
  baseURL: `${API_BASE_URL}/user/settings`,
});

userSettingsApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accessToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

/**
 * 사용자 설정 조회
 */
export const getUserSettings = async (): Promise<UserSettings> => {
  try {
    const response = await userSettingsApi.get<UserSettings>('');
    return response.data;
  } catch (error) {
    // 사용자 설정이 없으면 기본값 반환
    return {
      userId: 0,
      username: '',
      buyAlertEnabled: false,
      dataUpdateIntervalMinutes: 1,
    };
  }
};

/**
 * 사용자 설정 업데이트
 */
export const updateUserSettings = async (
  settings: UpdateUserSettingsRequest
): Promise<UserSettings> => {
  const response = await userSettingsApi.put<UserSettings>('', settings);
  return response.data;
};

/**
 * 최근 매수 신호 확인
 */
export const checkBuySignal = async (): Promise<BuySignalStatus> => {
  try {
    const response = await userSettingsApi.get<BuySignalStatus>('/check-buy-signal');
    return response.data;
  } catch (error) {
    return { hasSignal: false, lastSignalTime: 0, timestamp: 0 };
  }
};

// 설정 Export/Import 관련 인터페이스
export interface SettingsExportData {
  version: string;
  exportedAt: string;
  analysisSettings: SettingDto[];
  indicatorPeriodSettings: any[];
  tradingStrategies: any[];
  strategyRules: any[];
}

export interface ImportResult {
  success: boolean;
  message: string;
  importedAt?: string;
}

export const settingsApi = {
  getAllSettings: async (): Promise<SettingDto[]> => {
    const response = await axios.get(`${API_BASE_URL}/settings`);
    return response.data;
  },

  getSettingsByCategory: async (category: string): Promise<SettingDto[]> => {
    const response = await axios.get(`${API_BASE_URL}/settings/category/${category}`);
    return response.data;
  },

  getSetting: async (key: string): Promise<SettingDto> => {
    const response = await axios.get(`${API_BASE_URL}/settings/${key}`);
    return response.data;
  },

  saveSetting: async (setting: SettingDto): Promise<SettingDto> => {
    const response = await axios.post(`${API_BASE_URL}/settings`, setting);
    return response.data;
  },

  saveSettings: async (settings: SettingDto[]): Promise<SettingDto[]> => {
    const response = await axios.post(`${API_BASE_URL}/settings/batch`, settings);
    return response.data;
  },

  deleteSetting: async (key: string): Promise<void> => {
    await axios.delete(`${API_BASE_URL}/settings/${key}`);
  },

  getSettingsAsMap: async (category: string): Promise<Record<string, string>> => {
    const response = await axios.get(`${API_BASE_URL}/settings/map/${category}`);
    return response.data;
  },

  saveSettingsFromMap: async (category: string, settings: Record<string, string>): Promise<void> => {
    await axios.put(`${API_BASE_URL}/settings/map/${category}`, settings);
  },

  /**
   * 모든 설정 Export (JSON 다운로드)
   */
  exportSettings: async (): Promise<SettingsExportData> => {
    const response = await axios.get(`${API_BASE_URL}/settings/export`);
    return response.data;
  },

  /**
   * 설정 Import (JSON 업로드)
   */
  importSettings: async (importData: SettingsExportData): Promise<ImportResult> => {
    const response = await axios.post(`${API_BASE_URL}/settings/import`, importData);
    return response.data;
  },

  /**
   * 설정 Export 후 파일 다운로드 (localStorage의 보조지표 설정 포함)
   */
  downloadExportFile: async (): Promise<void> => {
    try {
      const exportData = await settingsApi.exportSettings();
      
      // ✅ localStorage에서 보조지표 색상/스타일 설정 가져오기
      const indicatorColorSettings: Record<string, any> = {};
      const colorKeys = [
        // MACD
        'macdLineColor', 'macdSignalColor', 'macdHistogramUpColor', 'macdHistogramDownColor',
        'macdLineWidth', 'macdSignalWidth', 'macdLineStyle', 'macdSignalLineStyle',
        'macdZeroLineColor', 'macdZeroLineWidth', 'macdZeroLineStyle',
        // RSI
        'rsiColor', 'rsiWidth', 'rsiLineStyle', 'rsiOverboughtColor', 'rsiOversoldColor',
        'rsiOverboughtWidth', 'rsiOversoldWidth', 'rsiOverboughtLineStyle', 'rsiOversoldLineStyle',
        // Stochastic
        'stochasticFastColor', 'stochasticSlowColor', 'stochasticFastWidth', 'stochasticSlowWidth',
        'stochasticFastLineStyle', 'stochasticSlowLineStyle',
        'stochasticOverboughtColor', 'stochasticOversoldColor', 'stochasticOverboughtWidth', 'stochasticOversoldWidth',
        'stochasticOverboughtLineStyle', 'stochasticOversoldLineStyle',
        // CCI
        'cciColor', 'cciSignalColor', 'cciWidth', 'cciSignalWidth', 'cciLineStyle', 'cciSignalLineStyle',
        'cciOverboughtColor', 'cciOversoldColor', 'cciOverboughtWidth', 'cciOversoldWidth',
        'cciOverboughtLineStyle', 'cciOversoldLineStyle',
        // ADX/DMI
        'adxColor', 'adxWidth', 'adxLineStyle', 'plusDiColor', 'minusDiColor',
        'plusDiWidth', 'minusDiWidth', 'plusDiLineStyle', 'minusDiLineStyle',
        'adxStrongColor', 'adxWeakColor', 'adxStrongWidth', 'adxWeakWidth',
        'adxStrongLineStyle', 'adxWeakLineStyle',
        // TRIX
        'trixColor', 'trixSignalColor', 'trixWidth', 'trixSignalWidth',
        'trixLineStyle', 'trixSignalLineStyle',
        // Williams %R
        'williamsRColor', 'williamsRWidth', 'williamsRLineStyle',
        'williamsROverboughtColor', 'williamsROversoldColor',
        'williamsROverboughtWidth', 'williamsROversoldWidth',
        'williamsROverboughtLineStyle', 'williamsROversoldLineStyle',
        // BWI
        'bwiColor', 'bwiWidth', 'bwiLineStyle',
        'bwiOverboughtColor', 'bwiMiddleColor', 'bwiOversoldColor',
        'bwiOverboughtWidth', 'bwiMiddleWidth', 'bwiOversoldWidth',
        'bwiOverboughtLineStyle', 'bwiMiddleLineStyle', 'bwiOversoldLineStyle',
        // OBV
        'obvColor', 'obvSignalColor', 'obvWidth', 'obvSignalWidth',
        'obvLineStyle', 'obvSignalLineStyle',
        // Volume Oscillator
        'volumeOscColor', 'volumeOscWidth', 'volumeOscLineStyle',
        // VR
        'vrColor', 'vrWidth', 'vrLineStyle',
        'vrOverboughtColor', 'vrBaseLineColor', 'vrOversoldColor',
        'vrOverboughtWidth', 'vrBaseLineWidth', 'vrOversoldWidth',
        'vrOverboughtLineStyle', 'vrBaseLineLineStyle', 'vrOversoldLineStyle',
        // Disparity
        'disparityUltraShortColor', 'disparityShortColor', 'disparityMidColor', 'disparityLongColor',
        'disparityUltraShortWidth', 'disparityShortWidth', 'disparityMidWidth', 'disparityLongWidth',
        'disparityUltraShortLineStyle', 'disparityShortLineStyle', 'disparityMidLineStyle', 'disparityLongLineStyle',
        // New/Invest Psychological
        'newPsyColor', 'newPsyWidth', 'newPsyLineStyle',
        'newPsyOverboughtColor', 'newPsyOversoldColor',
        'newPsyOverboughtWidth', 'newPsyOversoldWidth',
        'newPsyOverboughtLineStyle', 'newPsyOversoldLineStyle',
        'investPsyColor', 'investPsyWidth', 'investPsyLineStyle',
        'investPsyOverboughtColor', 'investPsyOversoldColor',
        'investPsyOverboughtWidth', 'investPsyOversoldWidth',
        'investPsyOverboughtLineStyle', 'investPsyOversoldLineStyle',
        // Momentum
        'momentumColor', 'momentumWidth', 'momentumLineStyle',
      ];
      
      colorKeys.forEach(key => {
        const value = localStorage.getItem(key);
        if (value !== null) {
          // 숫자 타입 변환 시도
          if (key.includes('Width')) {
            indicatorColorSettings[key] = parseFloat(value);
          } else {
            indicatorColorSettings[key] = value;
          }
        }
      });
      
      // ✅ localStorage에서 보조지표 설정 가져오기
      const indicatorSettings: Record<string, any> = {};
      const settingKeys = [
        // 기간 설정
        'macdFastPeriod', 'macdSlowPeriod', 'macdSignalPeriod',
        'rsiPeriod', 'stochasticKPeriod', 'stochasticDPeriod',
        'cciPeriod', 'cciSignalPeriod', 'adxPeriod', 'dmiPeriod',
        'trixPeriod', 'trixSignalPeriod', 'williamsRPeriod',
        'bwiPeriod', 'obvPeriod', 'obvSignalPeriod',
        'volumeOscShortPeriod', 'volumeOscLongPeriod',
        'vrPeriod', 'disparityUltraShortPeriod', 'disparityShortPeriod',
        'disparityMidPeriod', 'disparityLongPeriod',
        'newPsychologicalPeriod', 'investPsychologicalPeriod',
        'momentumPeriod',
        // 활성화 상태
        'macdZeroLineEnabled', 'macdSignalEnabled',
        'rsiOverboughtEnabled', 'rsiOversoldEnabled', 'rsiSignalEnabled',
        'stochasticOverboughtEnabled', 'stochasticOversoldEnabled',
        'cciOverboughtEnabled', 'cciOversoldEnabled', 'cciSignalEnabled',
        'adxStrongEnabled', 'adxWeakEnabled', 'dmiEnabled',
        'trixEnabled', 'trixSignalEnabled',
        'williamsROverboughtEnabled', 'williamsROversoldEnabled',
        'bwiOverboughtEnabled', 'bwiMiddleEnabled', 'bwiOversoldEnabled',
        'obvSignalEnabled',
        'vrOverboughtEnabled', 'vrBaseLineEnabled', 'vrOversoldEnabled',
        'disparityUltraShortEnabled', 'disparityShortEnabled',
        'disparityMidEnabled', 'disparityLongEnabled', 'disparityEnabled',
        'newPsyOverboughtEnabled', 'newPsyOversoldEnabled',
        'investPsyOverboughtEnabled', 'investPsyOversoldEnabled',
        // 기준값
        'rsiOverbought', 'rsiOversold',
        'stochasticOverbought', 'stochasticOversold',
        'cciOverbought', 'cciOversold',
        'adxStrongThreshold', 'adxWeakThreshold',
        'williamsROverbought', 'williamsROversold',
        'bwiOverbought', 'bwiMiddle', 'bwiOversold',
        'vrOverbought', 'vrBaseLine', 'vrOversold',
        'newPsyOverbought', 'newPsyOversold',
        'investPsyOverbought', 'investPsyOversold',
      ];
      
      settingKeys.forEach(key => {
        const value = localStorage.getItem(key);
        if (value !== null) {
          // boolean 타입 변환
          if (key.includes('Enabled')) {
            indicatorSettings[key] = value === 'true';
          }
          // 숫자 타입 변환
          else if (key.includes('Period') || key.includes('Threshold') || 
                   key.includes('bought') || key.includes('sold') || 
                   key.includes('Middle') || key.includes('Base')) {
            indicatorSettings[key] = parseFloat(value);
          } else {
            indicatorSettings[key] = value;
          }
        }
      });
      
      // ✅ 보조지표 설정 추가
      const completeExportData = {
        ...exportData,
        indicatorColorSettings,
        indicatorSettings,
      };
      
      // JSON 파일 생성 및 다운로드
      const blob = new Blob([JSON.stringify(completeExportData, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      
      const now = new Date();
      const timestamp = now.toISOString().slice(0, 19).replace(/[:-]/g, '').replace('T', '-');
      link.download = `golden-analysis-settings-${timestamp}.json`;
      link.href = url;
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      console.log('✅ 설정 Export 완료 - 보조지표 색상 설정:', Object.keys(indicatorColorSettings).length, '개');
      console.log('✅ 설정 Export 완료 - 보조지표 설정:', Object.keys(indicatorSettings).length, '개');
    } catch (error) {
      console.error('설정 Export 실패:', error);
      throw error;
    }
  },

  /**
   * 파일에서 설정 Import (localStorage의 보조지표 설정 포함)
   */
  importFromFile: async (file: File): Promise<ImportResult> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = async (e) => {
        try {
          const content = e.target?.result as string;
          const importData: any = JSON.parse(content);
          
          // 유효성 검사
          if (!importData.version) {
            reject(new Error('유효하지 않은 설정 파일입니다. (버전 정보 없음)'));
            return;
          }
          
          // ✅ 백엔드로 서버 설정 Import
          const result = await settingsApi.importSettings(importData);
          
          // ✅ localStorage에 보조지표 색상/스타일 설정 저장
          if (importData.indicatorColorSettings) {
            console.log('📥 보조지표 색상 설정 Import 시작:', Object.keys(importData.indicatorColorSettings).length, '개');
            Object.entries(importData.indicatorColorSettings).forEach(([key, value]) => {
              if (value !== undefined && value !== null) {
                localStorage.setItem(key, String(value));
              }
            });
            console.log('✅ 보조지표 색상 설정 Import 완료');
          }
          
          // ✅ localStorage에 보조지표 설정 저장
          if (importData.indicatorSettings) {
            console.log('📥 보조지표 설정 Import 시작:', Object.keys(importData.indicatorSettings).length, '개');
            Object.entries(importData.indicatorSettings).forEach(([key, value]) => {
              if (value !== undefined && value !== null) {
                localStorage.setItem(key, String(value));
              }
            });
            console.log('✅ 보조지표 설정 Import 완료');
          }
          
          // ✅ Context 갱신을 위해 페이지 새로고침 권장
          if (importData.indicatorColorSettings || importData.indicatorSettings) {
            console.log('💡 보조지표 설정이 Import되었습니다. 페이지를 새로고침하여 변경사항을 적용하세요.');
          }
          
          resolve(result);
        } catch (error: any) {
          if (error instanceof SyntaxError) {
            reject(new Error('JSON 파일 형식이 올바르지 않습니다.'));
          } else {
            reject(error);
          }
        }
      };
      
      reader.onerror = () => {
        reject(new Error('파일 읽기 실패'));
      };
      
      reader.readAsText(file);
    });
  },

  // ==================== 피보나치 타임존 설정 API ====================

  /**
   * 게스트 사용자 피보나치 설정 조회
   */
  getGuestFibonacciSettings: async (deviceId: string): Promise<string> => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/settings/fibonacci/guest/${deviceId}`,
      { responseType: 'text' } // ✅ 응답을 텍스트로 받기 (자동 JSON 파싱 방지)
    );
    console.log('📂 [API] 피보나치 설정 조회 응답 (원본):', response.data);
    console.log('📂 [API] 피보나치 설정 조회 응답 타입:', typeof response.data);
    return response.data;
  } catch (error) {
    console.error('❌ [API] 피보나치 설정 조회 실패:', error);
    return '{}';
  }
},

/**
 * 게스트 사용자 피보나치 설정 저장
 */
saveGuestFibonacciSettings: async (
  deviceId: string,
  settings: string
): Promise<void> => {
  try {
    console.log('💾 [API] 피보나치 설정 저장 요청:', { deviceId, settings });
    await axios.post(
      `${API_BASE_URL}/settings/fibonacci/guest/${deviceId}`,
      { settings }
    );
    console.log('✅ [API] 피보나치 설정 저장 성공');
  } catch (error) {
    console.error('❌ [API] 피보나치 설정 저장 실패:', error);
    throw error;
  }
},

/**
 * 게스트 사용자 피보나치 그려진 객체들 조회
 */
getGuestFibonacciObjects: async (deviceId: string): Promise<string> => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/settings/fibonacci/objects/guest/${deviceId}`,
      { responseType: 'text' }
    );
    console.log('📂 [API] 피보나치 객체 조회 응답:', response.data);
    return response.data;
  } catch (error) {
    console.error('❌ [API] 피보나치 객체 조회 실패:', error);
    return '[]';
  }
},

/**
 * 게스트 사용자 피보나치 그려진 객체들 저장
 */
saveGuestFibonacciObjects: async (
  deviceId: string,
  objects: string
): Promise<void> => {
  try {
    console.log('💾 [API] 피보나치 객체 저장 요청:', { deviceId, objectsLength: objects.length });
    await axios.post(
      `${API_BASE_URL}/settings/fibonacci/objects/guest/${deviceId}`,
      { objects }
    );
    console.log('✅ [API] 피보나치 객체 저장 성공');
  } catch (error) {
    console.error('❌ [API] 피보나치 객체 저장 실패:', error);
    throw error;
  }
},

// ==================== 기간 측정 도구 설정 API ====================

/**
 * 게스트 사용자 기간 측정 설정 조회
 */
getGuestMeasureSettings: async (deviceId: string): Promise<string> => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/settings/measure/guest/${deviceId}`,
      { responseType: 'text' }
    );
    console.log('📂 [API] 기간 측정 설정 조회 응답:', response.data);
    return response.data;
  } catch (error) {
    console.error('❌ [API] 기간 측정 설정 조회 실패:', error);
    return '{}';
  }
},

/**
 * 게스트 사용자 기간 측정 설정 저장
 */
saveGuestMeasureSettings: async (
  deviceId: string,
  settings: string
): Promise<void> => {
  try {
    console.log('💾 [API] 기간 측정 설정 저장 요청:', { deviceId, settings });
    await axios.post(
      `${API_BASE_URL}/settings/measure/guest/${deviceId}`,
      { settings }
    );
    console.log('✅ [API] 기간 측정 설정 저장 성공');
  } catch (error) {
    console.error('❌ [API] 기간 측정 설정 저장 실패:', error);
    throw error;
  }
}
};

