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/visit_record.dart';
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
import 'package:lunchpick/presentation/providers/visit_provider.dart';

class VisitRecordCard extends ConsumerWidget {
  final VisitRecord visitRecord;
  final VoidCallback? onTap;

  const VisitRecordCard({super.key, required this.visitRecord, this.onTap});

  String _formatTime(DateTime dateTime) {
    final hour = dateTime.hour.toString().padLeft(2, '0');
    final minute = dateTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  Widget _buildVisitIcon(bool isConfirmed, bool isDark) {
    return Container(
      width: 40,
      height: 40,
      decoration: BoxDecoration(
        color: isConfirmed
            ? AppColors.lightPrimary.withValues(alpha: 0.1)
            : Colors.orange.withValues(alpha: 0.1),
        shape: BoxShape.circle,
      ),
      child: Icon(
        isConfirmed ? Icons.check_circle : Icons.schedule,
        color: isConfirmed ? AppColors.lightPrimary : Colors.orange,
        size: 24,
      ),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final restaurantAsync = ref.watch(
      restaurantProvider(visitRecord.restaurantId),
    );

    return restaurantAsync.when(
      data: (restaurant) {
        if (restaurant == null) {
          return const SizedBox.shrink();
        }

        return Card(
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          child: InkWell(
            onTap: onTap,
            borderRadius: BorderRadius.circular(12),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  _buildVisitIcon(visitRecord.isConfirmed, isDark),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          restaurant.name,
                          style: AppTypography.body1(
                            isDark,
                          ).copyWith(fontWeight: FontWeight.bold),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Icon(
                              Icons.category_outlined,
                              size: 14,
                              color: isDark
                                  ? AppColors.darkTextSecondary
                                  : AppColors.lightTextSecondary,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              restaurant.category,
                              style: AppTypography.caption(isDark),
                            ),
                            const SizedBox(width: 8),
                            Icon(
                              Icons.access_time,
                              size: 14,
                              color: isDark
                                  ? AppColors.darkTextSecondary
                                  : AppColors.lightTextSecondary,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              _formatTime(visitRecord.visitDate),
                              style: AppTypography.caption(isDark),
                            ),
                          ],
                        ),
                        if (!visitRecord.isConfirmed) ...[
                          const SizedBox(height: 8),
                          Text(
                            '방문 확인이 필요합니다',
                            style: AppTypography.caption(isDark).copyWith(
                              color: Colors.orange,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                  PopupMenuButton<String>(
                    icon: Icon(
                      Icons.more_vert,
                      color: isDark
                          ? AppColors.darkTextSecondary
                          : AppColors.lightTextSecondary,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    color: isDark
                        ? AppColors.darkSurface
                        : AppColors.lightSurface,
                    onSelected: (value) async {
                      if (value == 'confirm' && !visitRecord.isConfirmed) {
                        await ref
                            .read(visitNotifierProvider.notifier)
                            .confirmVisit(visitRecord.id);
                      } else if (value == 'delete') {
                        // 삭제 확인 다이얼로그 표시
                        final confirmed = await showDialog<bool>(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: const Text('방문 기록 삭제'),
                            content: const Text('이 방문 기록을 삭제하시겠습니까?'),
                            actions: [
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: const Text('취소'),
                              ),
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(true),
                                style: TextButton.styleFrom(
                                  foregroundColor: AppColors.lightError,
                                ),
                                child: const Text('삭제'),
                              ),
                            ],
                          ),
                        );

                        if (confirmed == true) {
                          await ref
                              .read(visitNotifierProvider.notifier)
                              .deleteVisitRecord(visitRecord.id);
                        }
                      }
                    },
                    itemBuilder: (context) => [
                      if (!visitRecord.isConfirmed)
                        PopupMenuItem(
                          value: 'confirm',
                          child: Row(
                            children: [
                              const Icon(
                                Icons.check,
                                color: AppColors.lightPrimary,
                                size: 20,
                              ),
                              const SizedBox(width: 8),
                              Text('방문 확인', style: AppTypography.body2(isDark)),
                            ],
                          ),
                        ),
                      PopupMenuItem(
                        value: 'delete',
                        child: Row(
                          children: [
                            Icon(
                              Icons.delete_outline,
                              color: AppColors.lightError,
                              size: 20,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              '삭제',
                              style: AppTypography.body2(
                                isDark,
                              ).copyWith(color: AppColors.lightError),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
      loading: () => const Card(
        margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Center(child: CircularProgressIndicator()),
        ),
      ),
      error: (error, stack) => const SizedBox.shrink(),
    );
  }
}
