import SwiftUI
import PhotosUI

struct HomeView: View {
    @Environment(AuthManager.self) private var auth
    @Environment(AppearanceManager.self) private var appearance
    @State private var vm = HomeViewModel()
    @State private var ringAnimated = false
    @Binding var selectedTab: Int

    var body: some View {
        ZStack {
            // Background
            if let bg = vm.backgroundImage {
                Image(uiImage: bg)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .ignoresSafeArea()
            } else {
                Color.canvas.ignoresSafeArea()
            }

            ScrollView {
                VStack(spacing: 16) {
                    // Top bar
                    HStack {
                        VStack(alignment: .leading, spacing: 2) {
                            if let name = auth.currentUser?.displayName {
                                Text("Hi, \(name)")
                                    .font(.title.weight(.bold))
                                    .foregroundStyle(vm.hasBackground ? .white : Color.textPrimary)
                            } else {
                                Text("Home")
                                    .font(.title.weight(.bold))
                                    .foregroundStyle(vm.hasBackground ? .white : Color.textPrimary)
                            }
                        }
                        Spacer()
                        Menu {
                            PhotosPicker(
                                selection: $vm.selectedPhoto,
                                matching: .images
                            ) {
                                Label("Change Background", systemImage: "photo")
                            }
                            if vm.hasBackground {
                                Button(role: .destructive) {
                                    vm.removeBackground()
                                } label: {
                                    Label("Remove Background", systemImage: "trash")
                                }
                            }
                            Divider()
                            Menu {
                                ForEach(AppearanceManager.Mode.allCases, id: \.self) { mode in
                                    Button {
                                        appearance.mode = mode
                                    } label: {
                                        Label(mode.label, systemImage: mode.icon)
                                    }
                                }
                            } label: {
                                Label("Appearance", systemImage: appearance.mode.icon)
                            }
                            Divider()
                            Button(role: .destructive) {
                                Task { await auth.logout() }
                            } label: {
                                Label("Sign Out", systemImage: "rectangle.portrait.and.arrow.right")
                            }
                        } label: {
                            Image(systemName: "person.circle.fill")
                                .font(.title2)
                                .foregroundStyle(vm.hasBackground ? .white : Color.accentWarm)
                        }
                    }
                    .padding(.horizontal)
                    .padding(.top, 16)

                    // Widget grid — half width, tap to go to fitness
                    HStack(spacing: 12) {
                        Button { selectedTab = 1 } label: {
                            calorieWidget
                        }
                        .buttonStyle(.plain)

                        Color.clear
                    }
                    .padding(.horizontal)

                    Spacer(minLength: 100)
                }
            }
        }
        .navigationBarHidden(true)
        .task {
            await vm.loadTodayData()
            withAnimation(.spring(response: 0.8, dampingFraction: 0.7)) {
                ringAnimated = true
            }
        }
        .onChange(of: vm.selectedPhoto) {
            Task { await vm.handlePhotoSelection() }
        }
    }

    private var calorieWidget: some View {
        VStack(spacing: 12) {
            Text("Calories")
                .font(.caption.weight(.semibold))
                .foregroundStyle(vm.hasBackground ? .white.opacity(0.7) : Color.textTertiary)
                .textCase(.uppercase)
                .tracking(0.5)

            // Animated ring
            ZStack {
                Circle()
                    .stroke(Color.emerald.opacity(0.15), lineWidth: 9)

                Circle()
                    .trim(from: 0, to: ringAnimated ? min(max(vm.calorieGoal > 0 ? vm.totalCalories / vm.calorieGoal : 0, 0), 1) : 0)
                    .stroke(Color.emerald, style: StrokeStyle(lineWidth: 9, lineCap: .round))
                    .rotationEffect(.degrees(-90))
                    .animation(.spring(response: 0.8, dampingFraction: 0.7), value: ringAnimated)

                VStack(spacing: 1) {
                    Text("\(Int(vm.totalCalories))")
                        .font(.system(size: 22, weight: .bold, design: .rounded))
                        .foregroundStyle(vm.hasBackground ? .white : Color.textPrimary)
                    Text("/ \(Int(vm.calorieGoal))")
                        .font(.system(size: 10, weight: .medium, design: .rounded))
                        .foregroundStyle(vm.hasBackground ? .white.opacity(0.6) : Color.textTertiary)
                }
            }
            .frame(width: 80, height: 80)

            let remaining = max(vm.calorieGoal - vm.totalCalories, 0)
            Text("\(Int(remaining)) left")
                .font(.caption2.weight(.medium))
                .foregroundStyle(vm.hasBackground ? .white.opacity(0.6) : Color.textTertiary)
        }
        .padding(16)
        .frame(maxWidth: .infinity)
        .aspectRatio(1, contentMode: .fit)
        .background {
            if vm.hasBackground {
                RoundedRectangle(cornerRadius: 16)
                    .fill(.ultraThinMaterial)
            } else {
                RoundedRectangle(cornerRadius: 16)
                    .fill(Color.surfaceCard)
                    .shadow(color: .black.opacity(0.05), radius: 8, y: 2)
            }
        }
    }
}
