import SwiftUI

struct CallWindowSetupView: View {
    @Environment(\.nahbarTheme) var theme
    @Environment(\.dismiss) var dismiss
    @ObservedObject var manager: CallWindowManager
    let isOnboarding: Bool
    let onDone: () -> Void

    @State private var startTime: Date = Date()
    @State private var endTime: Date = Date()

    var body: some View {
        VStack(spacing: 0) {
            if isOnboarding {
                RoundedRectangle(cornerRadius: 2)
                    .fill(Color.secondary.opacity(0.3))
                    .frame(width: 36, height: 4)
                    .padding(.top, 12)
            }

            ScrollView {
                VStack(alignment: .leading, spacing: 28) {

                    // Header
                    VStack(alignment: .leading, spacing: 8) {
                        Image(systemName: "phone.arrow.up.right")
                            .font(.system(size: 28, weight: .light))
                            .foregroundStyle(theme.accent)

                        Text("Gesprächszeit")
                            .font(.system(size: 24, weight: .light, design: theme.displayDesign))
                            .foregroundStyle(theme.contentPrimary)

                        Text("nahbar erinnert dich täglich in deinem Zeitfenster und schlägt einen Kontakt vor — mit Notizen, damit du vorbereitet bist.")
                            .font(.system(size: 15))
                            .foregroundStyle(theme.contentSecondary)
                            .fixedSize(horizontal: false, vertical: true)
                    }

                    // Time window
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "Zeitfenster", icon: "clock")

                        VStack(spacing: 0) {
                            HStack {
                                Text("Von")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                DatePicker("", selection: $startTime, displayedComponents: .hourAndMinute)
                                    .labelsHidden()
                                    .tint(theme.accent)
                                    .environment(\.locale, Locale(identifier: "de_DE"))
                            }
                            .padding(.horizontal, 14)
                            .padding(.vertical, 10)

                            RowDivider()

                            HStack {
                                Text("Bis")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                DatePicker("", selection: $endTime, displayedComponents: .hourAndMinute)
                                    .labelsHidden()
                                    .tint(theme.accent)
                                    .environment(\.locale, Locale(identifier: "de_DE"))
                            }
                            .padding(.horizontal, 14)
                            .padding(.vertical, 10)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                    }

                    // Weekday selector
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "Wochentage", icon: "calendar")

                        HStack(spacing: 6) {
                            ForEach(CallWindowManager.weekdayOrder, id: \.0) { weekday, label in
                                let isSelected = manager.selectedWeekdays.contains(weekday)
                                Button {
                                    if isSelected {
                                        // Mindestens einen Tag behalten
                                        if manager.selectedWeekdays.count > 1 {
                                            manager.selectedWeekdays.remove(weekday)
                                        }
                                    } else {
                                        manager.selectedWeekdays.insert(weekday)
                                    }
                                } label: {
                                    Text(label)
                                        .font(.system(size: 12, weight: isSelected ? .semibold : .regular))
                                        .frame(maxWidth: .infinity)
                                        .padding(.vertical, 9)
                                        .background(isSelected ? theme.accent : theme.surfaceCard)
                                        .foregroundStyle(isSelected ? .white : theme.contentSecondary)
                                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusTag))
                                        .overlay(
                                            RoundedRectangle(cornerRadius: theme.radiusTag)
                                                .stroke(theme.borderSubtle, lineWidth: isSelected ? 0 : 1)
                                        )
                                }
                            }
                        }
                    }

                    // Actions
                    VStack(spacing: 10) {
                        Button {
                            saveAndSchedule()
                            onDone()
                        } label: {
                            Text(isOnboarding ? "Einrichten" : "Speichern")
                                .font(.system(size: 16, weight: .medium))
                                .foregroundStyle(.white)
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 14)
                                .background(theme.accent)
                                .clipShape(RoundedRectangle(cornerRadius: theme.radiusTag))
                        }

                        if isOnboarding {
                            Button { onDone() } label: {
                                Text("Vielleicht später")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentSecondary)
                                    .frame(maxWidth: .infinity)
                            }
                        }
                    }
                }
                .padding(.horizontal, 24)
                .padding(.top, isOnboarding ? 20 : 16)
                .padding(.bottom, 40)
            }
        }
        .background(theme.backgroundPrimary.ignoresSafeArea())
        .navigationTitle(isOnboarding ? "" : "Gesprächszeit")
        .navigationBarTitleDisplayMode(.inline)
        .themedNavBar()
        .onAppear {
            startTime = timeDate(hour: manager.startHour, minute: manager.startMinute)
            endTime   = timeDate(hour: manager.endHour,   minute: manager.endMinute)
        }
    }

    private func timeDate(hour: Int, minute: Int) -> Date {
        Calendar.current.date(bySettingHour: hour, minute: minute, second: 0, of: Date()) ?? Date()
    }

    private func saveAndSchedule() {
        let cal = Calendar.current
        manager.startHour   = cal.component(.hour,   from: startTime)
        manager.startMinute = cal.component(.minute, from: startTime)
        manager.endHour     = cal.component(.hour,   from: endTime)
        manager.endMinute   = cal.component(.minute, from: endTime)
        manager.isEnabled   = true
        manager.scheduleNotifications()
    }
}
