import 'package:flutter/material.dart';

import '../../../../core/constants/app_colors.dart';
import '../../../../core/constants/app_typography.dart';
import '../../../../domain/entities/restaurant.dart';

class AddRestaurantSearchTab extends StatelessWidget {
  final TextEditingController queryController;
  final bool isSearching;
  final List<Restaurant> results;
  final Restaurant? selectedRestaurant;
  final VoidCallback onSearch;
  final ValueChanged<Restaurant> onResultSelected;
  final String? errorMessage;

  const AddRestaurantSearchTab({
    super.key,
    required this.queryController,
    required this.isSearching,
    required this.results,
    required this.selectedRestaurant,
    required this.onSearch,
    required this.onResultSelected,
    this.errorMessage,
  });

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: isDark
                ? AppColors.darkPrimary.withOpacity(0.1)
                : AppColors.lightPrimary.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(
                    Icons.search,
                    color: isDark
                        ? AppColors.darkPrimary
                        : AppColors.lightPrimary,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '상호명으로 검색',
                    style: AppTypography.body1(
                      isDark,
                    ).copyWith(fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                '가게 이름(필요 시 주소 키워드 포함)을 입력하면 네이버 로컬 검색 API로 결과를 불러옵니다.',
                style: AppTypography.body2(isDark),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        TextField(
          controller: queryController,
          decoration: InputDecoration(
            labelText: '상호명',
            prefixIcon: const Icon(Icons.storefront),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
          ),
          textInputAction: TextInputAction.search,
          onSubmitted: (_) => onSearch(),
        ),
        const SizedBox(height: 12),
        ElevatedButton.icon(
          onPressed: isSearching ? null : onSearch,
          icon: isSearching
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : const Icon(Icons.search),
          label: Text(isSearching ? '검색 중...' : '검색'),
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 14),
          ),
        ),
        if (errorMessage != null) ...[
          const SizedBox(height: 12),
          Text(
            errorMessage!,
            style: TextStyle(color: Colors.red[400], fontSize: 13),
          ),
        ],
        const SizedBox(height: 16),
        if (results.isNotEmpty)
          Container(
            decoration: BoxDecoration(
              color: isDark
                  ? AppColors.darkBackground
                  : AppColors.lightBackground,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: isDark ? AppColors.darkDivider : AppColors.lightDivider,
              ),
            ),
            child: ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: results.length,
              separatorBuilder: (_, __) => Divider(
                color: isDark ? AppColors.darkDivider : AppColors.lightDivider,
                height: 1,
              ),
              itemBuilder: (context, index) {
                final restaurant = results[index];
                final isSelected = selectedRestaurant?.id == restaurant.id;
                return ListTile(
                  onTap: () => onResultSelected(restaurant),
                  selected: isSelected,
                  selectedTileColor: isDark
                      ? AppColors.darkPrimary.withOpacity(0.08)
                      : AppColors.lightPrimary.withOpacity(0.08),
                  title: Text(
                    restaurant.name,
                    style: AppTypography.body1(
                      isDark,
                    ).copyWith(fontWeight: FontWeight.w600),
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (restaurant.roadAddress.isNotEmpty)
                        Text(
                          restaurant.roadAddress,
                          style: AppTypography.caption(isDark),
                        ),
                      Text(
                        restaurant.category,
                        style: AppTypography.caption(isDark).copyWith(
                          color: isDark ? Colors.grey[400] : Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                  trailing: isSelected
                      ? const Icon(
                          Icons.check_circle,
                          color: AppColors.lightPrimary,
                        )
                      : const Icon(Icons.chevron_right),
                );
              },
            ),
          )
        else
          Text(
            '검색 결과가 여기에 표시됩니다.',
            style: AppTypography.caption(
              isDark,
            ).copyWith(color: isDark ? Colors.grey[400] : Colors.grey[600]),
          ),
      ],
    );
  }
}
