import SwiftUI

struct DeferPicker: View {
	let onDefer: (Date?) -> Void
	@Environment(\.dismiss) private var dismiss
	@State private var showDatePicker = false
	@State private var customDate = Date()

	var body: some View {
		VStack(spacing: 0) {
			Button {
				onDefer(Calendar.current.date(byAdding: .day, value: 1, to: Date()))
				dismiss()
			} label: {
				Label("Tomorrow", systemImage: "sunrise")
					.frame(maxWidth: .infinity, alignment: .leading)
			}
			.buttonStyle(.plain)
			.padding(.horizontal, 12)
			.padding(.vertical, 8)

			Divider()

			Button {
				onDefer(nextMonday())
				dismiss()
			} label: {
				Label("Next Week", systemImage: "calendar.badge.clock")
					.frame(maxWidth: .infinity, alignment: .leading)
			}
			.buttonStyle(.plain)
			.padding(.horizontal, 12)
			.padding(.vertical, 8)

			Divider()

			Button {
				showDatePicker.toggle()
			} label: {
				Label("Pick Date", systemImage: "calendar")
					.frame(maxWidth: .infinity, alignment: .leading)
			}
			.buttonStyle(.plain)
			.padding(.horizontal, 12)
			.padding(.vertical, 8)

			if showDatePicker {
				DatePicker(
					"Defer until",
					selection: $customDate,
					in: Date()...,
					displayedComponents: .date
				)
				.datePickerStyle(.graphical)
				.padding(.horizontal, 12)

				Button("Confirm") {
					onDefer(customDate)
					dismiss()
				}
				.buttonStyle(.borderedProminent)
				.padding(.horizontal, 12)
				.padding(.vertical, 8)
			}

			Divider()

			Button {
				onDefer(nil)
				dismiss()
			} label: {
				Label("Someday", systemImage: "moon.zzz")
					.frame(maxWidth: .infinity, alignment: .leading)
			}
			.buttonStyle(.plain)
			.padding(.horizontal, 12)
			.padding(.vertical, 8)
		}
		.frame(minWidth: 220)
		.padding(.vertical, 4)
	}

	/// Returns the next Monday at midnight.
	private func nextMonday() -> Date {
		let calendar = Calendar.current
		let today = Date()
		let weekday = calendar.component(.weekday, from: today)
		// Sunday=1, Monday=2, ..., Saturday=7
		// Days until next Monday
		let daysUntilMonday: Int
		if weekday == 1 {
			// Sunday → 1 day
			daysUntilMonday = 1
		} else if weekday == 2 {
			// Already Monday → next Monday = 7 days
			daysUntilMonday = 7
		} else {
			// Tuesday(3)→6, Wednesday(4)→5, Thursday(5)→4, Friday(6)→3, Saturday(7)→2
			daysUntilMonday = 9 - weekday
		}
		return calendar.date(byAdding: .day, value: daysUntilMonday, to: calendar.startOfDay(for: today))!
	}
}
