import SwiftUI

struct LoginView: View {
    @EnvironmentObject var viewModel: CallViewModel
    @State private var username: String = "Jared"
    @State private var selectedRole: Role = .caller
    @State private var serverIp: String = ""
    @State private var isServerFound: Bool = false
    @StateObject private var bonjourService = BonjourService()
    
    var body: some View {
        VStack(spacing: 20) {
            Text("BeMyEars")
                .font(.largeTitle)
                .fontWeight(.bold)
            
            TextField("Username", text: $username)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .autocapitalization(.none)
                .padding()
            
            HStack(spacing: 0) {
                Button(action: { selectedRole = .caller }) {
                    Text("Caller (Deaf User)")
                        .font(.subheadline)
                        .padding(.vertical, 10)
                        .frame(maxWidth: .infinity)
                        .background(selectedRole == .caller ? Color.blue : Color.gray.opacity(0.2))
                        .foregroundColor(selectedRole == .caller ? .white : .primary)
                }
                
                Button(action: { selectedRole = .interpreter }) {
                    Text("Interpreter")
                        .font(.subheadline)
                        .padding(.vertical, 10)
                        .frame(maxWidth: .infinity)
                        .background(selectedRole == .interpreter ? Color.blue : Color.gray.opacity(0.2))
                        .foregroundColor(selectedRole == .interpreter ? .white : .primary)
                }
            }
            .cornerRadius(8)
            .padding()
            .onChange(of: selectedRole) { _, newRole in
                if newRole == .caller {
                    username = "Jared"
                } else {
                    username = "Terp_01"
                }
            }
            
            Button(action: {
                guard !username.isEmpty else { return }
                
                // Save Server IP
                if !serverIp.isEmpty {
                    UserDefaults.standard.set(serverIp, forKey: "server_ip")
                }
                
                viewModel.login(username: username, role: selectedRole)
            }) {
                Text("Join")
                    .font(.headline)
                    .foregroundColor(.white)
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(Color.red)
                    .cornerRadius(10)
            }
            .padding()
            
            Spacer()
            
            VStack(alignment: .leading, spacing: 5) {
                Text(isServerFound ? "Backend Server IP was found." : "Backend Server IP")
                    .font(.caption)
                    .foregroundColor(isServerFound ? .green : .gray)
                TextField("Server IP", text: $serverIp)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .keyboardType(.numbersAndPunctuation)
            }
            .padding(.horizontal)
            .padding(.bottom)
        }
        .padding()
        .onAppear {
            bonjourService.start()
            
            if let savedIp = UserDefaults.standard.string(forKey: "server_ip") {
                serverIp = savedIp
            } else if let localIp = NetworkManager.getLocalIPAddress() {
                // Try to predict server IP based on local IP (same subnet)
                // e.g. 192.168.1.x -> 192.168.1.
                var components = localIp.split(separator: ".")
                if components.count == 4 {
                    components.removeLast()
                    serverIp = components.joined(separator: ".") + "."
                } else {
                    serverIp = localIp
                }
            }
        }
        .onReceive(bonjourService.$foundServer) { found in
            if let found = found {
                serverIp = found
                isServerFound = true
            }
        }
    }
}
