import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/constants/app_colors.dart';
import '../../../core/constants/app_typography.dart';
import '../../../core/utils/category_mapper.dart';
import '../../../core/utils/app_logger.dart';
import '../../providers/restaurant_provider.dart';
import '../../providers/settings_provider.dart';
import '../../widgets/category_selector.dart';
import '../../widgets/native_ad_placeholder.dart';
import 'manual_restaurant_input_screen.dart';
import 'widgets/restaurant_card.dart';
import 'widgets/add_restaurant_dialog.dart';

class RestaurantListScreen extends ConsumerStatefulWidget {
  const RestaurantListScreen({super.key});

  @override
  ConsumerState<RestaurantListScreen> createState() =>
      _RestaurantListScreenState();
}

class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
  final _searchController = TextEditingController();
  bool _isSearching = false;

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final searchQuery = ref.watch(searchQueryProvider);
    final selectedCategory = ref.watch(selectedCategoryProvider);
    final screenshotModeEnabled = ref
        .watch(screenshotModeEnabledProvider)
        .maybeWhen(data: (value) => value, orElse: () => false);
    final isFiltered = searchQuery.isNotEmpty || selectedCategory != null;
    final restaurantsAsync = ref.watch(sortedRestaurantsByDistanceProvider);

    return Scaffold(
      backgroundColor: isDark
          ? AppColors.darkBackground
          : AppColors.lightBackground,
      appBar: AppBar(
        title: _isSearching
            ? TextField(
                controller: _searchController,
                autofocus: true,
                style: const TextStyle(color: Colors.white),
                decoration: const InputDecoration(
                  hintText: '맛집 검색...',
                  hintStyle: TextStyle(color: Colors.white70),
                  border: InputBorder.none,
                ),
                onChanged: (value) {
                  ref.read(searchQueryProvider.notifier).state = value;
                },
              )
            : const Text('내 맛집 리스트'),
        backgroundColor: isDark
            ? AppColors.darkPrimary
            : AppColors.lightPrimary,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          if (_isSearching) ...[
            IconButton(
              icon: const Icon(Icons.close),
              onPressed: () {
                setState(() {
                  _isSearching = false;
                  _searchController.clear();
                  ref.read(searchQueryProvider.notifier).state = '';
                });
              },
            ),
          ] else ...[
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: () {
                setState(() {
                  _isSearching = true;
                });
              },
            ),
          ],
        ],
      ),
      body: Column(
        children: [
          // 카테고리 선택기
          Container(
            color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: CategorySelector(
              selectedCategory: selectedCategory,
              onCategorySelected: (category) {
                ref.read(selectedCategoryProvider.notifier).state = category;
              },
              showAllOption: true,
            ),
          ),
          // 맛집 목록
          Expanded(
            child: restaurantsAsync.when(
              data: (restaurantsData) {
                AppLogger.debug(
                  '[restaurant_list_ui] data received, filtered=$isFiltered',
                );
                var items = restaurantsData;

                if (isFiltered) {
                  // 검색 필터
                  if (searchQuery.isNotEmpty) {
                    final lowercaseQuery = searchQuery.toLowerCase();
                    items = items.where((item) {
                      final r = item.restaurant;
                      return r.name.toLowerCase().contains(lowercaseQuery) ||
                          (r.description?.toLowerCase().contains(
                                lowercaseQuery,
                              ) ??
                              false) ||
                          r.category.toLowerCase().contains(lowercaseQuery);
                    }).toList();
                  }

                  // 카테고리 필터
                  if (selectedCategory != null) {
                    items = items.where((item) {
                      final r = item.restaurant;
                      return r.category == selectedCategory ||
                          r.category.contains(selectedCategory) ||
                          CategoryMapper.normalizeNaverCategory(
                                r.category,
                                r.subCategory,
                              ) ==
                              selectedCategory ||
                          CategoryMapper.getDisplayName(r.category) ==
                              selectedCategory;
                    }).toList();
                  }
                }

                if (items.isEmpty) {
                  return _buildEmptyState(isDark);
                }

                const adInterval = 6; // 5리스트 후 1광고
                const adOffset = 5; // 1~5 리스트 이후 6 광고 시작
                final adCount = (items.length ~/ adOffset);
                final totalCount = items.length + adCount;

                return ListView.builder(
                  itemCount: totalCount,
                  itemBuilder: (context, index) {
                    final isAdIndex =
                        index >= adOffset &&
                        (index - adOffset) % adInterval == 0;
                    if (isAdIndex) {
                      return NativeAdPlaceholder(
                        enabled: !screenshotModeEnabled,
                        margin: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 8,
                        ),
                        height: 200, // 카드 높이와 비슷한 중간 사이즈
                      );
                    }

                    final adsBefore = index < adOffset
                        ? 0
                        : ((index - adOffset) ~/ adInterval) + 1;
                    final itemIndex = index - adsBefore;
                    final item = items[itemIndex];

                    return RestaurantCard(
                      restaurant: item.restaurant,
                      distanceKm: item.distanceKm,
                    );
                  },
                );
              },
              loading: () {
                AppLogger.debug('[restaurant_list_ui] loading...');
                return const Center(
                  child: CircularProgressIndicator(
                    color: AppColors.lightPrimary,
                  ),
                );
              },
              error: (error, stack) => Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.error_outline,
                      size: 64,
                      color: isDark
                          ? AppColors.darkError
                          : AppColors.lightError,
                    ),
                    const SizedBox(height: 16),
                    Text('오류가 발생했습니다', style: AppTypography.heading2(isDark)),
                    const SizedBox(height: 8),
                    Text(
                      error.toString(),
                      style: AppTypography.body2(isDark),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddOptions,
        backgroundColor: AppColors.lightPrimary,
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  Widget _buildEmptyState(bool isDark) {
    final selectedCategory = ref.watch(selectedCategoryProvider);
    final searchQuery = ref.watch(searchQueryProvider);
    final isFiltering = selectedCategory != null || searchQuery.isNotEmpty;

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            isFiltering ? Icons.search_off : Icons.restaurant_menu,
            size: 80,
            color: isDark
                ? AppColors.darkTextSecondary
                : AppColors.lightTextSecondary,
          ),
          const SizedBox(height: 16),
          Text(
            isFiltering ? '조건에 맞는 맛집이 없어요' : '아직 등록된 맛집이 없어요',
            style: AppTypography.heading2(isDark),
          ),
          const SizedBox(height: 8),
          Text(
            isFiltering
                ? selectedCategory != null
                      ? '선택한 카테고리에 해당하는 맛집이 없습니다'
                      : '검색 결과가 없습니다'
                : '+ 버튼을 눌러 맛집을 추가해보세요',
            style: AppTypography.body2(isDark),
          ),
          if (isFiltering) ...[
            const SizedBox(height: 16),
            TextButton(
              onPressed: () {
                ref.read(selectedCategoryProvider.notifier).state = null;
                ref.read(searchQueryProvider.notifier).state = '';
              },
              child: Text(
                '필터 초기화',
                style: TextStyle(color: AppColors.lightPrimary),
              ),
            ),
          ],
        ],
      ),
    );
  }

  void _showAddOptions() {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    showModalBottomSheet(
      context: context,
      backgroundColor: isDark ? AppColors.darkSurface : AppColors.lightSurface,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 40,
                height: 4,
                margin: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: isDark
                      ? AppColors.darkDivider
                      : AppColors.lightDivider,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              ListTile(
                leading: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: AppColors.lightPrimary.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.link, color: AppColors.lightPrimary),
                ),
                title: const Text('네이버 지도 링크로 추가'),
                subtitle: const Text('네이버 지도앱에서 공유한 링크 붙여넣기'),
                onTap: () {
                  Navigator.pop(context);
                  _addByNaverLink();
                },
              ),
              ListTile(
                leading: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: AppColors.lightPrimary.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.edit, color: AppColors.lightPrimary),
                ),
                title: const Text('직접 입력'),
                subtitle: const Text('가게 정보를 직접 입력하여 추가'),
                onTap: () {
                  Navigator.pop(context);
                  _addManually();
                },
              ),
              const SizedBox(height: 12),
            ],
          ),
        );
      },
    );
  }

  Future<void> _addByNaverLink() {
    return showDialog(
      context: context,
      builder: (context) =>
          const AddRestaurantDialog(mode: AddRestaurantDialogMode.naverLink),
    );
  }

  Future<void> _addManually() async {
    await Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => const ManualRestaurantInputScreen()),
    );
  }
}
