//
//  ExploreView.swift
//  AppClientBaseSwift
//
//  Explore/Search screen view
//  View màn hình Khám phá/Tìm kiếm
//

import SwiftUI

// MARK: - Explore View
// View Khám phá

/// Explore tab main view
/// View chính của tab Khám phá
struct ExploreView: View {

    // MARK: - Properties

    /// Search text binding
    /// Binding text tìm kiếm
    @State private var searchText: String = ""

    /// Search results (placeholder)
    /// Kết quả tìm kiếm (placeholder)
    @State private var searchResults: [String] = []

    /// Selected category filter
    /// Filter category đã chọn
    @State private var selectedCategory: String?

    /// Available categories
    /// Các category có sẵn
    private let categories = [
        ("all", "Tất cả", "square.grid.2x2"),
        ("food", "Ẩm thực", "fork.knife"),
        ("coffee", "Cà phê", "cup.and.saucer"),
        ("shopping", "Mua sắm", "bag"),
        ("entertainment", "Giải trí", "sparkles"),
        ("travel", "Du lịch", "airplane"),
    ]

    // MARK: - Body

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: DesignSystem.spacingLG) {
                    // Category filter
                    // Filter category
                    categoryFilter

                    // Content based on search state
                    // Nội dung dựa trên trạng thái tìm kiếm
                    if searchText.isEmpty {
                        // Show browse content
                        // Hiển thị nội dung browse
                        browseContent
                    } else {
                        // Show search results
                        // Hiển thị kết quả tìm kiếm
                        searchResultsContent
                    }
                }
                .padding(.horizontal, DesignSystem.spacingMD)
            }
            .navigationTitle("tab_explore".localized)
            .searchable(text: $searchText, prompt: "explore_search_placeholder".localized)
        }
    }

    // MARK: - Subviews

    /// Category filter horizontal scroll
    /// Scroll ngang filter category
    private var categoryFilter: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: DesignSystem.spacingSM) {
                ForEach(categories, id: \.0) { category in
                    CategoryChip(
                        title: category.1,
                        icon: category.2,
                        isSelected: selectedCategory == category.0
                            || (selectedCategory == nil && category.0 == "all")
                    )
                    .onTapGesture {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            selectedCategory = category.0 == "all" ? nil : category.0
                        }
                    }
                }
            }
            .padding(.vertical, DesignSystem.spacingXS)
        }
    }

    /// Browse content when not searching
    /// Nội dung browse khi không tìm kiếm
    private var browseContent: some View {
        VStack(alignment: .leading, spacing: DesignSystem.spacingLG) {
            // Popular section
            // Phần phổ biến
            VStack(alignment: .leading, spacing: DesignSystem.spacingSM) {
                Text("explore_popular".localized)
                    .font(.headline)

                LazyVGrid(
                    columns: [
                        GridItem(.flexible()),
                        GridItem(.flexible()),
                    ], spacing: DesignSystem.spacingMD
                ) {
                    ForEach(0..<6, id: \.self) { index in
                        ExploreCard(index: index)
                    }
                }
            }

            // Nearby section
            // Phần gần đây
            VStack(alignment: .leading, spacing: DesignSystem.spacingSM) {
                HStack {
                    Text("explore_nearby".localized)
                        .font(.headline)

                    Spacer()

                    Button("common_see_all".localized) {
                        // Show all nearby
                    }
                    .font(.subheadline)
                }

                VStack(spacing: DesignSystem.spacingSM) {
                    ForEach(0..<3, id: \.self) { index in
                        NearbyRow(index: index)
                    }
                }
            }
        }
    }

    /// Search results content
    /// Nội dung kết quả tìm kiếm
    private var searchResultsContent: some View {
        VStack(spacing: DesignSystem.spacingMD) {
            if searchResults.isEmpty && !searchText.isEmpty {
                // Empty state
                // Trạng thái rỗng
                ContentUnavailableView(
                    "explore_no_results".localized,
                    systemImage: "magnifyingglass",
                    description: Text("explore_try_different".localized)
                )
                .padding(.top, DesignSystem.spacingXL)
            } else {
                // Results list
                // Danh sách kết quả
                ForEach(searchResults, id: \.self) { result in
                    Text(result)
                }
            }
        }
    }
}

// MARK: - Category Chip
// Chip Category

/// Category filter chip
/// Chip filter category
struct CategoryChip: View {
    let title: String
    let icon: String
    let isSelected: Bool

    var body: some View {
        HStack(spacing: DesignSystem.spacingXS) {
            Image(systemName: icon)
                .font(.caption)

            Text(title)
                .font(.subheadline)
        }
        .padding(.horizontal, DesignSystem.spacingMD)
        .padding(.vertical, DesignSystem.spacingSM)
        .background(isSelected ? Color.accentColor : Color.gray.opacity(0.15))
        .foregroundStyle(isSelected ? .white : .primary)
        .cornerRadius(DesignSystem.cornerRadiusCircle)
    }
}

// MARK: - Explore Card
// Card Explore

/// Explore grid card
/// Card grid explore
struct ExploreCard: View {
    let index: Int

    private let placeholderColors: [Color] = [
        .blue, .purple, .pink, .orange, .green, .mint,
    ]

    var body: some View {
        VStack(alignment: .leading, spacing: DesignSystem.spacingSM) {
            // Image placeholder
            // Placeholder ảnh
            RoundedRectangle(cornerRadius: DesignSystem.cornerRadiusMD)
                .fill(
                    LinearGradient(
                        colors: [
                            placeholderColors[index % placeholderColors.count].opacity(0.8),
                            placeholderColors[(index + 1) % placeholderColors.count].opacity(0.8),
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .frame(height: 120)
                .overlay(
                    Image(systemName: "photo")
                        .font(.title)
                        .foregroundStyle(.white.opacity(0.8))
                )

            // Info
            // Thông tin
            VStack(alignment: .leading, spacing: 2) {
                Text("Địa điểm \(index + 1)")
                    .font(.subheadline)
                    .fontWeight(.medium)
                    .lineLimit(1)

                HStack(spacing: 4) {
                    Image(systemName: "star.fill")
                        .font(.caption2)
                        .foregroundStyle(.yellow)

                    Text("4.\(5 - index % 3)")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }
        }
    }
}

// MARK: - Nearby Row
// Row Gần đây

/// Nearby location row
/// Row địa điểm gần đây
struct NearbyRow: View {
    let index: Int

    var body: some View {
        HStack(spacing: DesignSystem.spacingMD) {
            // Image
            RoundedRectangle(cornerRadius: DesignSystem.cornerRadiusSM)
                .fill(Color.accentColor.opacity(0.1))
                .frame(width: 64, height: 64)
                .overlay(
                    Image(systemName: "mappin.circle.fill")
                        .font(.title2)
                        .foregroundColor(.accentColor)
                )

            // Info
            // Thông tin
            VStack(alignment: .leading, spacing: DesignSystem.spacingXS) {
                Text("Địa điểm gần bạn \(index + 1)")
                    .font(.subheadline)
                    .fontWeight(.medium)

                Text("Cách \(index + 1).5 km")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }

            Spacer()

            // Distance badge
            // Badge khoảng cách
            VStack(alignment: .trailing, spacing: 2) {
                HStack(spacing: 2) {
                    Image(systemName: "star.fill")
                        .font(.caption2)
                        .foregroundStyle(.yellow)
                    Text("4.\(8 - index)")
                        .font(.caption)
                }

                Text("12\(index) đánh giá")
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }
        }
        .padding(DesignSystem.spacingSM)
        .background(Color.gray.opacity(0.1))
        .cornerRadius(DesignSystem.cornerRadiusMD)
    }
}

// MARK: - Preview

#Preview {
    ExploreView()
}
