//
//  NgaSettingView.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2024/05/21.
//
import SwiftUI
import CoreLocation
import UIKit

struct NgaSettingView: View {
    @ObservedObject var taskViewModel: TaskViewModel
    @ObservedObject var nga = SharingData.nga
    @ObservedObject var map = SharingData.map

    var body: some View {
        if nga.editType == EditNgaType.movePoint {
            NgaPointSetting(taskViewModel: taskViewModel)
        } else {
            NgaSetting(taskViewModel: taskViewModel)
        }
    }
}

struct NgaSetting: View {
    @ObservedObject var taskViewModel: TaskViewModel
    @ObservedObject var nga = SharingData.nga
    @ObservedObject var map = SharingData.map

    var body: some View {
        VStack(spacing: 0) {
            HStack {
                Text("Area Name").padding(.horizontal, 0)
                    .foregroundColor(nga.editNga!.isLock ? ColorSet.BodyDescriptiion.color : ColorSet.Body.color)
                TextField("", text: $taskViewModel.ngaName)
                    .foregroundColor(nga.editNga!.isLock ? ColorSet.BodyDescriptiion.color : ColorSet.Body.color)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .keyboardType(.emailAddress)
                    .frame(width: 150)
                    .disabled(nga.editNga!.isLock)

                let stateLock = nga.editNga!.points.count < 3 || nga.editNga!.name.isEmpty
                Button{
                    if var ngaData = nga.editNga {
                        ngaData.isLock.toggle()
                        nga.editNga = ngaData
                        nga.editType = EditNgaType.nonEdit
                    }
                }label:{
                    if nga.editNga!.isLock {
                        Image(systemName: "lock.fill")
                            .foregroundColor(Color.white)
                            .scaledToFit()
                            .frame(height: 18)
                    } else {
                        Image(systemName: "lock.open.fill")
                            .foregroundColor(stateLock ? ColorSet.BodyDescriptiion.color : ColorSet.Body.color)
                            .scaledToFit()
                            .frame(height: 18)
                    }
                }
                .disabled(stateLock)
                .padding(.horizontal, 30)
            }
            .onAppear(perform: {
                if let name = nga.editNga?.name {
                    taskViewModel.ngaName = name
                }
            })

//            HStack {
//                Button{
//                    var ngaData = nga.editNga!
//                    ngaData.isRunning.toggle()
//                    ngaData.passingCnt = 0
//                    nga.editNga = ngaData
//                }label:{
//                    HStack {
//                        Text("Watch")
//                            .font(FontStyle.EmphasisText.font)
//                            .foregroundColor(nga.editNga!.isLock ? ColorSet.BodyDescriptiion.color : ColorSet.Body.color)
//
//                        if nga.editNga!.isRunning {
//                            Image(systemName: "checkmark.square.fill")
//                                .resizable()
//                                .frame(width: 22, height: 22)
//                        } else {
//                            Image(systemName: "square")
//                                .resizable()
//                                .frame(width: 22, height: 22)
//                        }
//                    }
//                    .padding(.vertical, 17)
//                    .padding(.horizontal, 30)
//                }
//                .disabled(nga.editNga!.isLock)
//
//                Button{
//                    var ngaData = nga.editNga!
//                    ngaData.isLock.toggle()
//                    nga.editNga = ngaData
//                }label:{
//                    HStack {
//                        Text("Lock")
//                            .font(FontStyle.EmphasisText.font)
//                            .foregroundColor(ColorSet.Body.color)
//
//                        if nga.editNga!.isLock {
//                            Image(systemName: "checkmark.square.fill")
//                                .resizable()
//                                .frame(width: 22, height: 22)
//                        } else {
//                            Image(systemName: "square")
//                                .resizable()
//                                .frame(width: 22, height: 22)
//                        }
//                    }
//                    .padding(.horizontal, 30)
//                }
//            }

            HStack {
                let stateEdit = nga.editNga!.isLock ? true : nga.editType != EditNgaType.nonEdit
                Button(action: {
                    nga.editType = EditNgaType.addPoint
                }, label: {
                    Text("Edit polygon")
                        .font(FontStyle.DefaultText.font)
                        .padding()
                })
                .frame(width: 153, height: 42)
                .foregroundColor(ColorSet.ButtonText.color)
                .background(stateEdit ? ColorSet.SecondaryDisable.color : ColorSet.PrimaryActiveIcon.color)
                .cornerRadius(30)
                .padding(.vertical, 20)
                .disabled(stateEdit)

                let stateRegister = nga.editNga!.points.count < 3 || taskViewModel.ngaName.isEmpty
                Button(action: {
                    if var ngaData = nga.editNga {
                        ngaData.name = taskViewModel.ngaName
                        nga.editType = EditNgaType.registered
                        nga.editNgaArea(value: ngaData, type: NgaOperation.Change)
                    }
                    taskViewModel.viewMode = .NgaNotification
                }, label: {
                    Text("Register")
                        .font(FontStyle.DefaultText.font)
                        .padding()
                })
                .frame(width: 153, height: 42)
                .foregroundColor(ColorSet.ButtonText.color)
                .background(stateRegister ? ColorSet.SecondaryDisable.color : ColorSet.PrimaryActiveIcon.color)
                .cornerRadius(30)
                .padding(.vertical, 20)
                .disabled(stateRegister)
             }
        }
    }
}

/**
 * ポイント位置移動
 */
struct NgaPointSetting: View {
    @ObservedObject var taskViewModel: TaskViewModel
    @State private var selectLat = Array(repeating: 0, count: 4)
    @State private var selectLon = Array(repeating: 0, count: 4)

    var body: some View {
        ZStack {
            VStack(spacing: 0) {
                let no = getPointCoordinates()
                Text("No.\(no) Point Coordinates").padding(.horizontal, 0)

                Spacer()

                HStack {
                    Picker("", selection: $selectLat[0]) {
                        Text("N")
                        Text("S")
                    }.pickerStyle(.wheel)
                    Picker("", selection: $selectLat[1]) {
                        ForEach((0...89), id:\.self) { num in
                            Text("\(num)")
                        }
                    }.pickerStyle(.wheel)
                    Text("°").padding(.horizontal, 0)
                    Picker("", selection: $selectLat[2]) {
                        ForEach((0...59), id:\.self) { num in
                            Text("\(num)")
                        }
                    }.pickerStyle(.wheel)
                    Text(".").padding(.horizontal, 0)
                    Picker("", selection: $selectLat[3]) {
                        ForEach((0...999), id:\.self) { num in
                            Text("\(num)")
                        }
                    }.pickerStyle(.wheel)
                    Text("'").padding(.horizontal, 0)
                }
                .frame(width: 350, height: 60)
                .onChange(of: selectLat) { value in
                    changeLocationDouble()
                }

                HStack {
                    Picker("", selection: $selectLon[0]) {
                        Text("E")
                        Text("W")
                    }.pickerStyle(.wheel)
                    Picker("", selection: $selectLon[1]) {
                        ForEach((0...179), id:\.self) { num in
                            Text("\(num)")
                        }
                    }.pickerStyle(.wheel)
                    Text("°").padding(.horizontal, 0)

                    Picker("", selection: $selectLon[2]) {
                        ForEach((0...59), id:\.self) { num in
                            Text("\(num)")
                        }
                    }.pickerStyle(.wheel)
                    Text(".").padding(.horizontal, 0)
                    Picker("", selection: $selectLon[3]) {
                        ForEach((0...999), id:\.self) { num in
                            Text("\(num)")
                        }
                    }.pickerStyle(.wheel)
                    Text("'").padding(.horizontal, 0)
                }
                .frame(width: 350, height: 60)
                .onChange(of: selectLon) { value in
                    changeLocationDouble()
                }

                HStack {
                    Button(action: {
                        SharingData.nga.editType = EditNgaType.deletePoint
                        SharingData.map.isMapFree = true
                    }, label: {
                        Text("Delete")
                            .font(FontStyle.DefaultText.font)
                            .padding()
                    })
                    .frame(width: 153, height: 42)
                    .foregroundColor(ColorSet.ButtonText.color)
                    .background(ColorSet.PrimaryActiveIcon.color)
                    .cornerRadius(30)
                    .padding(.vertical, 20)

                    Button(action: {
                        SharingData.nga.editType = EditNgaType.addPoint
                    }, label: {
                        Text("Set")
                            .font(FontStyle.DefaultText.font)
                            .padding()
                    })
                    .frame(width: 153, height: 42)
                    .foregroundColor(ColorSet.ButtonText.color)
                    .background(ColorSet.PrimaryActiveIcon.color)
                    .cornerRadius(30)
                    .padding(.vertical, 20)
                }
            }
        }
        .onAppear(perform: {
            changeLocationArray()
        })
        .onChange(of: selectLat) { newValue in
            changeLocationDouble()
        }
    }

    /**
     * Picker情報用に位置情報を分解
     */
    func changeLocationArray() {
        if let no = SharingData.nga.selectPoint {
            if let location = SharingData.nga.editNga?.points[no] {
                selectLat = LocationCalculation.latDegtoInt(lat: location.latitude)
                selectLon = LocationCalculation.lonDegtoInt(lon: location.longitude)
            }
        }
    }

    /**
     * Picker情報から位置情報に変換
     */
    func changeLocationDouble() {
        if let no = SharingData.nga.selectPoint {
            var location = SharingData.nga.editNga!.points[no]

            location.latitude = LocationCalculation.latInttoDouble(lat: selectLat)!
            location.longitude = LocationCalculation.lonInttoDouble(lon: selectLon)!
            SharingData.nga.editNga!.points[no] = location
            SharingData.nga.targetLocation = location
        }
    }

    func getPointCoordinates() -> Int {
        var selectPoint = 0
        if let no = SharingData.nga.selectPoint {
            selectPoint = no + 1
        }

        return selectPoint
    }
}

#Preview {
    NgaSettingView(taskViewModel: TaskViewModel())
}

#Preview {
    NgaSetting(taskViewModel: TaskViewModel())
}

#Preview {
    NgaPointSetting(taskViewModel: TaskViewModel())
}
