//
//  SQDatePicker.swift
//  Allovoisins
//
//  Created by gabin Warnier de wailly on 13/12/2024.
//  Copyright © 2024 AlloVoisins. All rights reserved.
//

import SwiftUI

struct SQDatePickerView: View {
    var label: String
    var placeholder: String
    var error: Binding<SQFormFieldError>?
    var isDisabled: Bool
    var dateRange: ClosedRange<Date>?
    @Binding private var selectedDate: Date?
    @State private var showDatePicker: Bool = false

    init(_ label: String,
         placeholder: String,
         selectedDate: Binding<Date?> = .constant(Date()),
         error: Binding<SQFormFieldError>? = nil,
         isDisabled: Bool = false,
         dateRange: ClosedRange<Date>? = nil)
    {
        self.label = label
        self.placeholder = placeholder
        self._selectedDate = selectedDate
        self.error = error
        self.isDisabled = isDisabled
        self.dateRange = dateRange
    }

    var body: some View {
        ZStack {
            VStack(alignment: .leading, spacing: 4) {
                SQText(label)
                    .sqFont(.semiBold)
                    .sqColor(.sqNeutral(80))
                // TextField
                HStack(spacing: 4) {
                    TextField("", text: .constant(formattedDate(selectedDate)))
                        .font(.sq(.medium))
                        .foregroundStyle(Color.sqNeutral(isDisabled ? 60 : 100))
                        .tint(.sqNeutral(80))
                        .placeholder(when: selectedDate == nil) {
                            SQText(placeholder)
                                .sqColor(.sqNeutral(50))
                        }
                        .onChange(of: self.selectedDate) { _ in
                            error?.wrappedValue = .none
                        }
                        .submitLabel(.done)
                        .disabled(true)
                    SQIcon(.calendar, color: isDisabled ? .sqNeutral(40) : .sqNeutral(100))
                }
                .padding(16)
                .foregroundStyle(Color.sqNeutral())
                .background(isDisabled ? Color.sqNeutral(10) : .clear)
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .inset(by: 0.5)
                        .stroke(error?.wrappedValue.isInError ?? false ? .sqSemanticRed : isDisabled ? Color.sqNeutral(20) : Color.sqNeutral(30), lineWidth: 1)
                )
                HStack(spacing: 16) {
                    if let error = error?.wrappedValue, error.isInError {
                        HStack(spacing: 4) {
                            SQIcon(.circle_exclamation, customSize: 12, type: .solid, color: .sqSemanticRed)
                            SQText(error.message)
                                .sqSize(12)
                                .sqFont(.semiBold)
                                .sqColor(.sqSemanticRed)
                        }
                    }
                }
            }
        }
        .contentShape(.rect)
        .onTapGesture {
            if isDisabled == false {
                showDatePicker.toggle()
            }
        }
        .sheet(isPresented: $showDatePicker) {
            BottomSheetDatePicker(label: label, selectedDate: $selectedDate, dateRange: dateRange)
        }
    }

    private func formattedDate(_ date: Date?) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        guard let dateNotNil = date else { return "" }
        return formatter.string(from: dateNotNil)
    }
}

struct BottomSheetDatePicker: View {
    var label: String
    @Binding var selectedDate: Date?
    var dateRange: ClosedRange<Date>? = nil
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        VStack {
            SQText(label)
                .sqFont(.semiBold)
                .padding()

            DatePicker(
                "",
                selection: Binding(
                    get: { selectedDate ?? Date() },
                    set: { selectedDate = $0 }
                ),
                in: dateRange ?? Date.distantPast ... Date.distantFuture,
                displayedComponents: .date
            )
            .datePickerStyle(GraphicalDatePickerStyle())
            .labelsHidden()

            Spacer()

            SQButton("Valider") {
                if selectedDate == nil {
                    if let range = dateRange {
                        // Utiliser la borne inférieur (hier) qui est la date la plus récente autorisée
                        selectedDate = range.lowerBound
                    } else {
                        selectedDate = Date()
                    }
                }
                presentationMode.wrappedValue.dismiss()
            }
        }
        .padding()
        .presentationDetents([.medium])
    }
}

#Preview {
    SQDatePickerView("Date de naissance", placeholder: "01/01/1970", selectedDate: .constant(Date()))
}
