import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';
import '../../../../core/theme/app_theme.dart';
import '../../data/repositories/quest_repository.dart';
import '../../../../shared/data/local/app_database.dart'; // Für QuestCollection Typ
import '../widgets/quest_item.dart';

class QuestLogScreen extends ConsumerWidget {
  const QuestLogScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final questRepo = ref.watch(questRepositoryProvider);
    final l10n = AppLocalizations.of(context)!;

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Quest Log'),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () => context.go('/hub'),
          ),
          bottom: TabBar(
            indicatorColor: AppTheme.primaryColor,
            labelColor: AppTheme.primaryColor,
            unselectedLabelColor: Colors.grey,
            tabs: [
              Tab(text: l10n.questTabDailies),
              Tab(text: l10n.questTabJourney),
            ],
          ),
        ),
        body: StreamBuilder<List<QuestCollection>>(
          stream: questRepo.watchQuests(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            }

            final allQuests = snapshot.data ?? [];

            final dailies = allQuests.where((q) => q.type == 'daily').toList();
            final story = allQuests.where((q) => q.type != 'daily').toList();

            return TabBarView(
              children: [
                _QuestList(
                    quests: dailies, emptyMessage: l10n.questEmptyDailies),
                _QuestList(quests: story, emptyMessage: l10n.questEmptyJourney),
              ],
            );
          },
        ),
      ),
    );
  }
}

class _QuestList extends StatelessWidget {
  final List<QuestCollection> quests;
  final String emptyMessage;

  const _QuestList({required this.quests, required this.emptyMessage});

  @override
  Widget build(BuildContext context) {
    if (quests.isEmpty) {
      return Center(
        child: Text(
          emptyMessage,
          textAlign: TextAlign.center,
          style: TextStyle(color: AppTheme.textSecondary),
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: quests.length,
      itemBuilder: (context, index) {
        return QuestItem(quest: quests[index]);
      },
    );
  }
}
