//
//  ExpandableMessageInput.swift
//  lichunWebsocket
//
//  Expandable text input with send button for chat
//

import SwiftUI

struct ExpandableMessageInput: View {
    @Binding var text: String
    let canSend: Bool
    let onSend: () -> Void

    @State private var textHeight: CGFloat = 40
    @FocusState private var isFocused: Bool

    private let minHeight: CGFloat = 40
    private let maxHeight: CGFloat = 120

    // MARK: - Body

    var body: some View {
        HStack(alignment: .bottom, spacing: AppSpacing.sm) {
            // Text input
            ZStack(alignment: .leading) {
                // Placeholder
                if text.isEmpty {
                    Text("Type a message...")
                        .font(.appBody)
                        .foregroundColor(AppColors.disabledText)
                        .padding(.horizontal, 12)
                        .padding(.vertical, 10)
                }

                // Dynamic text editor with height calculation
                TextEditor(text: $text)
                    .font(.appBody)
                    .foregroundColor(AppColors.primaryText)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 6)
                    .frame(minHeight: minHeight, maxHeight: maxHeight)
                    .scrollContentBackground(.hidden) // iOS 16+
                    .background(Color.clear)
                    .focused($isFocused)
                    .onChange(of: text) { _ in
                        updateTextHeight()
                    }
            }
            .background(
                // Adaptive input background
                LinearGradient(
                    colors: [
                        AppColors.surfaceElevated,
                        AppColors.surfaceSubtle
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
            )
            .cornerRadius(20) // More rounded for cozy feel
            .overlay(
                RoundedRectangle(cornerRadius: 20)
                    .strokeBorder(
                        isFocused ? AppColors.primary.opacity(0.25) : AppColors.secondaryText.opacity(0.12),
                        lineWidth: 1.5
                    )
            )
            .shadow(
                color: isFocused ? AppColors.primary.opacity(0.08) : Color.black.opacity(0.03),
                radius: isFocused ? 8 : 4,
                x: 0,
                y: 2
            )
            .animation(.spring(response: 0.3, dampingFraction: 0.7), value: isFocused)

            // Send button
            Button(action: {
                if canSend && !text.isEmpty {
                    // Haptic feedback
                    let generator = UIImpactFeedbackGenerator(style: .medium)
                    generator.impactOccurred()

                    onSend()
                }
            }) {
                ZStack {
                    Circle()
                        .fill(
                            canSend && !text.isEmpty
                                ? LinearGradient(
                                    colors: [AppColors.primary, AppColors.accent],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                                : LinearGradient(
                                    colors: [AppColors.disabledText],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                        )
                        .frame(width: 44, height: 44)

                    Image(systemName: "arrow.up")
                        .font(.system(size: 18, weight: .bold))
                        .foregroundColor(.white)
                }
            }
            .disabled(!canSend || text.isEmpty)
            .scaleEffect(canSend && !text.isEmpty ? 1.0 : 0.9)
            .animation(.spring(response: 0.3, dampingFraction: 0.6), value: canSend)
            .animation(.spring(response: 0.3, dampingFraction: 0.6), value: text.isEmpty)
        }
        .padding(.horizontal, AppSpacing.md)
        .padding(.vertical, AppSpacing.sm)
        .background(
            // Warm background with gentle shadow
            ZStack {
                AppColors.background

                // Top shadow for depth
                LinearGradient(
                    colors: [
                        Color.black.opacity(0.03),
                        Color.clear
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
                .frame(height: 20)
                .offset(y: -10)
            }
        )
    }

    // MARK: - Helper Methods

    private func updateTextHeight() {
        // Calculate the height based on content
        // This is a simple approximation
        let lineHeight: CGFloat = 22
        let lines = text.split(separator: "\n").count
        let estimatedLines = max(1, lines)

        let calculatedHeight = CGFloat(estimatedLines) * lineHeight + 16
        textHeight = min(max(minHeight, calculatedHeight), maxHeight)
    }
}

// MARK: - Preview
#Preview {
    VStack {
        Spacer()

        ExpandableMessageInput(
            text: .constant(""),
            canSend: true,
            onSend: {
                print("Send tapped")
            }
        )
    }
    .background(AppColors.background)
}
