//
//  YHSelectPhoneCountryViewController.swift
//  galaxy
//
//  Created by EDY on 2025/2/12.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

struct Country {
    let name: String
    let code: String
    let index: String // 字符索引
}

class YHSelectPhoneCountryViewController: YHBaseViewController {
    public var backLocationStringController: ((Country) -> Void)?
    var searchView: UITextField!
    var tableView: UITableView!
    var searchTableView: UITableView!
    var filteredCountries: [Country] = []

    let countries: [Country] = [
            Country(name: "阿富汗", code: "93", index: "A"),
            Country(name: "阿尔巴尼亚", code: "355", index: "A"),
            Country(name: "阿尔及利亚", code: "213", index: "A"),
            Country(name: "美属萨摩亚", code: "1684", index: "M"),
            Country(name: "安道尔", code: "376", index: "A"),
            Country(name: "安哥拉", code: "244", index: "A"),
            Country(name: "安圭拉", code: "1264", index: "A"),
            Country(name: "安提瓜和巴布达", code: "1268", index: "A"),
            Country(name: "阿根廷", code: "54", index: "A"),
            Country(name: "亚美尼亚", code: "374", index: "Y"),
            Country(name: "阿鲁巴", code: "297", index: "A"),
            Country(name: "澳大利亚", code: "61", index: "A"),
            Country(name: "奥地利", code: "43", index: "A"),
            Country(name: "阿塞拜疆", code: "994", index: "A"),
            Country(name: "巴哈马", code: "1242", index: "B"),
            Country(name: "巴林", code: "973", index: "B"),
            Country(name: "孟加拉国", code: "880", index: "M"),
            Country(name: "巴巴多斯", code: "1246", index: "B"),
            Country(name: "白俄罗斯", code: "375", index: "B"),
            Country(name: "比利时", code: "32", index: "B"),
            Country(name: "伯利兹", code: "501", index: "B"),
            Country(name: "贝宁", code: "229", index: "B"),
            Country(name: "百慕大群岛", code: "1441", index: "B"),
            Country(name: "不丹", code: "975", index: "B"),
            Country(name: "玻利维亚", code: "591", index: "B"),
            Country(name: "波斯尼亚和黑塞哥维那", code: "387", index: "B"),
            Country(name: "博茨瓦纳", code: "267", index: "B"),
            Country(name: "巴西", code: "55", index: "B"),
            Country(name: "文莱", code: "673", index: "W"),
            Country(name: "保加利亚", code: "359", index: "B"),
            Country(name: "布基纳法索", code: "226", index: "B"),
            Country(name: "布隆迪", code: "257", index: "B"),
            Country(name: "柬埔寨", code: "855", index: "J"),
            Country(name: "喀麦隆", code: "237", index: "K"),
            Country(name: "加拿大", code: "1", index: "J"),
            Country(name: "开普", code: "238", index: "K"),
            Country(name: "开曼群岛", code: "1345", index: "K"),
            Country(name: "中非共和国", code: "236", index: "Z"),
            Country(name: "乍得", code: "235", index: "Z"),
            Country(name: "智利", code: "56", index: "Z"),
            Country(name: "中国", code: "86", index: "Z"),
            Country(name: "哥伦比亚", code: "57", index: "G"),
            Country(name: "科摩罗", code: "269", index: "K"),
            Country(name: "库克群岛", code: "682", index: "K"),
            Country(name: "哥斯达黎加", code: "506", index: "G"),
            Country(name: "克罗地亚", code: "385", index: "K"),
            Country(name: "库拉索", code: "599", index: "K"),
            Country(name: "塞浦路斯", code: "357", index: "S"),
            Country(name: "捷克", code: "420", index: "J"),
            Country(name: "刚果民主共和国", code: "243", index: "G"),
            Country(name: "丹麦", code: "45", index: "D"),
            Country(name: "吉布提", code: "253", index: "J"),
            Country(name: "多米尼克", code: "1767", index: "D"),
            Country(name: "多米尼加共和国", code: "1809", index: "D"),
            Country(name: "东帝汶", code: "670", index: "D"),
            Country(name: "厄瓜多尔", code: "593", index: "E"),
            Country(name: "埃及", code: "20", index: "E"),
            Country(name: "萨尔瓦多", code: "503", index: "S"),
            Country(name: "赤道几内亚", code: "240", index: "C"),
            Country(name: "厄立特里亚", code: "291", index: "E"),
            Country(name: "爱沙尼亚", code: "372", index: "A"),
            Country(name: "埃塞俄比亚", code: "251", index: "A"),
            Country(name: "法罗群岛", code: "298", index: "F"),
            Country(name: "斐济", code: "679", index: "F"),
            Country(name: "芬兰", code: "358", index: "F"),
            Country(name: "法国", code: "33", index: "F"),
            Country(name: "法属圭亚那", code: "594", index: "F"),
            Country(name: "法属波利尼西亚", code: "689", index: "F"),
            Country(name: "加蓬", code: "241", index: "J"),
            Country(name: "冈比亚", code: "220", index: "G"),
            Country(name: "格鲁吉亚", code: "995", index: "G"),
            Country(name: "德国", code: "49", index: "D"),
            Country(name: "加纳", code: "233", index: "J"),
            Country(name: "直布罗陀", code: "350", index: "Z"),
            Country(name: "希腊", code: "30", index: "X"),
            Country(name: "格陵兰岛", code: "299", index: "G"),
            Country(name: "格林纳达", code: "1473", index: "G"),
            Country(name: "瓜德罗普岛", code: "590", index: "G"),
            Country(name: "关岛", code: "1671", index: "G"),
            Country(name: "瓜地马拉", code: "502", index: "G"),
            Country(name: "几内亚", code: "224", index: "J"),
            Country(name: "几内亚比绍共和国", code: "245", index: "J"),
            Country(name: "圭亚那", code: "592", index: "J"),
            Country(name: "海地", code: "509", index: "H"),
            Country(name: "洪都拉斯", code: "504", index: "H"),
            Country(name: "中国香港", code: "852", index: "Z"),
            Country(name: "匈牙利", code: "36", index: "H"),
            Country(name: "冰岛", code: "354", index: "B"),
            Country(name: "印度", code: "91", index: "Y"),
            Country(name: "印度尼西亚", code: "62", index: "Y"),
            Country(name: "伊拉克", code: "964", index: "Y"),
            Country(name: "爱尔兰", code: "353", index: "Y"),
            Country(name: "以色列", code: "972", index: "Y"),
            Country(name: "意大利", code: "39", index: "Y"),
            Country(name: "象牙海岸", code: "225", index: "X"),
            Country(name: "牙买加", code: "1876", index: "Y"),
            Country(name: "日本", code: "81", index: "R"),
            Country(name: "约旦", code: "962", index: "Y"),
            Country(name: "哈萨克斯坦", code: "7", index: "H"),
            Country(name: "肯尼亚", code: "254", index: "K"),
            Country(name: "基里巴斯", code: "686", index: "J"),
            Country(name: "科威特", code: "965", index: "K"),
            Country(name: "吉尔吉斯斯坦", code: "996", index: "J"),
            Country(name: "老挝", code: "856", index: "L"),
            Country(name: "拉脱维亚", code: "371", index: "L"),
            Country(name: "黎巴嫩", code: "961", index: "L"),
            Country(name: "莱索托", code: "266", index: "L"),
            Country(name: "利比里亚", code: "231", index: "L"),
            Country(name: "利比亚", code: "218", index: "L"),
            Country(name: "列支敦士登", code: "423", index: "L"),
            Country(name: "立陶宛", code: "370", index: "L"),
            Country(name: "卢森堡", code: "352", index: "L"),
            Country(name: "中国澳门", code: "853", index: "Z"),
            Country(name: "马其顿", code: "389", index: "M"),
            Country(name: "马达加斯加", code: "261", index: "M"),
            Country(name: "马拉维", code: "265", index: "M"),
            Country(name: "马来西亚", code: "60", index: "M"),
            Country(name: "马尔代夫", code: "960", index: "M"),
            Country(name: "马里", code: "223", index: "M"),
            Country(name: "马耳他", code: "356", index: "M"),
            Country(name: "马提尼克", code: "596", index: "M"),
            Country(name: "毛里塔尼亚", code: "222", index: "M"),
            Country(name: "毛里求斯", code: "230", index: "M"),
            Country(name: "马约特", code: "269", index: "M"),
            Country(name: "墨西哥", code: "52", index: "M"),
            Country(name: "摩尔多瓦", code: "373", index: "M"),
            Country(name: "摩纳哥", code: "377", index: "M"),
            Country(name: "蒙古", code: "976", index: "M"),
            Country(name: "黑山", code: "382", index: "H"),
            Country(name: "蒙特塞拉特岛", code: "1664", index: "M"),
            Country(name: "摩洛哥", code: "212", index: "M"),
            Country(name: "莫桑比克", code: "258", index: "M"),
            Country(name: "缅甸", code: "95", index: "M"),
            Country(name: "纳米比亚", code: "264", index: "N"),
            Country(name: "尼泊尔", code: "977", index: "N"),
            Country(name: "荷兰", code: "31", index: "H"),
            Country(name: "新喀里多尼亚", code: "687", index: "X"),
            Country(name: "新西兰", code: "64", index: "X"),
            Country(name: "尼加拉瓜", code: "505", index: "N"),
            Country(name: "尼日尔", code: "227", index: "N"),
            Country(name: "尼日利亚", code: "234", index: "N"),
            Country(name: "挪威", code: "47", index: "N"),
            Country(name: "阿曼", code: "968", index: "A"),
            Country(name: "巴基斯坦", code: "92", index: "B"),
            Country(name: "帕劳", code: "680", index: "P"),
            Country(name: "巴勒斯坦", code: "970", index: "B"),
            Country(name: "巴拿马", code: "507", index: "B"),
            Country(name: "巴布亚新几内亚", code: "675", index: "B"),
            Country(name: "巴拉圭", code: "595", index: "B"),
            Country(name: "秘鲁", code: "51", index: "B"),
            Country(name: "菲律宾", code: "63", index: "P"),
            Country(name: "波兰", code: "48", index: "P"),
            Country(name: "葡萄牙", code: "351", index: "P"),
            Country(name: "波多黎各", code: "1787", index: "P"),
            Country(name: "卡塔尔", code: "974", index: "Q"),
            Country(name: "刚果共和国", code: "242", index: "G"),
            Country(name: "留尼汪", code: "262", index: "L"),
            Country(name: "罗马尼亚", code: "40", index: "L"),
            Country(name: "俄罗斯", code: "7", index: "L"),
            Country(name: "卢旺达", code: "250", index: "L"),
            Country(name: "圣基茨和尼维斯", code: "1869", index: "S"),
            Country(name: "圣露西亚", code: "1758", index: "S"),
            Country(name: "圣彼埃尔和密克隆岛", code: "508", index: "S"),
            Country(name: "圣文森特和格林纳丁斯", code: "1784", index: "S"),
            Country(name: "萨摩亚", code: "685", index: "S"),
            Country(name: "圣马力诺", code: "378", index: "S"),
            Country(name: "圣多美和普林西比", code: "239", index: "S"),
            Country(name: "沙特阿拉伯", code: "966", index: "S"),
            Country(name: "塞内加尔", code: "221", index: "S"),
            Country(name: "塞尔维亚", code: "381", index: "S"),
            Country(name: "塞舌尔", code: "248", index: "S"),
            Country(name: "塞拉利昂", code: "232", index: "S"),
            Country(name: "新加坡", code: "65", index: "X"),
            Country(name: "圣马丁岛（荷兰部分）", code: "1721", index: "S"),
            Country(name: "斯洛伐克", code: "421", index: "S"),
            Country(name: "斯洛文尼亚", code: "386", index: "S"),
            Country(name: "所罗门群岛", code: "677", index: "S"),
            Country(name: "索马里", code: "252", index: "S"),
            Country(name: "南非", code: "27", index: "N"),
            Country(name: "韩国", code: "82", index: "H"),
            Country(name: "西班牙", code: "34", index: "X"),
            Country(name: "斯里兰卡", code: "94", index: "S"),
            Country(name: "苏丹", code: "249", index: "S"),
            Country(name: "苏里南", code: "597", index: "S"),
            Country(name: "斯威士兰", code: "268", index: "S"),
            Country(name: "瑞典", code: "46", index: "R"),
            Country(name: "瑞士", code: "41", index: "R"),
            Country(name: "中国台湾", code: "886", index: "Z"),
            Country(name: "塔吉克斯坦", code: "992", index: "T"),
            Country(name: "坦桑尼亚", code: "255", index: "T"),
            Country(name: "泰国", code: "66", index: "T"),
            Country(name: "东帝汶", code: "670", index: "D"),
            Country(name: "多哥", code: "228", index: "D"),
            Country(name: "汤加", code: "676", index: "T"),
            Country(name: "特立尼达和多巴哥", code: "1868", index: "T"),
            Country(name: "突尼斯", code: "216", index: "T"),
            Country(name: "土耳其", code: "90", index: "T"),
            Country(name: "土库曼斯坦", code: "993", index: "T"),
            Country(name: "特克斯和凯科斯群岛", code: "1649", index: "T"),
            Country(name: "乌干达", code: "256", index: "W"),
            Country(name: "乌克兰", code: "380", index: "W"),
            Country(name: "阿拉伯联合酋长国", code: "971", index: "A"),
            Country(name: "英国", code: "44", index: "Y"),
            Country(name: "美国", code: "1", index: "M"),
            Country(name: "乌拉圭", code: "598", index: "W"),
            Country(name: "乌兹别克斯坦", code: "998", index: "W"),
            Country(name: "瓦努阿图", code: "678", index: "W"),
            Country(name: "委内瑞拉", code: "58", index: "W"),
            Country(name: "越南", code: "84", index: "Y"),
            Country(name: "英属处女群岛", code: "1340", index: "Y"),
            Country(name: "美属维尔京群岛", code: "1284", index: "M"),
            Country(name: "也门", code: "967", index: "Y"),
            Country(name: "赞比亚", code: "260", index: "Z"),
            Country(name: "津巴布韦", code: "263", index: "Z")
    ]
    var sections: [String] = []
    var countryGroups: [String: [Country]] = [:]
    var searchDataSource: [YHCountryMessage]?
    var viewModel: YHSelectCountryViewModel?

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "国家地区"
        viewModel = YHSelectCountryViewModel()
        setView()
        getData()
    }
    
    func getData() {
        countryGroups = getIndexedCountries()
        sections = sortedIndices()
        tableView.reloadData()
        
    }
    
    func sortedIndices() -> [String] {
        return getIndexedCountries().keys.sorted()
    }
    
    func getIndexedCountries() -> [String: [Country]] {
        var indexedCountries = [String: [Country]]()
        
        for country in countries {
            if indexedCountries[country.index] == nil {
                indexedCountries[country.index] = []
            }
            indexedCountries[country.index]?.append(country)
        }
        
        return indexedCountries
    }
    
    func setView() {
        view.backgroundColor = .white
        searchView = {
            let searchBar = UITextField()
            searchBar.font = .PFSC_R(ofSize: 14)
            searchBar.placeholder = "请输入国家地区"
            searchBar.backgroundColor = UIColor.contentBkgColor
            searchBar.keyboardType = .default
            searchBar.delegate = self
            searchBar.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 42))
            searchBar.leftViewMode = .always
            return searchBar
        }()
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 16)
            make.height.equalTo(42)
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHCountryTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 78)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
            make.left.right.equalTo(view)
        }
        
        searchTableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHCountryTableViewCell.self)
            tableView.isHidden = true
            return tableView
        }()
        view.addSubview(searchTableView)
        searchTableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 78)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
            make.left.right.equalTo(view)
        }
        
    }
}

extension YHSelectPhoneCountryViewController: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if textField.text == "" {
            filteredCountries = []
            tableView.isHidden = false
            searchTableView.isHidden = true
        } else {
            // 匹配逻辑
            filteredCountries = countries.filter { $0.name.contains(textField.text ?? "") }
            tableView.isHidden = true
            searchTableView.isHidden = false
        }
        self.tableView.reloadData()
        self.searchTableView.reloadData()
    }
}

extension YHSelectPhoneCountryViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView == searchTableView {
            return 1
        }
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == searchTableView {
            return filteredCountries.count
        }
        let index = sections[section]
        return countryGroups[index]?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHCountryTableViewCell.self)
        let index = sections[indexPath.section]
        if tableView == searchTableView {
            let country = filteredCountries[indexPath.row]
            cell.titleLabel.text = "\(country.name)"
            cell.messagelabel.text = "+\(country.code)"
        } else {
            if let country = countryGroups[index]?[indexPath.row] {
                cell.titleLabel.text = "\(country.name)"
                cell.messagelabel.text = "+\(country.code)"
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if tableView == searchTableView {
            return nil
        }
        return "  " + sections[section]
    }
    
    // MARK: - Section Index
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if tableView == searchTableView {
            return nil
        }
        return sections
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return index
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == searchTableView {
            let country = filteredCountries[indexPath.row]
            if let backLocationStringController = backLocationStringController {
                backLocationStringController(country)
                self.navigationController?.popViewController()
            }
        } else {
            let index = sections[indexPath.section]
            let country = countryGroups[index]?[indexPath.row] ?? Country(name: "", code: "", index: "")
            if let backLocationStringController = backLocationStringController {
                backLocationStringController(country)
                self.navigationController?.popViewController()
            }
        }
        
    }
}
