import SwiftUI
import SwiftData

struct TagRulesEditView: View {
    @Environment(\.dismiss) private var dismiss
    @StateObject private var viewModel = TagViewModel()
    @Query private var allSettings: [AppSettings]
    @State private var showPremium = false
    let tag: Tag

    private var language: AppLanguage {
        (allSettings.first?.languageEnum ?? .system).resolved()
    }

    private var isPremium: Bool {
        allSettings.first?.isPremium ?? false
    }

    var body: some View {
        NavigationStack {
            ZStack {
                Color.mealMoodBackground.ignoresSafeArea()

                ScrollView {
                    VStack(spacing: 24) {
                        // Tag header
                        HStack(spacing: 12) {
                            Circle()
                                .fill(Color(hex: tag.color))
                                .frame(width: 20, height: 20)
                            Text(tag.localizedName(language: language))
                                .font(.mealMoodH2)
                                .foregroundColor(.mealMoodTextPrimary)
                        }
                        .padding(.top, 8)

                        // Max per week
                        VStack(alignment: .leading, spacing: 12) {
                            HStack {
                                Text("tags_max_per_week")
                                    .font(.mealMoodBodyBold)
                                    .foregroundColor(.mealMoodTextPrimary)
                                Spacer()
                                Toggle("", isOn: $viewModel.useMaxLimit)
                                    .tint(.mealMoodCoral)
                                    .labelsHidden()
                            }

                            if viewModel.useMaxLimit {
                                HStack(spacing: 8) {
                                    ForEach(1...7, id: \.self) { num in
                                        Button {
                                            viewModel.maxPerWeek = num
                                            HapticManager.shared.selection()
                                        } label: {
                                            Text("\(num)")
                                                .font(.mealMoodSmall)
                                                .fontWeight(.semibold)
                                                .frame(width: 36, height: 36)
                                                .background(
                                                    viewModel.maxPerWeek == num
                                                        ? Color.mealMoodCoral
                                                        : Color.mealMoodSurface
                                                )
                                                .foregroundColor(
                                                    viewModel.maxPerWeek == num
                                                        ? .white
                                                        : .mealMoodTextPrimary
                                                )
                                                .cornerRadius(8)
                                                .overlay(
                                                    RoundedRectangle(cornerRadius: 8)
                                                        .stroke(Color(hex: "#E0E0E0"), lineWidth: viewModel.maxPerWeek == num ? 0 : 1)
                                                )
                                        }
                                    }
                                }

                                    Text("\(String(localized: "tags_max_per_week")): \(viewModel.maxPerWeek ?? 3)")
                                    .font(.mealMoodCaption)
                                    .foregroundColor(.mealMoodTextSecondary)
                            }
                        }
                        .padding(16)
                        .background(Color.mealMoodSurface)
                        .cornerRadius(14)

                        // No consecutive toggle
                        VStack(spacing: 0) {
                            HStack {
                                VStack(alignment: .leading, spacing: 4) {
                                    Text("tags_no_consecutive")
                                        .font(.mealMoodBodyBold)
                                        .foregroundColor(.mealMoodTextPrimary)
                                    Text("tags_no_consecutive_desc")
                                        .font(.mealMoodCaption)
                                        .foregroundColor(.mealMoodTextSecondary)
                                }
                                Spacer()
                                Toggle("", isOn: $viewModel.noConsecutive)
                                    .tint(.mealMoodCoral)
                                    .labelsHidden()
                                    .disabled(!isPremium)
                            }
                            .padding(16)
                        }
                        .background(Color.mealMoodSurface)
                        .cornerRadius(14)

                        // No duplicate in day toggle
                        VStack(spacing: 0) {
                            HStack {
                                VStack(alignment: .leading, spacing: 4) {
                                    Text("tags_no_duplicate")
                                        .font(.mealMoodBodyBold)
                                        .foregroundColor(.mealMoodTextPrimary)
                                    Text("tags_no_duplicate_desc")
                                        .font(.mealMoodCaption)
                                        .foregroundColor(.mealMoodTextSecondary)
                                }
                                Spacer()
                                Toggle("", isOn: $viewModel.noDuplicateInDay)
                                    .tint(.mealMoodCoral)
                                    .labelsHidden()
                                    .disabled(!isPremium)
                            }
                            .padding(16)
                        }
                        .background(Color.mealMoodSurface)
                        .cornerRadius(14)

                        // Meal type restriction
                        VStack(alignment: .leading, spacing: 12) {
                            Text("tags_restriction")
                                .font(.mealMoodBodyBold)
                                .foregroundColor(.mealMoodTextPrimary)

                            Picker("Restricción", selection: $viewModel.mealTypeRestriction) {
                                Text("tags_no_restriction").tag(nil as String?)
                                Text("tags_lunch_only").tag("lunch" as String?)
                                Text("tags_dinner_only").tag("dinner" as String?)
                            }
                            .pickerStyle(.segmented)
                            .disabled(!isPremium)
                        }
                        .padding(16)
                        .background(Color.mealMoodSurface)
                        .cornerRadius(14)

                        if !isPremium {
                            HStack(spacing: 8) {
                                Image(systemName: "star.circle")
                                Text("premium_limit_rules")
                                Spacer()
                                Button("settings_remove_ads") {
                                    showPremium = true
                                }
                            }
                            .font(.mealMoodCaption)
                            .foregroundColor(.mealMoodCoral)
                            .padding(12)
                            .background(Color.mealMoodSurface)
                            .cornerRadius(12)
                        }
                    }
                    .padding(24)
                }
            }
            .navigationTitle(tag.localizedName(language: language))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        viewModel.save()
                        dismiss()
                    } label: {
                        Image(systemName: "checkmark")
                            .fontWeight(.semibold)
                            .foregroundColor(.mealMoodCoral)
                    }
                }
            }
            .onAppear {
                viewModel.loadTag(tag)
            }
            .sheet(isPresented: $showPremium) {
                if let settings = allSettings.first {
                    NavigationStack { PremiumView(settings: settings) }
                }
            }
        }
    }
}
