import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../shared/data/local/app_database.dart';
import '../../data/repositories/quest_repository.dart';

class QuestItem extends ConsumerStatefulWidget {
  final QuestCollection quest;

  const QuestItem({
    super.key,
    required this.quest,
  });

  @override
  ConsumerState<QuestItem> createState() => _QuestItemState();
}

class _QuestItemState extends ConsumerState<QuestItem> {
  bool _isClaiming = false;

  Future<void> _handleClaim() async {
    setState(() => _isClaiming = true);
    try {
      final questRepo = ref.read(questRepositoryProvider);
      await questRepo.claimQuest(widget.quest.id);

      if (mounted) {
        final l10n = AppLocalizations.of(context)!;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.check_circle, color: AppTheme.successColor),
                const SizedBox(width: 8),
                Text(l10n.questRewardCollected(widget.quest.rewardXP)),
              ],
            ),
            backgroundColor: Colors.black87,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Error: $e')));
      }
    } finally {
      if (mounted) setState(() => _isClaiming = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final progress =
        (widget.quest.currentValue / widget.quest.targetValue).clamp(0.0, 1.0);
    final isComplete = widget.quest.isCompleted;
    final isClaimed = widget.quest.isClaimed;

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: isComplete && !isClaimed
            ? const BorderSide(color: AppTheme.successColor, width: 1)
            : BorderSide.none,
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Header
            Row(
              children: [
                Icon(
                  _getIconForType(widget.quest.type),
                  color: isComplete
                      ? AppTheme.successColor
                      : AppTheme.primaryColor,
                  size: 20,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    widget.quest.title,
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                          color: isClaimed ? Colors.grey : Colors.white,
                          decoration:
                              isClaimed ? TextDecoration.lineThrough : null,
                        ),
                  ),
                ),
                if (isClaimed)
                  const Icon(Icons.check, color: Colors.grey, size: 20)
                else if (widget.quest.rewardXP > 0)
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                    decoration: BoxDecoration(
                      color: AppTheme.xpBarFill.withValues(alpha: 0.2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      '+${widget.quest.rewardXP} XP',
                      style: const TextStyle(
                          color: AppTheme.primaryColor,
                          fontSize: 12,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
              ],
            ),

            const SizedBox(height: 8),
            Text(
              widget.quest.description,
              style: TextStyle(
                  color: isClaimed ? Colors.grey : AppTheme.textSecondary,
                  fontSize: 12),
            ),
            const SizedBox(height: 16),

            // Progress Bar & Action
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(4),
                        child: LinearProgressIndicator(
                          value: progress,
                          backgroundColor: Colors.grey[800],
                          color: isComplete
                              ? AppTheme.successColor
                              : AppTheme.primaryColor,
                          minHeight: 8,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '${widget.quest.currentValue} / ${widget.quest.targetValue}',
                        style:
                            const TextStyle(color: Colors.grey, fontSize: 10),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 16),
                if (isComplete && !isClaimed)
                  ElevatedButton(
                    onPressed: _isClaiming ? null : _handleClaim,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppTheme.successColor,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 0),
                      minimumSize: const Size(0, 32),
                    ),
                    child: _isClaiming
                        ? const SizedBox(
                            width: 12,
                            height: 12,
                            child: CircularProgressIndicator(
                                strokeWidth: 2, color: Colors.white))
                        : Text(AppLocalizations.of(context)!.questClaim,
                            style: const TextStyle(fontSize: 12)),
                  )
                else if (widget.quest.rewardItem != null && !isClaimed)
                  const Icon(Icons.inventory_2,
                      color: AppTheme.secondaryColor, size: 20),
              ],
            ),
          ],
        ),
      ),
    );
  }

  IconData _getIconForType(String type) {
    switch (type) {
      case 'daily':
        return Icons.today;
      case 'story':
        return Icons.auto_stories;
      case 'milestone':
        return Icons.emoji_events;
      default:
        return Icons.task_alt;
    }
  }
}
