import SwiftUI

struct ServerBottomBar: View {
    @Binding var environment: ServerEnvironment
    @Binding var localBaseURL: String
    let onServerChange: (String) -> Void

    @State private var expanded = false
    @State private var validationMessage: String?

    private var resolvedBaseURL: String {
        environment == .production
            ? ServerEnvironment.production.defaultBaseURL
            : ServerSettings.normalizedBaseURL(localBaseURL)
    }

    private var shortLabel: String {
        switch environment {
        case .production:
            return "w.tkmind.cn"
        case .local:
            let url = resolvedBaseURL
            if let host = URL(string: url)?.host {
                return host
            }
            return "本地"
        }
    }

    var body: some View {
        VStack(spacing: 0) {
            Divider()
            if expanded {
                expandedPanel
            }
            collapsedRow
        }
        .background(Color(.systemBackground))
    }

    private var collapsedRow: some View {
        Button {
            withAnimation(.easeInOut(duration: 0.2)) {
                expanded.toggle()
            }
        } label: {
            HStack(spacing: 8) {
                Image(systemName: "server.rack")
                    .font(.caption)
                    .foregroundStyle(Color(red: 0.31, green: 0.43, blue: 0.97))
                Text("服务器")
                    .font(.caption)
                    .foregroundStyle(.secondary)
                Text(environment.title)
                    .font(.caption.weight(.semibold))
                Text(shortLabel)
                    .font(.caption2)
                    .foregroundStyle(.secondary)
                    .lineLimit(1)
                Spacer(minLength: 0)
                Image(systemName: expanded ? "chevron.down" : "chevron.up")
                    .font(.caption2.weight(.semibold))
                    .foregroundStyle(.tertiary)
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 10)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
    }

    private var expandedPanel: some View {
        VStack(alignment: .leading, spacing: 10) {
            Picker("服务器", selection: $environment) {
                ForEach(ServerEnvironment.allCases) { item in
                    Text(item.title).tag(item)
                }
            }
            .pickerStyle(.segmented)
            .onChange(of: environment) { _, _ in
                validationMessage = nil
                applyServerChange()
            }

            if environment == .local {
                TextField("http://192.168.x.x:18003", text: $localBaseURL)
                    .textInputAutocapitalization(.never)
                    .autocorrectionDisabled()
                    .keyboardType(.URL)
                    .font(.caption)
                    .padding(.horizontal, 10)
                    .padding(.vertical, 8)
                    .background(Color(.secondarySystemBackground))
                    .clipShape(RoundedRectangle(cornerRadius: 8))
                    .onSubmit {
                        applyServerChange()
                    }

                Text("模拟器 127.0.0.1:18003；真机填电脑局域网 IP")
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }

            if let validationMessage {
                Text(validationMessage)
                    .font(.caption2)
                    .foregroundStyle(.red)
            }
        }
        .padding(.horizontal, 14)
        .padding(.bottom, 8)
    }

    private func applyServerChange() {
        validationMessage = nil
        let baseURL = resolvedBaseURL

        guard baseURL.hasPrefix("http://") || baseURL.hasPrefix("https://") else {
            validationMessage = "地址需以 http:// 或 https:// 开头"
            return
        }
        guard ServerSettings.apiBaseURL(for: baseURL).hasPrefix("http") else {
            validationMessage = "地址格式无效"
            return
        }

        ServerSettings.environment = environment
        if environment == .local {
            ServerSettings.localBaseURL = baseURL
        }
        onServerChange(baseURL)
    }
}

#Preview {
    ServerBottomBar(
        environment: .constant(.production),
        localBaseURL: .constant("http://127.0.0.1:18003"),
        onServerChange: { _ in }
    )
}
