import APIClient
import ComponentLibrary
import ComposableArchitecture
import Localization
import SwiftUI

public struct SimpleModeView: View {
    @Bindable var store: StoreOf<BlendedCreatePromptBuilder>
    @FocusState private var focusedField: BlendedCreatePromptBuilder.FocusedField?
    private let getRandomPromptAction: () -> Void

    @State var lastLyricsMode: BlendedCreatePrompt.LyricsMode = .auto

    private var instrumentalToggleLyricsModeBinding: Binding<Bool> {
        Binding<Bool>(
            get: { store.prompt.lyricsMode == .instrumental },
            set: { newValue in
                withAnimation {
                    if newValue {
                        self.lastLyricsMode = store.prompt.lyricsMode
                        store.prompt.lyricsMode = .instrumental
                    } else if store.prompt.lyricsMode == .instrumental {
                        store.prompt.lyricsMode = self.lastLyricsMode
                    }
                }
            }
        )
    }

    public init(
        store: StoreOf<BlendedCreatePromptBuilder>,
        getRandomPromptAction: @escaping () -> Void
    ) {
        self.store = store
        self.getRandomPromptAction = getRandomPromptAction
    }

    public var body: some View {
        ScrollViewReader { proxy in
            FadingEdgesScrollView {
                VStack(spacing: 10) {
                    // !! NOTE: We've disabled audio uploads for Simple Mode for the time being
//                    if let audioRecording = store.prompt.audioRecording {
//                        var isSelected: Bool {
//                            guard case .createStyle = store.destination else { return false }
//                            return true
//                        }
//
//                        AudioUploadDetailView(
//                            audioRecording: audioRecording,
//                            uploadState: store.audioUploadState,
//                            imageUrl: store.imageUrl,
//                            isPlaying: store.isPlaying,
//                            isPlayButtonDisabled: store.isPlayButtonDisabled,
//                            elapsedTime: store.elapsedTime.seconds,
//                            totalTime: audioRecording.duration,
//                            elapsed: store.clipDuration,
//                            playPause: { store.send(.audio(.didTapTogglePlay)) },
//                            delete: { store.send(.audio(.didTapDeleteClip)) },
//                            selectedStyle: store.prompt.audioCreateStyle,
//                            didTapCreateStyle: { store.send(.audio(.didTapCreateStyleButton)) }
//                        )
//                    }

                    descriptionEntryView

                    lyricsView
                        .animation(.default, value: store.prompt.lyricsMode)
                }
            }
            .scrollBounceBehavior(.basedOnSize)
            .scrollClipDisabled()
            .bind($store.focusedField, to: $focusedField)
            .onChange(of: focusedField) { _, field in
                switch field {
                case .simple(let simpleField):
                    let anchor: UnitPoint = switch simpleField {
                    case .description:
                        .bottom
                    case .lyrics:
                        .top
                    }
                    withAnimation {
                        proxy.scrollTo(simpleField, anchor: anchor)
                    }

                default:
                    break
                }
            }
            .onTapGesture { self.dismissKeyboard() }
            .task { store.send(.simple(.task)) }
        }
    }

    @ViewBuilder
    private var descriptionEntryView: some View {
        VStack(alignment: .leading) {
            // Invisible spacer that acts as an anchor reference
            Color.clear
                .frame(height: 1)
                .id(BlendedCreatePromptBuilder.FocusedField.Simple.description)

            Button {
                store.send(.simple(.didTapGetRandomDescription), animation: .bouncy)
                UIImpactFeedbackGenerator(style: .medium).impactOccurred()
            } label: {
                Image.Icon.dice
                    .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                    .frame(width: 16, height: 16)
            }
            .padding(10)
            .buttonStyle(ScaleButtonStyle(scaleAmount: 0.9))
            .zIndex(1)

            CharacterLimitedTextField(text: $store.prompt.description, axis: .vertical, characterLimit: store.descriptionCharCountLimit)
                .textFieldStyle(BlendedTextFieldStyle(placeholders: [
                    L10n.FeatureCreateClip.promptPlaceholder1,
                    L10n.FeatureCreateClip.promptPlaceholder2,
                    L10n.FeatureCreateClip.promptPlaceholder3,
                ], typography: .bodyLarge, placeholderTextColor: Color.SemanticV2.foregroundPrimary))
                .lineLimit(4 ... 8)
                .fixedSize(horizontal: false, vertical: true)
                .focused($focusedField, equals: .simple(.description))
                .clipShape(.rect)
                .padding(10)

            Spacer()

            if store.prompt.description.count > Int(Float(store.descriptionCharCountLimit) * store.charCountDisplayThreshold) {
                HStack {
                    Spacer()

                    CharCountV2(text: store.prompt.description, limit: store.descriptionCharCountLimit)
                }
            }

            // Invisible spacer that acts as an anchor reference
            Color.clear
                .frame(height: 1)
                .id(BlendedCreatePromptBuilder.FocusedField.Simple.lyrics)

            recommendedDescriptionTags
        }
        .padding(10)
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .background { Color.SemanticV2.backgroundSecondary }
        .clipShape(RoundedRectangle(cornerRadius: 20))
    }

    @ViewBuilder
    private var recommendedDescriptionTags: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 6) {
                // Show refresh button first if we have any tags at all
                if !store.recommendedDescriptionTags.isEmpty {
                    Button {
                        store.send(.simple(.didTapRefreshRecommendedDescriptionTags), animation: .easeInOut)
                        UIImpactFeedbackGenerator(style: .light).impactOccurred()
                    } label: {
                        Circle()
                            .fill(.clear)
                            .stroke(Color.SemanticV2.borderSecondary, lineWidth: 1)
                            .frame(width: 44, height: 44)
                            .overlay {
                                Image.Icon.refresh
                                    .resizable()
                                    .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                                    .frame(width: 14, height: 14)
                            }
                    }
                    .buttonStyle(ScaleButtonStyle(scaleAmount: 0.9))
                }

                // Tags
                ForEach(store.recommendedDescriptionTags, id: \.self) { style in
                    Button {
                        store.send(.simple(.didSelectDescriptionTag(style)), animation: .easeInOut)
                        UIImpactFeedbackGenerator(style: .medium).impactOccurred()
                    } label: {
                        Text(style)
                            .typographyV1(.subtitleSmallNew)
                            .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                            .padding(.horizontal, 12)
                            .frame(height: 44)
                            .background {
                                Capsule()
                                    .fill(.clear)
                                    .stroke(Color.SemanticV2.borderSecondary, lineWidth: 1)
                            }
                    }
                    .buttonStyle(ScaleButtonStyle(scaleAmount: 0.9))
                }
            }
        }
        .scrollBounceBehavior(.basedOnSize)
        .scrollClipDisabled(true)
    }

    @ViewBuilder
    public var lyricsView: some View {
        VStack {
            // Header
            HStack {
                Button {
                    UIImpactFeedbackGenerator(style: .medium).impactOccurred()
                    store.send(.simple(.didToggleWriteLyricsExpanded), animation: .default)
                } label: {
                    // Write lyrics toggle
                    HStack {
                        if store.prompt.lyricsMode == .write {
                            Circle()
                                .foregroundStyle(Color.SemanticV2.backgroundGlassDense)
                                .overlay {
                                    Image.Icon.close
                                        .resizable()
                                        .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                                        .frame(width: 18, height: 18)
                                }
                                .frame(width: 24, height: 24)
                                .buttonStyle(ScaleButtonStyle(scaleAmount: 0.9))
                        } else {
                            Image.Icon.plus
                                .resizable()
                                .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                                .frame(width: 18, height: 18)
                                .clipShape(.rect)
                        }

                        Text(L10n.FeatureCreateClip.lyrics)
                            .typographyV1(.subtitleMedium)
                            .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                            .frame(maxWidth: .infinity, alignment: .leading)
                    }
                    .padding(.horizontal, 10)
                    .frame(height: 46)
                }

                // isInstrumental toggle
                HStack(spacing: 0) {
                    Text(L10n.FeatureCreateClip.instrumental)
                        .typographyV1(.subtitleMedium)
                        .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                        .frame(maxWidth: .infinity, alignment: .leading)

                    Toggle("", isOn: instrumentalToggleLyricsModeBinding)
                        .toggleStyle(.switch)
                        .tint(Color.orange)
                        .scaleEffect(0.7)
                        .labelsHidden() // SwiftUI toggles automatically align to their parent's trailing edge without this
                }
                .padding(.leading, 20)
                .padding(.trailing, 10)
                .frame(height: 46)
            }

            if store.prompt.lyricsMode == .write {
                lyrics
                    .padding(.horizontal, 5)

                HStack {
                    generateLyricsButton
                        .frame(height: 44)

                    Spacer()
                }
                .padding(5)
            }
        }
        .modifier(if: store.prompt.lyricsMode == .write) { content in
            content
                .padding(5)
        }
        .background {
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.SemanticV2.backgroundSecondary)
        }
    }

    private var lyrics: some View {
        CharacterLimitedTextEditor(
            placeholder: L10n.FeatureCreateClip.blendedCreateLyricsPlaceholder,
            text: $store.prompt.lyrics,
            characterLimit: store.lyricsCharCountLimit
        )
        .focused($focusedField, equals: .simple(.lyrics))
        .typographyV1(.bodyMedium)
        .foregroundStyle(Color.SemanticV2.foregroundPrimary)
        .tint(.SemanticV2.accentBrand)
        .padding(.horizontal, 15)
        .padding(.top, 15)
        .padding(.bottom, 10)
        .frame(minHeight: 120, maxHeight: 240)
        .background {
            RoundedRectangle(cornerRadius: 10)
                .fill(.clear)
                .strokeBorder(Color.SemanticV2.borderPrimary, lineWidth: 1)
        }
        .disabled(store.isGeneratingLyrics)
        .opacity(store.isGeneratingLyrics ? 0.5 : 1)
    }

    @ViewBuilder
    private var generateLyricsButton: some View {
        Button {
            store.send(.simple(.didTapGenerateLyrics))
            UIImpactFeedbackGenerator(style: .medium).impactOccurred()
        } label: {
            HStack {
                if store.isGeneratingLyrics {
                    ProgressView()
                }

                Text(store.generateLyricsButtonText)
                    .typographyV1(.subtitleSmallNew)
                    .foregroundStyle(Color.SemanticV2.foregroundPrimary)
                    .padding(.vertical, 10)
                    .padding(.horizontal, 12)
                    .background(Color.SemanticV2.backgroundGlassThin)
                    .cornerRadius(24)
            }
        }
        .disabled(store.isGeneratingLyrics)
        .buttonStyle(.plain)
    }
}
