import ComponentLibrary
import SwiftUI

public struct ExpandableSection<FocusValue: Hashable, Content: View>: View {
    let title: String
    @Binding var text: String
    let limit: Int
    let placeholder: String
    let focusBinding: FocusState<FocusValue?>.Binding
    let focusValue: FocusValue
    var isDisabled: Bool = false
    let footer: Content

    @State private var isExpanded: Bool = true

    private var warningThreshold: Int {
        Int(Double(limit) * 0.9)
    }

    private var isTypingMode: Bool {
        !text.isEmpty
    }

    public init(
        title: String,
        text: Binding<String>,
        limit: Int,
        placeholder: String,
        focusBinding: FocusState<FocusValue?>.Binding,
        focusValue: FocusValue,
        isDisabled: Bool = false,
        @ViewBuilder footer: () -> Content
    ) {
        self.title = title
        self._text = text
        self.limit = limit
        self.placeholder = placeholder
        self.focusBinding = focusBinding
        self.focusValue = focusValue
        self.isDisabled = isDisabled
        self.footer = footer()
    }

    public var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack(spacing: 8) {
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        isExpanded.toggle()
                    }
                }) {
                    HStack(spacing: 8) {
                        Image.FigmaMCP.chevronRight
                            .figmaMCPIconStyle(size: 12, semanticColor: Color.FigmaMCP.Semantic.foregroundPrimary)
                            .rotationEffect(.degrees(isExpanded ? 90 : 0))
                            .animation(.easeInOut(duration: 0.2), value: isExpanded)

                        VStack(alignment: .leading, spacing: 4) {
                            HStack(alignment: .bottom, spacing: 8) {
                                Text(title)
                                    .figmaMCPTypography(TypographyV1.FigmaMCP.smallTitle)
                                    .foregroundStyle(Color.FigmaMCP.Semantic.foregroundPrimary)
                                    .lineLimit(1)

                                if text.count >= warningThreshold {
                                    Text("\(text.count)")
                                        .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                                        .foregroundStyle(Color.FigmaMCP.Semantic.accentError)
                                }
                            }

                            if !isExpanded && !text.isEmpty {
                                Text(text.replacingOccurrences(of: "\n", with: " "))
                                    .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                                    .foregroundStyle(Color.FigmaMCP.Semantic.foregroundTertiary)
                                    .lineLimit(1)
                                    .multilineTextAlignment(.leading)
                            }
                        }
                        Spacer()
                    }
                    .contentShape(.rect)
                }
                .buttonStyle(PlainButtonStyle())
                .frame(maxWidth: .infinity)

                if isTypingMode && isExpanded && !isDisabled {
                    Button(action: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            text = ""
                            focusBinding.wrappedValue = nil
                        }
                    }) {
                        Image.FigmaMCP.clear
                            .figmaMCPIconStyle(size: 20, semanticColor: Color.FigmaMCP.Semantic.foregroundTertiary)
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 64)

            if isExpanded {
                VStack(alignment: .leading, spacing: 0) {
                    ZStack(alignment: .topLeading) {
                        if text.isEmpty {
                            Text(placeholder)
                                .figmaMCPTypography(TypographyV1.FigmaMCP.mediumRegular)
                                .foregroundStyle(Color.FigmaMCP.Semantic.fogDense)
                                .allowsHitTesting(false)
                                .frame(maxHeight: .infinity, alignment: .top)
                        }

                        TextField("", text: $text, axis: .vertical)
                            .figmaMCPTypography(TypographyV1.FigmaMCP.mediumRegular)
                            .foregroundStyle(Color.FigmaMCP.Semantic.foregroundPrimary)
                            .lineLimit(1 ... 10)
                            .textFieldStyle(PlainTextFieldStyle())
                            .focused(focusBinding, equals: focusValue)
                            .frame(maxHeight: .infinity, alignment: .top)
                            .disabled(isDisabled)
                            .opacity(isDisabled ? 0.5 : 1)
                            .onChange(of: text) { _, newValue in
                                if newValue.count > limit {
                                    text = String(newValue.prefix(limit))
                                }
                            }
                    }
                    .frame(minHeight: 60, maxHeight: .infinity, alignment: .top)
                }
                .padding(.horizontal, 16)
                .padding(.bottom, 16)

                footer
            }
        }
        .background(Color.FigmaMCP.Semantic.fogThin)
        .clipShape(RoundedRectangle(cornerRadius: 16))
    }
}

