import React, { createContext, useContext, useState, useEffect, useMemo, ReactNode } from 'react';
import { createTheme, Theme } from '@mui/material/styles';

// 테마 타입 정의
export type ThemeMode = 'light' | 'dark' | 'blue';

interface ThemeContextType {
  themeMode: ThemeMode;
  setThemeMode: (mode: ThemeMode) => void;
  theme: Theme;
  chartColors: ChartColors;
}

// 차트 색상 인터페이스
export interface ChartColors {
  background: string;
  textColor: string;
  gridColor: string;
  candleRising: string;
  candleFalling: string;
  ma12: string;
  ma26: string;
  ma60: string;
  crosshairColor: string;
  crosshairLabelBg: string;
  tooltipBg: string;
  tooltipBorder: string;
  // 볼린저 밴드
  bollingerUpperColor?: string;
  bollingerUpperWidth?: number;
  bollingerUpperLineStyle?: 'solid' | 'dashed' | 'dotted';
  bollingerMiddleColor?: string;
  bollingerMiddleWidth?: number;
  bollingerMiddleLineStyle?: 'solid' | 'dashed' | 'dotted';
  bollingerLowerColor?: string;
  bollingerLowerWidth?: number;
  bollingerLowerLineStyle?: 'solid' | 'dashed' | 'dotted';
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 화이트 모드 테마 (goldenCross 스타일)
const lightTheme = createTheme({
  palette: {
    mode: 'light',
    primary: {
      main: '#1976d2',
      light: '#42a5f5',
      dark: '#1565c0',
    },
    secondary: {
      main: '#dc004e',
    },
    warning: {
      main: '#ff9800',
    },
    background: {
      default: '#f5f5f5',
      paper: '#ffffff',
    },
    text: {
      primary: '#212121',
      secondary: '#757575',
    },
    success: {
      main: '#4caf50',
    },
    error: {
      main: '#f44336',
    },
    info: {
      main: '#2196f3',
    },
  },
  typography: {
    fontFamily: '"Noto Sans KR", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    h4: {
      fontWeight: 600,
    },
    h5: {
      fontWeight: 600,
    },
    h6: {
      fontWeight: 500,
    },
  },
  components: {
    MuiAppBar: {
      styleOverrides: {
        root: {
          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        },
      },
    },
    MuiCard: {
      styleOverrides: {
        root: {
          border: '1px solid rgba(0, 0, 0, 0.1)',
        },
      },
    },
    MuiPaper: {
      styleOverrides: {
        root: {
          backgroundImage: 'none',
        },
      },
    },
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: 'none',
          fontWeight: 500,
        },
      },
    },
    MuiTableHead: {
      styleOverrides: {
        root: {
          '& .MuiTableCell-head': {
            backgroundColor: '#f5f5f5',
            fontWeight: 600,
          },
        },
      },
    },
  },
});

// 다크 모드 테마 (시인성 개선)
const darkTheme = createTheme({
  palette: {
    mode: 'dark',
    primary: {
      main: '#7aa2f7',      // 더 밝은 블루
      light: '#a9c4ff',
      dark: '#5a7dc7',
    },
    secondary: {
      main: '#f7768e',      // 선명한 코랄 핑크
      light: '#ffb0b8',
      dark: '#d45a6e',
    },
    background: {
      default: '#1a1b26',   // 도쿄 나이트 스타일 배경
      paper: '#24283b',
    },
    text: {
      primary: '#c0caf5',   // 밝은 라벤더 (시인성 향상)
      secondary: '#9aa5ce', // 부드러운 보조 텍스트
    },
    success: {
      main: '#9ece6a',      // 선명한 라임 그린
    },
    error: {
      main: '#f7768e',      // 선명한 코랄
    },
    warning: {
      main: '#e0af68',      // 따뜻한 골드
    },
    info: {
      main: '#7dcfff',      // 시안 블루
    },
    divider: 'rgba(192, 202, 245, 0.15)',
  },
  typography: {
    fontFamily: '"Noto Sans KR", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    h4: {
      fontWeight: 600,
      color: '#c0caf5',
    },
    h5: {
      fontWeight: 600,
      color: '#c0caf5',
    },
    h6: {
      fontWeight: 500,
      color: '#c0caf5',
    },
  },
  components: {
    MuiCard: {
      styleOverrides: {
        root: {
          backgroundImage: 'linear-gradient(145deg, #24283b 0%, #1f2335 100%)',
          border: '1px solid rgba(122, 162, 247, 0.15)',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.3)',
        },
      },
    },
    MuiPaper: {
      styleOverrides: {
        root: {
          backgroundImage: 'none',
          backgroundColor: '#24283b',
        },
      },
    },
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: 'none',
          fontWeight: 500,
        },
      },
    },
    MuiTableHead: {
      styleOverrides: {
        root: {
          '& .MuiTableCell-head': {
            backgroundColor: '#1f2335',
            fontWeight: 600,
            color: '#c0caf5',
          },
        },
      },
    },
    MuiTableCell: {
      styleOverrides: {
        root: {
          borderColor: 'rgba(192, 202, 245, 0.1)',
          color: '#a9b1d6',
        },
      },
    },
    MuiChip: {
      styleOverrides: {
        root: {
          fontWeight: 500,
        },
      },
    },
    MuiDialog: {
      styleOverrides: {
        paper: {
          borderRadius: 12,
          border: '1px solid rgba(63, 126, 245, 0.35)',
          backgroundImage: 'none',
          backgroundColor: '#1e222d',
          boxShadow: '0 0 0 1px rgba(63,126,245,0.08), 0 20px 60px rgba(0,0,0,0.65), 0 0 40px rgba(63,126,245,0.06)',
          overflow: 'hidden',
        },
      },
    },
    MuiDialogTitle: {
      styleOverrides: {
        root: {
          background: 'linear-gradient(180deg, rgba(63,126,245,0.14) 0%, rgba(63,126,245,0.04) 28px, #1f2335 100%)',
          borderBottom: '1px solid rgba(122,162,247,0.12)',
          color: '#c0caf5',
          fontSize: '14px',
          fontWeight: 700,
          padding: '10px 14px',
        },
      },
    },
    MuiDialogContent: {
      styleOverrides: {
        root: {
          backgroundColor: '#1e222d',
          color: '#c0caf5',
          padding: '12px 14px',
        },
      },
    },
    MuiDialogActions: {
      styleOverrides: {
        root: {
          backgroundColor: '#1e222d',
          borderTop: '1px solid rgba(122,162,247,0.1)',
          padding: '10px 14px',
        },
      },
    },
    MuiInputBase: {
      styleOverrides: {
        root: {
          color: '#c0caf5',
        },
      },
    },
    MuiOutlinedInput: {
      styleOverrides: {
        notchedOutline: {
          borderColor: 'rgba(122, 162, 247, 0.3)',
        },
      },
    },
  },
});

// 차트 색상 테마
const lightChartColors: ChartColors = {
  background: '#ffffff',
  textColor: '#333333',
  gridColor: '#f0f0f0',
  candleRising: '#ef4444',    // 빨간색 (상승)
  candleFalling: '#2196f3',   // 파란색 (하락)
  ma12: '#2196F3',
  ma26: '#FF9800',
  ma60: '#9C27B0',
  crosshairColor: 'rgba(33, 150, 243, 0.5)',
  crosshairLabelBg: '#2196F3',
  tooltipBg: 'rgba(255, 255, 255, 0.95)',
  tooltipBorder: 'rgba(33, 150, 243, 0.3)',
  // 볼린저 밴드
  bollingerUpperColor: '#FF9800',
  bollingerUpperWidth: 1.5,
  bollingerUpperLineStyle: 'solid',
  bollingerMiddleColor: '#2196F3',
  bollingerMiddleWidth: 1.5,
  bollingerMiddleLineStyle: 'dashed',
  bollingerLowerColor: '#4CAF50',
  bollingerLowerWidth: 1.5,
  bollingerLowerLineStyle: 'solid',
};

const darkChartColors: ChartColors = {
  background: '#1a1b26',           // 배경과 일치
  textColor: '#c0caf5',            // 밝은 텍스트 (시인성 향상)
  gridColor: 'rgba(122, 162, 247, 0.12)', // 부드러운 그리드
  candleRising: '#ff6b6b',         // 빨간색 (상승)
  candleFalling: '#4dabf7',        // 파란색 (하락)
  ma12: '#7aa2f7',                 // 밝은 블루
  ma26: '#e0af68',                 // 따뜻한 골드
  ma60: '#bb9af7',                 // 밝은 퍼플
  crosshairColor: 'rgba(122, 162, 247, 0.6)',
  crosshairLabelBg: '#7aa2f7',
  tooltipBg: 'rgba(36, 40, 59, 0.98)',
  tooltipBorder: 'rgba(122, 162, 247, 0.4)',
  // 볼린저 밴드
  bollingerUpperColor: '#e0af68',
  bollingerUpperWidth: 1.5,
  bollingerUpperLineStyle: 'solid',
  bollingerMiddleColor: '#7aa2f7',
  bollingerMiddleWidth: 1.5,
  bollingerMiddleLineStyle: 'dashed',
  bollingerLowerColor: '#9ece6a',
  bollingerLowerWidth: 1.5,
  bollingerLowerLineStyle: 'solid',
};

// 블루 모드 테마 (시인성 개선)
const blueTheme = createTheme({
  palette: {
    mode: 'dark',
    primary: {
      main: '#5eb5ff',       // 밝은 스카이 블루
      light: '#8ed0ff',
      dark: '#3a9ae0',
    },
    secondary: {
      main: '#64d2ff',       // 시안
      light: '#94e2ff',
      dark: '#4ab5e0',
    },
    background: {
      default: '#0c1929',    // 딥 네이비
      paper: '#15273d',
    },
    text: {
      primary: '#e8f4ff',    // 밝은 아이스 블루
      secondary: '#b8d4f0',  // 부드러운 블루 그레이
    },
    success: {
      main: '#5dffa2',       // 민트 그린
    },
    error: {
      main: '#ff6b8a',       // 코랄 핑크
    },
    warning: {
      main: '#ffc857',       // 골든 옐로우
    },
    info: {
      main: '#5eb5ff',
    },
    divider: 'rgba(94, 181, 255, 0.15)',
  },
  typography: {
    fontFamily: '"Noto Sans KR", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    h4: { fontWeight: 600, color: '#e8f4ff' },
    h5: { fontWeight: 600, color: '#e8f4ff' },
    h6: { fontWeight: 500, color: '#e8f4ff' },
  },
  components: {
    MuiCard: {
      styleOverrides: {
        root: {
          backgroundImage: 'linear-gradient(145deg, #15273d 0%, #0f1e30 100%)',
          border: '1px solid rgba(94, 181, 255, 0.2)',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.4)',
        },
      },
    },
    MuiPaper: {
      styleOverrides: {
        root: { 
          backgroundImage: 'none',
          backgroundColor: '#15273d',
        },
      },
    },
    MuiButton: {
      styleOverrides: {
        root: { textTransform: 'none', fontWeight: 500 },
      },
    },
    MuiTableHead: {
      styleOverrides: {
        root: {
          '& .MuiTableCell-head': {
            backgroundColor: '#0f1e30',
            fontWeight: 600,
            color: '#e8f4ff',
          },
        },
      },
    },
    MuiTableCell: {
      styleOverrides: {
        root: {
          borderColor: 'rgba(94, 181, 255, 0.1)',
          color: '#b8d4f0',
        },
      },
    },
    MuiOutlinedInput: {
      styleOverrides: {
        notchedOutline: {
          borderColor: 'rgba(94, 181, 255, 0.3)',
        },
      },
    },
  },
});

const blueChartColors: ChartColors = {
  background: '#0c1929',
  textColor: '#e8f4ff',              // 밝은 텍스트
  gridColor: 'rgba(94, 181, 255, 0.12)',
  candleRising: '#ff5555',           // 빨간색 (상승)
  candleFalling: '#55aaff',          // 파란색 (하락)
  ma12: '#5eb5ff',                   // 스카이 블루
  ma26: '#ffc857',                   // 골든 옐로우
  ma60: '#c792ea',                   // 라벤더
  crosshairColor: 'rgba(94, 181, 255, 0.6)',
  crosshairLabelBg: '#5eb5ff',
  tooltipBg: 'rgba(21, 39, 61, 0.98)',
  tooltipBorder: 'rgba(94, 181, 255, 0.4)',
  // 볼린저 밴드
  bollingerUpperColor: '#ffc857',
  bollingerUpperWidth: 1.5,
  bollingerUpperLineStyle: 'solid',
  bollingerMiddleColor: '#5eb5ff',
  bollingerMiddleWidth: 1.5,
  bollingerMiddleLineStyle: 'dashed',
  bollingerLowerColor: '#7dd3fc',
  bollingerLowerWidth: 1.5,
  bollingerLowerLineStyle: 'solid',
};

// 테마 맵
const themes: Record<ThemeMode, Theme> = {
  light: lightTheme,
  dark: darkTheme,
  blue: blueTheme,
};

const chartColorMap: Record<ThemeMode, ChartColors> = {
  light: lightChartColors,
  dark: darkChartColors,
  blue: blueChartColors,
};

// 로컬 스토리지 키
const THEME_STORAGE_KEY = 'golden-analysis-theme-mode';

interface ThemeProviderProps {
  children: ReactNode;
}

export const AppThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
  // 로컬 스토리지에서 테마 로드
  const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
    const savedTheme = localStorage.getItem(THEME_STORAGE_KEY);
    return (savedTheme as ThemeMode) || 'dark'; // 기본 다크모드
  });

  // 테마 변경 함수
  const setThemeMode = (mode: ThemeMode) => {
    setThemeModeState(mode);
    localStorage.setItem(THEME_STORAGE_KEY, mode);
  };

  // 현재 테마
  const theme = useMemo(() => themes[themeMode], [themeMode]);
  const chartColors = useMemo(() => chartColorMap[themeMode], [themeMode]);

  // body 배경색 업데이트
  useEffect(() => {
    document.body.style.backgroundColor = theme.palette.background.default;
    document.body.style.color = theme.palette.text.primary;
    document.body.style.minHeight = '100vh';
    document.body.style.backgroundAttachment = 'fixed';
    
    if (themeMode === 'dark') {
      // 도쿄 나이트 스타일 그라데이션
      document.body.style.background = 'linear-gradient(145deg, #1a1b26 0%, #1f2335 50%, #24283b 100%)';
    } else if (themeMode === 'blue') {
      // 딥 네이비 그라데이션
      document.body.style.background = 'linear-gradient(145deg, #0c1929 0%, #122540 50%, #15273d 100%)';
    } else {
      document.body.style.background = theme.palette.background.default;
    }
  }, [theme, themeMode]);

  const value = useMemo(
    () => ({
      themeMode,
      setThemeMode,
      theme,
      chartColors,
    }),
    [themeMode, theme, chartColors]
  );

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
};

// Hook
export const useAppTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useAppTheme must be used within a AppThemeProvider');
  }
  return context;
};

