import ComponentLibrary
import SwiftUI

/*
 Presents a timestamp that user can tap and edit.
 This is currently used in WaveformEditorControls, to present and allow the user
 to edit the start and end times of our clip selection.

 - The label presents the text: "extend from", "start at", etc.
 - The time is the current time of the clip selection. It's presented in 'MM:SS:MSMS' format.
 - The text field allows the user to edit the time in 'MM:SS' format once the user taps on it.
 - Tapping outside the textfield will submit the new time.
 */
public struct EditableTimestampField: View {
    let label: String
    let time: String
    @Binding var updatedTime: String
    let isLeftHandle: Bool
    var onSubmit: (String) -> Void
    var onTap: () -> Void
    var onFocus: () -> Void
    @FocusState var focusedField: WaveformEditorControls.Field?

    public var body: some View {
        VStack(spacing: 0) {
            Text(label)
                .typographyV1(.body1.size { _ in 8.0 }.lineHeight(8.0))
                .foregroundColor(Color.SemanticV1.textSecondary)
                .frame(width: 72, alignment: .trailing)
            ZStack {
                currentTimestamp
                timestampEntryTextField
            }
        }
        .frame(width: 72, alignment: .trailing)
        .padding(.leading, 6)
        .padding(.vertical, 4)
        .padding(.trailing, 6)
        .onTapGesture {
            focusedField = isLeftHandle ? .leftHandleTimestamp : .rightHandleTimestamp
        }
    }

    @ViewBuilder
    private var currentTimestamp: some View {
        Text(time)
            .typographyV1(.body1.size { _ in 17.0 }.lineHeight(15.0))
            .foregroundColor(Color.SemanticV1.textPrimary)
            .minimumScaleFactor(0.5)
            .frame(width: 72, alignment: .trailing)
            .opacity(focusedField == nil ? 1 : 0)
    }

    @ViewBuilder
    private var timestampEntryTextField: some View {
        TextField("00:00", text: $updatedTime)
            .typographyV1(.body1.size { _ in 17.0 }.lineHeight(15.0))
            .foregroundColor(Color.SemanticV1.textPrimary)
            .frame(width: 72, alignment: .trailing)
            .keyboardType(.numberPad)
            .multilineTextAlignment(.trailing)
            .onChange(of: updatedTime) { _, newValue in
                // Remove any colons from the input
                let digitsOnly = newValue.replacingOccurrences(of: ":", with: "")

                // Keep only the numeric characters
                let numbers = digitsOnly.filter { $0.isNumber }

                if !numbers.isEmpty {
                    // Pad with leading zeros to always have 4 digits
                    let paddedNumbers = String(format: "%04d", Int(numbers) ?? 0)
                    // Insert colon in the appropriate position
                    updatedTime = "\(paddedNumbers.prefix(2)):\(paddedNumbers.suffix(2))"
                }
            }
            .onSubmit {
                focusedField = nil
                onSubmit(updatedTime)
            }
            .focused($focusedField, equals: isLeftHandle ? .leftHandleTimestamp : .rightHandleTimestamp)
            .opacity(focusedField == nil ? 0 : 1)
            .tint(Color.SemanticV1.iconLink)
    }
}
