import UIKit
import WebKit
import KakaoSDKCommon
import KakaoSDKAuth
import KakaoSDKUser

class MainViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    
    private let TAG = "MainViewController"
    
    // WebView
    var webView: WKWebView!
    var webViewMenu: WKWebView?
    
    // UI 요소
    var progressBar: UIProgressView!
    var bottomNavigationView: UITabBar!
    
    // 상태 변수
    var currentUrl: String?
    var isTwoClickBack = false
    
    // UserDefaults (Android의 SharedPreferences와 동일)
    let userDefaults = UserDefaults.standard
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 앱 초기화
        setupWebView()
        setupUI()
        
        // 카카오 SDK 초기화 (AppDelegate에서 이미 초기화했다고 가정)
        
        // 웹뷰 로드
        loadInitialUrl()
    }
    
    private func setupWebView() {
        // WKWebView 설정
        let webConfiguration = WKWebViewConfiguration()
        let contentController = WKUserContentController()
        
        // JavaScript 인터페이스 추가
        contentController.add(self, name: "appInterface")
        webConfiguration.userContentController = contentController
        
        // 웹뷰 생성
        webView = WKWebView(frame: view.bounds, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.allowsBackForwardNavigationGestures = true
        
        // 웹뷰 설정
        if let webView = webView {
            webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            
            // 웹뷰 설정
            if #available(iOS 14.0, *) {
                webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = true
            } else {
                webView.configuration.preferences.javaScriptEnabled = true
            }
            
            // 쿠키 설정
            webView.configuration.websiteDataStore = .default()
            
            view.addSubview(webView)
        }
    }
    
    private func setupUI() {
        // 프로그레스바 설정
        progressBar = UIProgressView(progressViewStyle: .default)
        progressBar.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(progressBar)
        
        // 프로그레스바 제약조건
        NSLayoutConstraint.activate([
            progressBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            progressBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            progressBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            progressBar.heightAnchor.constraint(equalToConstant: 2.0)
        ])
        
        // 하단 탭바 설정 (Android의 BottomNavigationView와 유사)
        bottomNavigationView = UITabBar()
        bottomNavigationView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(bottomNavigationView)
        
        // 탭바 제약조건
        NSLayoutConstraint.activate([
            bottomNavigationView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            bottomNavigationView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            bottomNavigationView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            bottomNavigationView.heightAnchor.constraint(equalToConstant: 49.0)
        ])
        
        // 웹뷰 제약조건 업데이트
        if let webView = webView {
            webView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                webView.topAnchor.constraint(equalTo: progressBar.bottomAnchor),
                webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
                webView.bottomAnchor.constraint(equalTo: bottomNavigationView.topAnchor)
            ])
        }
        
        // KVO 설정 - 웹뷰 로딩 진행 상황 관찰
        webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
    }
    
    private func loadInitialUrl() {
        // 초기 URL 로드
        let initialUrl = "https://your-initial-url.com"
        if let url = URL(string: initialUrl) {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
    
    // MARK: - WKNavigationDelegate 메서드
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        // 페이지 로딩 시작
        progressBar.isHidden = false
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 페이지 로딩 완료
        progressBar.isHidden = true
        currentUrl = webView.url?.absoluteString
        
        // 사용자 정보가 있으면 웹뷰에 전달
        if let userId = userDefaults.string(forKey: "userid"),
           let email = userDefaults.string(forKey: "email"),
           let nickname = userDefaults.string(forKey: "nickname") {
            let script = "set_user_info('\(userId)','\(email)','\(nickname)')"
            webView.evaluateJavaScript(script, completionHandler: nil)
        }
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        // 페이지 로딩 실패
        progressBar.isHidden = true
        
        // 에러 처리
        let alert = UIAlertController(title: "오류", message: "페이지를 로드할 수 없습니다: \(error.localizedDescription)", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "확인", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    // MARK: - WKUIDelegate 메서드
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        // 새 창 열기 처리
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        return nil
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        // JavaScript alert 처리
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "확인", style: .default, handler: { _ in
            completionHandler()
        }))
        present(alert, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        // JavaScript confirm 처리
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "취소", style: .cancel, handler: { _ in
            completionHandler(false)
        }))
        alert.addAction(UIAlertAction(title: "확인", style: .default, handler: { _ in
            completionHandler(true)
        }))
        present(alert, animated: true, completion: nil)
    }
    
    // MARK: - KVO
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressBar.progress = Float(webView.estimatedProgress)
        }
    }
    
    // MARK: - 카카오 로그인 관련 메서드
    
    func openKakaoLogin() {
        // 카카오 로그인 화면으로 이동
        let kakaoLoginVC = KakaoLogin()
        present(kakaoLoginVC, animated: true, completion: nil)
    }
    
    // MARK: - 뒤로가기 처리
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // KVO 제거
        webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
}

// MARK: - WKScriptMessageHandler (JavaScript 인터페이스)
extension MainViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        // JavaScript에서 호출한 메시지 처리
        if message.name == "appInterface" {
            if let messageBody = message.body as? [String: Any] {
                if let action = messageBody["action"] as? String {
                    switch action {
                    case "openKakaoLogin":
                        openKakaoLogin()
                    case "getUserInfo":
                        getUserInfo()
                    case "showToast":
                        if let toast = messageBody["message"] as? String {
                            showToast(message: toast)
                        }
                    default:
                        break
                    }
                }
            }
        }
    }
    
    // JavaScript 인터페이스 메서드들
    private func getUserInfo() {
        // 사용자 정보 가져오기
        if let userId = userDefaults.string(forKey: "userid"),
           let email = userDefaults.string(forKey: "email"),
           let nickname = userDefaults.string(forKey: "nickname") {
            let script = "set_user_info('\(userId)','\(email)','\(nickname)')"
            webView.evaluateJavaScript(script, completionHandler: nil)
        }
    }
    
    private func showToast(message: String) {
        // 토스트 메시지 표시 (iOS에서는 UIAlertController 사용)
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        present(alert, animated: true, completion: nil)
        
        // 1.5초 후 자동으로 닫기
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            alert.dismiss(animated: true, completion: nil)
        }
    }
} 