import SwiftUI
import EventKit

struct SettingsView: View {
    @ObservedObject var calendarService: CalendarService
    @Environment(\.dismiss) var dismiss

    var body: some View {
        VStack(spacing: 0) {
            HStack {
                Text("設定")
                    .font(.headline)
                    .padding()
                Spacer()
                Button("キャンセル") {
                    calendarService.loadDefaultSelectedCalendars()
                    dismiss()
                }
                .padding(.trailing, 8)
                Button("完了") {
                    calendarService.saveSelectedCalendars()
                    dismiss()
                }
                .keyboardShortcut(.defaultAction)
                .padding(.trailing)
            }
            .background(Color(nsColor: .windowBackgroundColor))

            Divider()

            VStack(alignment: .leading, spacing: 0) {
                Text("表示するカレンダー")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                    .padding(.horizontal)
                    .padding(.top)
                    .padding(.bottom, 8)

                if calendarService.availableCalendars.isEmpty {
                    Text("カレンダーがありません")
                        .foregroundColor(.secondary)
                        .padding()
                } else {
                    List {
                        ForEach(calendarService.availableCalendars, id: \.calendarIdentifier) { calendar in
                            CalendarRow(
                                calendar: calendar,
                                isSelected: calendarService.selectedCalendars.contains(calendar.calendarIdentifier)
                            ) { isSelected in
                                if isSelected {
                                    calendarService.selectedCalendars.insert(calendar.calendarIdentifier)
                                } else {
                                    calendarService.selectedCalendars.remove(calendar.calendarIdentifier)
                                }
                            }
                        }
                    }
                    .listStyle(.plain)
                }
            }
        }
        .frame(minWidth: 400, minHeight: 300)
    }
}

struct CalendarRow: View {
    let calendar: EKCalendar
    let isSelected: Bool
    let onToggle: (Bool) -> Void

    var body: some View {
        HStack {
            Circle()
                .fill(Color(calendar.color))
                .frame(width: 12, height: 12)
            Text(calendar.title)
                .font(.body)
            Spacer()
            Toggle("", isOn: .init(
                get: { isSelected },
                set: { onToggle($0) }
            ))
            .labelsHidden()
        }
    }
}
