part of '../../main.dart';

class SavedAnalysesPage extends StatefulWidget {
  const SavedAnalysesPage({super.key, required this.endpoint});

  final Uri endpoint;

  @override
  State<SavedAnalysesPage> createState() => _SavedAnalysesPageState();
}

class _SavedAnalysesPageState extends State<SavedAnalysesPage> {
  late Future<List<SavedAnalysis>> _analyses;

  @override
  void initState() {
    super.initState();
    _analyses = _loadAnalyses();
  }

  Future<List<SavedAnalysis>> _loadAnalyses() async {
    final response = await http
        .get(widget.endpoint)
        .timeout(const Duration(seconds: 30));

    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw Exception('API error ${response.statusCode}: ${response.body}');
    }

    final decoded = jsonDecode(response.body) as Map<String, dynamic>;
    final data = decoded['data'] as List<dynamic>? ?? [];
    return data
        .map(
          (item) =>
              SavedAnalysis.fromJson((item as Map).cast<String, dynamic>()),
        )
        .toList();
  }

  Future<void> _refresh() async {
    setState(() {
      _analyses = _loadAnalyses();
    });
    await _analyses;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Lihat Analisis')),
      body: FutureBuilder<List<SavedAnalysis>>(
        future: _analyses,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (snapshot.hasError) {
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.error_outline, size: 40),
                    const SizedBox(height: 12),
                    Text(
                      'Gagal memuat data analisis.\n${snapshot.error}',
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 12),
                    FilledButton.icon(
                      onPressed: _refresh,
                      icon: const Icon(Icons.refresh),
                      label: const Text('Coba Lagi'),
                    ),
                  ],
                ),
              ),
            );
          }

          final analyses = snapshot.data ?? [];
          if (analyses.isEmpty) {
            return const Center(child: Text('Belum ada analisis tersimpan.'));
          }
          final groups = StudentAnalysisGroup.fromAnalyses(analyses);

          return RefreshIndicator(
            onRefresh: _refresh,
            child: ListView.separated(
              padding: const EdgeInsets.all(16),
              itemCount: groups.length,
              separatorBuilder: (_, __) => const SizedBox(height: 10),
              itemBuilder: (context, index) {
                final group = groups[index];
                return Card(
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundColor: AppColors.navy,
                      foregroundColor: AppColors.blueSoft,
                      child: const Icon(Icons.folder_outlined),
                    ),
                    title: Text(group.studentName),
                    subtitle: Text(
                      '${group.latest.genderLabel} | ${group.count} hasil analisis\nRata-rata PD: ${group.averagePdPercent}%',
                    ),
                    isThreeLine: true,
                    trailing: const Icon(Icons.chevron_right),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute<void>(
                          builder:
                              (context) =>
                                  StudentAnalysisDetailPage(group: group),
                        ),
                      );
                    },
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

class StudentAnalysisGroup {
  const StudentAnalysisGroup({
    required this.studentName,
    required this.analyses,
  });

  final String studentName;
  final List<SavedAnalysis> analyses;

  SavedAnalysis get latest => analyses.first;
  int get count => analyses.length;
  String get averagePdPercent {
    if (analyses.isEmpty) {
      return '0.0';
    }
    final average =
        analyses.fold<double>(
          0,
          (total, analysis) => total + analysis.probabilityPd,
        ) /
        analyses.length;
    return (average * 100).toStringAsFixed(1);
  }

  static List<StudentAnalysisGroup> fromAnalyses(List<SavedAnalysis> analyses) {
    final grouped = <String, List<SavedAnalysis>>{};
    final displayNames = <String, String>{};

    for (final analysis in analyses) {
      final name =
          analysis.studentName.trim().isEmpty
              ? '-'
              : analysis.studentName.trim();
      final key = name.toLowerCase();
      displayNames.putIfAbsent(key, () => name);
      grouped.putIfAbsent(key, () => []).add(analysis);
    }

    final groups =
        grouped.entries
            .map(
              (entry) => StudentAnalysisGroup(
                studentName: displayNames[entry.key] ?? entry.key,
                analyses: entry.value,
              ),
            )
            .toList();
    groups.sort(
      (a, b) =>
          a.studentName.toLowerCase().compareTo(b.studentName.toLowerCase()),
    );
    return groups;
  }
}

class StudentAnalysisDetailPage extends StatelessWidget {
  const StudentAnalysisDetailPage({super.key, required this.group});

  final StudentAnalysisGroup group;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(group.studentName)),
      body: ListView.separated(
        padding: const EdgeInsets.all(16),
        itemCount: group.analyses.length,
        separatorBuilder: (_, __) => const SizedBox(height: 10),
        itemBuilder: (context, index) {
          final analysis = group.analyses[index];
          return Card(
            child: ListTile(
              leading: CircleAvatar(
                backgroundColor: AppColors.navy,
                foregroundColor: AppColors.blueSoft,
                child: Text(analysis.label),
              ),
              title: Text('Prediksi ${index + 1}'),
              subtitle: Text(
                '${analysis.genderLabel} | ${analysis.description}\nPD ${analysis.pdPercent}%  |  TPD ${analysis.tpdPercent}%',
              ),
              isThreeLine: true,
            ),
          );
        },
      ),
    );
  }
}
