import SwiftUI

struct FitnessTabView: View {
    @State private var selectedTab: FitnessTab = .today
    @State private var todayVM = TodayViewModel()
    @State private var showFoodSearch = false

    enum FitnessTab: String, CaseIterable {
        case today = "Today"
        case history = "History"
        case templates = "Templates"
        case goals = "Goals"
    }

    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // Custom segmented control
                tabBar

                // Content
                Group {
                    switch selectedTab {
                    case .today:
                        TodayView(viewModel: todayVM, showFoodSearch: $showFoodSearch)
                    case .history:
                        HistoryView()
                    case .templates:
                        TemplatesView(dateString: todayVM.dateString) {
                            Task { await todayVM.load() }
                        }
                    case .goals:
                        GoalsView()
                    }
                }
            }
            .background(Color.canvas)
            .navigationTitle("Fitness")
            .navigationBarTitleDisplayMode(.large)
            .sheet(isPresented: $showFoodSearch) {
                FoodSearchView(date: todayVM.dateString) {
                    Task { await todayVM.load() }
                }
            }
        }
    }

    private var tabBar: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 6) {
                ForEach(FitnessTab.allCases, id: \.rawValue) { tab in
                    Button {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            selectedTab = tab
                        }
                    } label: {
                        Text(tab.rawValue)
                            .font(.subheadline.weight(selectedTab == tab ? .semibold : .medium))
                            .foregroundStyle(selectedTab == tab ? Color.surface : Color.text3)
                            .padding(.horizontal, 16)
                            .padding(.vertical, 8)
                            .background(
                                selectedTab == tab
                                    ? Color.accentWarm
                                    : Color.surfaceSecondary
                            )
                            .clipShape(Capsule())
                    }
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 8)
        }
    }
}
