//
//  WeatherView.swift
//  WeatherApp
//
//  Created by Azamat Tajiyev on 19.05.2025.
//

import SwiftUI

struct WeatherView: View {
    @StateObject private var viewModel: WeatherViewModel

    init(viewModel: WeatherViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    var body: some View {
        NavigationView {
            ZStack {
                forecastList
                if viewModel.isLoading && viewModel.forecasts.isEmpty {
                    loadingOverlay
                }

                if let error = viewModel.errorMessage {
                    errorOverlay(message: error)
                }
            }
            .navigationTitle("Weather Forecast")
        }
        .task {
            await viewModel.load()
        }
    }

    private var forecastList: some View {
        List(viewModel.forecasts, id: \.date) { forecast in
            ForecastRow(forecast: forecast)
        }
        .refreshable {
            await viewModel.load()
        }
    }

    private var loadingOverlay: some View {
        ZStack {
            Color.black.opacity(0.1).ignoresSafeArea()
            ProgressView("Loading...")
                .padding()
                .background(.thinMaterial)
                .cornerRadius(12)
        }
    }

    private func errorOverlay(message: String) -> some View {
        VStack {
            Spacer()
            Text(message)
                .foregroundColor(.red)
                .multilineTextAlignment(.center)
                .padding()
                .background(Color.white.opacity(0.9))
                .cornerRadius(8)
                .shadow(radius: 4)
                .padding()
        }
        .transition(.move(edge: .bottom))
    }
}
