import ComponentLibrary
import ComposableArchitecture
import Foundation
import Localization
import SwiftUI

public struct HookFollowPill: View {
    let isFollowing: Bool
    let followTapped: () -> Void

    @State private var hideFollowButton: Bool

    public init(
        isFollowing: Bool = false,
        followTapped: @escaping () -> Void
    ) {
        self.isFollowing = isFollowing
        self.followTapped = followTapped
        self.hideFollowButton = isFollowing
    }

    public var body: some View {
        followButton
            .opacity(hideFollowButton ? 0 : 1)
            .scaleEffect(hideFollowButton ? 0.95 : 1)
            .animation(.easeInOut(duration: 0.2), value: hideFollowButton)
            .onChange(of: isFollowing) { oldValue, newValue in
                guard newValue != oldValue else { return }
                // Makes sure we also reset the button when the user unfollows
                // or if the network request fails
                hideFollowButton = newValue
            }
    }

    private var followButton: some View {
        Button {
            followTapped()
            hideFollowButton = true
        } label: {
            Text(L10n.FeatureProfile.follow)
                .typographyV1(.followPill)
                .foregroundStyle(.white)
                .padding(.horizontal, 8)
                .padding(.vertical, 2)
                .background {
                    Capsule()
                        .strokeBorder(.white, lineWidth: 1)
                }
        }
        .buttonStyle(ScaleButtonStyle())
    }
}

private extension TypographyV1 {
    static let followPill: TypographyV1 = .init(
        name: "Follow Pill",
        size: 12,
        style: .body,
        weight: .ppNeueMontrealMedium,
        kerning: 0.24,
        lineHeight: 18
    )
}
