import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lunchpick/core/constants/app_colors.dart';
import 'package:lunchpick/core/constants/app_typography.dart';
import 'package:lunchpick/domain/entities/restaurant.dart';
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
import 'package:lunchpick/presentation/providers/visit_provider.dart';
import 'edit_restaurant_dialog.dart';

class RestaurantCard extends ConsumerWidget {
  final Restaurant restaurant;
  final double? distanceKm;

  const RestaurantCard({super.key, required this.restaurant, this.distanceKm});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final lastVisitAsync = ref.watch(lastVisitDateProvider(restaurant.id));

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: InkWell(
        onTap: () => _showRestaurantDetail(context, isDark),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  // 카테고리 아이콘
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: AppColors.lightPrimary.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(
                      _getCategoryIcon(restaurant.category),
                      color: AppColors.lightPrimary,
                      size: 24,
                    ),
                  ),
                  const SizedBox(width: 12),

                  // 가게 정보
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    restaurant.name,
                                    style: AppTypography.heading2(isDark),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  const SizedBox(height: 4),
                                  Row(
                                    children: [
                                      Text(
                                        restaurant.category,
                                        style: AppTypography.body2(isDark),
                                      ),
                                      if (restaurant.subCategory !=
                                          restaurant.category) ...[
                                        Text(
                                          ' • ',
                                          style: AppTypography.body2(isDark),
                                        ),
                                        Text(
                                          restaurant.subCategory,
                                          style: AppTypography.body2(isDark),
                                        ),
                                      ],
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),

                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      _BadgesRow(
                        distanceKm: distanceKm,
                        needsAddressVerification:
                            restaurant.needsAddressVerification,
                        isDark: isDark,
                      ),
                      const SizedBox(height: 8),
                      // 더보기 버튼
                      PopupMenuButton<_RestaurantMenuAction>(
                        icon: Icon(
                          Icons.more_vert,
                          color: isDark
                              ? AppColors.darkTextSecondary
                              : AppColors.lightTextSecondary,
                        ),
                        offset: const Offset(0, 8),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        onSelected: (action) =>
                            _handleMenuAction(action, context, ref),
                        itemBuilder: (context) => [
                          const PopupMenuItem(
                            value: _RestaurantMenuAction.edit,
                            child: Row(
                              children: [
                                Icon(Icons.edit, color: AppColors.lightPrimary),
                                SizedBox(width: 8),
                                Text('수정'),
                              ],
                            ),
                          ),
                          const PopupMenuItem(
                            value: _RestaurantMenuAction.delete,
                            child: Row(
                              children: [
                                Icon(Icons.delete, color: AppColors.lightError),
                                SizedBox(width: 8),
                                Text('삭제'),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),

              if (restaurant.description != null) ...[
                const SizedBox(height: 12),
                Text(
                  restaurant.description!,
                  style: AppTypography.body2(isDark),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],

              const SizedBox(height: 12),

              // 주소
              Row(
                children: [
                  Icon(
                    Icons.location_on,
                    size: 16,
                    color: isDark
                        ? AppColors.darkTextSecondary
                        : AppColors.lightTextSecondary,
                  ),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      restaurant.roadAddress,
                      style: AppTypography.caption(isDark),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),

              // 마지막 방문일
              lastVisitAsync.when(
                data: (lastVisit) {
                  if (lastVisit != null) {
                    final daysSinceVisit = DateTime.now()
                        .difference(lastVisit)
                        .inDays;
                    return Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: Row(
                        children: [
                          Icon(
                            Icons.schedule,
                            size: 16,
                            color: isDark
                                ? AppColors.darkTextSecondary
                                : AppColors.lightTextSecondary,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            daysSinceVisit == 0
                                ? '오늘 방문'
                                : '$daysSinceVisit일 전 방문',
                            style: AppTypography.caption(isDark),
                          ),
                        ],
                      ),
                    );
                  }
                  return const SizedBox.shrink();
                },
                loading: () => const SizedBox.shrink(),
                error: (_, __) => const SizedBox.shrink(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  IconData _getCategoryIcon(String category) {
    switch (category) {
      case '한식':
        return Icons.rice_bowl;
      case '중식':
        return Icons.ramen_dining;
      case '일식':
        return Icons.set_meal;
      case '양식':
        return Icons.restaurant;
      case '카페':
        return Icons.coffee;
      case '분식':
        return Icons.fastfood;
      case '치킨':
        return Icons.egg;
      case '피자':
        return Icons.local_pizza;
      default:
        return Icons.restaurant_menu;
    }
  }

  void _showRestaurantDetail(BuildContext context, bool isDark) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: isDark
            ? AppColors.darkSurface
            : AppColors.lightSurface,
        title: Text(restaurant.name),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDetailRow(
              '카테고리',
              '${restaurant.category} > ${restaurant.subCategory}',
              isDark,
            ),
            if (restaurant.description != null)
              _buildDetailRow('설명', restaurant.description!, isDark),
            if (restaurant.phoneNumber != null)
              _buildDetailRow('전화번호', restaurant.phoneNumber!, isDark),
            _buildDetailRow('도로명 주소', restaurant.roadAddress, isDark),
            _buildDetailRow('지번 주소', restaurant.jibunAddress, isDark),
            if (restaurant.lastVisitDate != null)
              _buildDetailRow(
                '마지막 방문',
                '${restaurant.lastVisitDate!.year}년 ${restaurant.lastVisitDate!.month}월 ${restaurant.lastVisitDate!.day}일',
                isDark,
              ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('닫기'),
          ),
        ],
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, bool isDark) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: AppTypography.caption(isDark)),
          const SizedBox(height: 2),
          Text(value, style: AppTypography.body2(isDark)),
        ],
      ),
    );
  }

  void _handleMenuAction(
    _RestaurantMenuAction action,
    BuildContext context,
    WidgetRef ref,
  ) async {
    switch (action) {
      case _RestaurantMenuAction.edit:
        await showDialog<bool>(
          context: context,
          builder: (context) => EditRestaurantDialog(restaurant: restaurant),
        );
        break;
      case _RestaurantMenuAction.delete:
        final confirmed = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('맛집 삭제'),
            content: Text('${restaurant.name}을(를) 삭제하시겠습니까?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('취소'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                child: const Text(
                  '삭제',
                  style: TextStyle(color: AppColors.lightError),
                ),
              ),
            ],
          ),
        );

        if (confirmed == true) {
          await ref
              .read(restaurantNotifierProvider.notifier)
              .deleteRestaurant(restaurant.id);
        }
        break;
    }
  }
}

class _DistanceBadge extends StatelessWidget {
  final double distanceKm;
  final bool isDark;

  const _DistanceBadge({required this.distanceKm, required this.isDark});

  @override
  Widget build(BuildContext context) {
    final text = _formatDistance(distanceKm);
    final isFar = distanceKm * 1000 >= 2000;
    final Color bgColor;
    final Color textColor;

    if (isFar) {
      bgColor = isDark
          ? AppColors.darkError.withOpacity(0.15)
          : AppColors.lightError.withOpacity(0.15);
      textColor = AppColors.lightError;
    } else {
      bgColor = isDark
          ? AppColors.darkPrimary.withOpacity(0.12)
          : AppColors.lightPrimary.withOpacity(0.12);
      textColor = AppColors.lightPrimary;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.place, size: 16, color: textColor),
          const SizedBox(width: 4),
          Text(
            text,
            style: AppTypography.caption(
              isDark,
            ).copyWith(color: textColor, fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  String _formatDistance(double distanceKm) {
    final meters = distanceKm * 1000;
    if (meters >= 2000) {
      return '2.0km 이상';
    }
    if (meters >= 1000) {
      return '${distanceKm.toStringAsFixed(1)}km';
    }
    return '${meters.round()}m';
  }
}

enum _RestaurantMenuAction { edit, delete }

class _BadgesRow extends StatelessWidget {
  final double? distanceKm;
  final bool needsAddressVerification;
  final bool isDark;

  const _BadgesRow({
    required this.distanceKm,
    required this.needsAddressVerification,
    required this.isDark,
  });

  @override
  Widget build(BuildContext context) {
    final badges = <Widget>[];
    if (needsAddressVerification) {
      badges.add(_AddressVerificationChip(isDark: isDark));
    }
    if (distanceKm != null) {
      badges.add(_DistanceBadge(distanceKm: distanceKm!, isDark: isDark));
    }

    if (badges.isEmpty) return const SizedBox.shrink();

    return Wrap(
      spacing: 8,
      runSpacing: 4,
      alignment: WrapAlignment.end,
      children: badges,
    );
  }
}

class _AddressVerificationChip extends StatelessWidget {
  final bool isDark;

  const _AddressVerificationChip({required this.isDark});

  @override
  Widget build(BuildContext context) {
    final bgColor = isDark
        ? AppColors.darkError.withOpacity(0.12)
        : AppColors.lightError.withOpacity(0.12);
    final textColor = isDark ? AppColors.darkError : AppColors.lightError;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.error_outline, size: 16, color: textColor),
          const SizedBox(width: 4),
          Text(
            '주소확인',
            style: TextStyle(color: textColor, fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }
}
