// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// admin_screen.dart
//
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/core/services/database/database_service.dart';
import 'package:nokken/tools/mood_data_generator.dart';
import 'package:nokken/tools/medication_data_generator.dart';
import 'package:nokken/tools/bloodwork_data_generator.dart';
import 'package:nokken/src/features/mood_tracker/providers/mood_state.dart';
import 'package:nokken/src/features/medication_tracker/providers/medication_state.dart';
import 'package:nokken/src/features/medication_tracker/providers/medication_taken_provider.dart';
import 'package:nokken/src/features/bloodwork_tracker/providers/bloodwork_state.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';

// Provider for DatabaseService
final databaseServiceProvider = Provider<DatabaseService>((ref) {
  return DatabaseService();
});

class AdminScreen extends ConsumerStatefulWidget {
  const AdminScreen({super.key});

  @override
  ConsumerState<AdminScreen> createState() => _AdminScreenState();
}

class _AdminScreenState extends ConsumerState<AdminScreen> {
  bool _isLoading = false;
  String _statusMessage = '';
  String _currentAction = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Admin Tools'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Data Generation Tools',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // Mood Data Generator
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Mood Data Generator',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      'Generates 365 days of random mood entries from 364 days ago to today.',
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _isLoading ? null : _generateMoodData,
                      child: _isLoading && _currentAction == 'mood'
                          ? const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SizedBox(
                                  width: 16,
                                  height: 16,
                                  child:
                                      CircularProgressIndicator(strokeWidth: 2),
                                ),
                                SizedBox(width: 8),
                                Text('Generating...'),
                              ],
                            )
                          : const Text('Generate Mood Data'),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // Medication Data Generator
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Medication Data Generator',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      'Creates 5 medication types (2 pills, 1 topical, 1 patch, 1 injection) '
                      'and generates 365 days of adherence data with realistic rates: '
                      '95-97% for pills/topical and 96-98% for patches/injections.',
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _isLoading ? null : _generateMedicationData,
                      child: _isLoading && _currentAction == 'medication'
                          ? const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SizedBox(
                                  width: 16,
                                  height: 16,
                                  child:
                                      CircularProgressIndicator(strokeWidth: 2),
                                ),
                                SizedBox(width: 8),
                                Text('Generating...'),
                              ],
                            )
                          : const Text('Generate Medication Data'),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Bloodwork Data Generator',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      'Creates bloodwork labs every 70-110 days with hormone readings, '
                      '2-4 doctor appointments, and 1 surgery throughout the year.',
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _isLoading ? null : _generateBloodworkData,
                      child: _isLoading && _currentAction == 'bloodwork'
                          ? const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SizedBox(
                                  width: 16,
                                  height: 16,
                                  child:
                                      CircularProgressIndicator(strokeWidth: 2),
                                ),
                                SizedBox(width: 8),
                                Text('Generating...'),
                              ],
                            )
                          : const Text('Generate Bloodwork Data'),
                    ),
                  ],
                ),
              ),
            ),

            // Status message
            if (_statusMessage.isNotEmpty)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: AppTheme.grey,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(_statusMessage),
              ),
          ],
        ),
      ),
    );
  }

  Future<void> _generateMoodData() async {
    setState(() {
      _isLoading = true;
      _currentAction = 'mood';
      _statusMessage = 'Generating mood data...';
    });

    try {
      // Get the database service
      final databaseService = ref.read(databaseServiceProvider);
      final generator = MoodDataGenerator(databaseService);

      await generator.generateMoodEntries();

      // Refresh mood state by calling load method directly
      await ref.read(moodStateProvider.notifier).loadMoodEntries();

      setState(() {
        _statusMessage = 'Successfully generated 365 mood entries!';
      });
    } catch (e) {
      setState(() {
        _statusMessage = 'Error generating mood data: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
        _currentAction = '';
      });
    }
  }

  Future<void> _generateMedicationData() async {
    setState(() {
      _isLoading = true;
      _currentAction = 'medication';
      _statusMessage = 'Generating medication data...';
    });

    try {
      // Get the database service
      final databaseService = ref.read(databaseServiceProvider);
      final generator = MedicationDataGenerator(databaseService);

      await generator.generateMedicationData();

      // Refresh medications by calling load method directly
      await ref.read(medicationStateProvider.notifier).loadMedications();

      // Refresh taken medications for today
      final today = DateTime.now();
      await ref
          .read(medicationTakenProvider.notifier)
          .loadTakenMedicationsForDate(today);

      setState(() {
        _statusMessage =
            'Successfully generated medication data with realistic adherence patterns!';
      });
    } catch (e) {
      setState(() {
        _statusMessage = 'Error generating medication data: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
        _currentAction = '';
      });
    }
  }

  Future<void> _generateBloodworkData() async {
    setState(() {
      _isLoading = true;
      _currentAction = 'bloodwork';
      _statusMessage = 'Generating bloodwork data...';
    });

    try {
      // Get the database service
      final databaseService = ref.read(databaseServiceProvider);
      final generator = BloodworkDataGenerator(databaseService);

      await generator.generateBloodworkData();

      // Refresh bloodwork state by calling load method directly
      await ref.read(bloodworkStateProvider.notifier).loadBloodwork();

      setState(() {
        _statusMessage = 'Successfully generated bloodwork data!';
      });
    } catch (e) {
      setState(() {
        _statusMessage = 'Error generating bloodwork data: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
        _currentAction = '';
      });
    }
  }
}
