import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import '../services/notification_service.dart';

class NotificationDebugScreen extends StatefulWidget {
  const NotificationDebugScreen({super.key});

  @override
  State<NotificationDebugScreen> createState() =>
      _NotificationDebugScreenState();
}

class _NotificationDebugScreenState extends State<NotificationDebugScreen> {
  bool _isLoading = false;
  bool? _canScheduleExactNotifications;
  String? _lastStatus;
  String? _fcmToken;
  List<PendingNotificationRequest> _pendingNotifications = [];

  @override
  void initState() {
    super.initState();
    _loadPendingNotifications();
  }

  Future<void> _setStatus(String message) async {
    if (!mounted) return;
    setState(() {
      _lastStatus = message;
    });
  }

  Future<void> _loadPendingNotifications() async {
    setState(() {
      _isLoading = true;
    });

    try {
      await NotificationService.instance.initialize();
      final canScheduleExact =
          await NotificationService.instance.canScheduleExactNotifications();
      final pending = await NotificationService.instance.pendingNotifications();
      final token = await NotificationService.instance.getFcmToken();

      if (!mounted) return;
      setState(() {
        _pendingNotifications = pending;
        _canScheduleExactNotifications = canScheduleExact;
        _fcmToken = token;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
        _lastStatus = 'Gagal memuat notifikasi tertunda: $e';
      });
    }
  }

  Future<void> _sendImmediateSimple() async {
    await _runAction(() async {
      await NotificationService.instance.showInstantNotification(
        title: 'Tes Notifikasi IrriGo',
        body: 'Notifikasi lokal berhasil dikirim dari halaman debug.',
        payload: 'debug:immediate',
      );
    }, 'Notifikasi langsung terkirim');
  }

  Future<void> _sendModeChangedSample() async {
    await _runAction(() async {
      await NotificationService.instance.showModeChangedNotification(
        modeLabel: 'berdasarkan jadwal',
        enabled: true,
      );
    }, 'Notifikasi mode berhasil dikirim');
  }

  Future<void> _sendSensorTriggeredSample() async {
    await _runAction(() async {
      await NotificationService.instance.showWateringNotification(
        title: 'IrriGo - Penyiraman Otomatis',
        body:
            'Penyiraman dilakukan pada pot 3 karena kelembapan 28% di bawah ambang batas 40%.',
        payload: {
          'type': 'sensor_triggered',
          'pot': 3,
          'soil': 28,
          'threshold': 40,
        },
      );
    }, 'Notifikasi otomatis sensor terkirim');
  }

  Future<void> _scheduleThirtySecondNotification() async {
    await _runAction(() async {
      final success = await NotificationService.instance
          .scheduleStable30SecondNotification(
            title: 'Tes Notifikasi 30 Detik',
            body:
                'Notifikasi ini dijadwalkan 30 detik. Minimize app atau tutup setelah ini untuk test background notification!',
            payload: 'debug:scheduled_30s',
          );

      if (success) {
        await _setStatus(
          '✅ Notifikasi 30 detik dijadwalkan STABIL! Cek ulang dibawah utk lihat status exact alarm dan pending notifikasi.',
        );
      } else {
        await _setStatus(
          '❌ GAGAL scheduling 30 detik. Periksa POST_NOTIFICATIONS permission di settings app!',
        );
      }
    }, 'Jadwalkan Notif 30 Detik Stabil');

    await _loadPendingNotifications();
  }

  Future<void> _requestExactAlarmPermission() async {
    await _runAction(() async {
      final granted =
          await NotificationService.instance.requestExactAlarmsPermission();
      if (!granted) {
        await _setStatus(
          'Exact alarm belum aktif/diizinkan oleh sistem. Aplikasi pakai inexact agar tetap stabil.',
        );
        return;
      }
      await _setStatus('Exact alarm aktif. Jadwal lokal akan lebih presisi.');
    }, 'Izin exact alarm berhasil diminta');

    await _loadPendingNotifications();
  }

  Future<void> _revalidatePermissions() async {
    await _runAction(() async {
      final postNotifGranted =
          await NotificationService.instance.revalidatePermissions();
      final exactGranted =
          await NotificationService.instance.canScheduleExactNotifications();

      final status = '''
✅ Permission Status Fresh Check:
  • POST_NOTIFICATIONS: ${postNotifGranted ? '✅ GRANTED' : '❌ DENIED'}
  • SCHEDULE_EXACT_ALARM: ${exactGranted ? '✅ AVAILABLE' : '⚠️ NOT AVAILABLE'}

Jika ada yang DENIED, settings app → IrriGo → Izin → aktifkan permission.
      ''';

      await _setStatus(status);
    }, 'Permission berhasil di-revalidasi');

    await _loadPendingNotifications();
  }

  Future<void> _cancelAllNotifications() async {
    await _runAction(() async {
      await NotificationService.instance.cancelAll();
    }, 'Semua notifikasi dibatalkan');

    await _loadPendingNotifications();
  }

  Future<void> _runAction(
    Future<void> Function() action,
    String successText,
  ) async {
    setState(() {
      _isLoading = true;
    });

    try {
      await NotificationService.instance.initialize();
      await action();
      await _setStatus(successText);
    } catch (e) {
      await _setStatus('Error: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Debug Notifikasi'),
        backgroundColor: Colors.orange,
        actions: [
          IconButton(
            onPressed: _isLoading ? null : _loadPendingNotifications,
            icon: const Icon(Icons.refresh),
            tooltip: 'Refresh',
          ),
        ],
      ),
      body:
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    _buildInfoCard(),
                    const SizedBox(height: 16),
                    _buildActionCard(),
                    const SizedBox(height: 16),
                    _buildPendingCard(),
                    if (_lastStatus != null) ...[
                      const SizedBox(height: 16),
                      _buildStatusCard(),
                    ],
                  ],
                ),
              ),
    );
  }

  Widget _buildInfoCard() {
    return Card(
      elevation: 2,
      color: Colors.blue.shade50,
      child: const Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Cara kerja notifikasi IrriGo',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Text(
              '• Notifikasi langsung muncul saat app aktif atau background.\n'
              '• Notifikasi terjadwal lokal tetap bisa muncul walau app diminimize/ditutup setelah dijadwalkan.\n'
              '• Agar jadwal presisi, aktifkan exact alarm.\n'
              '• Untuk event server saat app benar-benar mati, gunakan push notification dari Railway Worker + FCM (sudah dipasang).',
              style: TextStyle(fontSize: 13, height: 1.4),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionCard() {
    return Card(
      elevation: 3,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              'Aksi Debug',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            ElevatedButton.icon(
              onPressed: _isLoading ? null : _sendImmediateSimple,
              icon: const Icon(Icons.notifications_active),
              label: const Text('Kirim Notifikasi Langsung'),
            ),
            const SizedBox(height: 8),
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _sendModeChangedSample,
              icon: const Icon(Icons.settings),
              label: const Text('Simulasi Notif Ubah Mode'),
            ),
            const SizedBox(height: 8),
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _sendSensorTriggeredSample,
              icon: const Icon(Icons.water_drop),
              label: const Text('Simulasi Notif Sensor Trigger'),
            ),
            const SizedBox(height: 8),
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _scheduleThirtySecondNotification,
              icon: const Icon(Icons.schedule),
              label: const Text('Jadwalkan Notif 30 Detik'),
            ),
            const SizedBox(height: 8),
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _requestExactAlarmPermission,
              icon: const Icon(Icons.alarm_on),
              label: const Text('Aktifkan Exact Alarm'),
            ),
            const SizedBox(height: 8),
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _loadPendingNotifications,
              icon: const Icon(Icons.key),
              label: const Text('Cek Ulang Token FCM'),
            ),
            const SizedBox(height: 8),
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _revalidatePermissions,
              icon: const Icon(Icons.verified_user),
              label: const Text('Validasi Ulang Permission'),
            ),
            const SizedBox(height: 8),
            TextButton.icon(
              onPressed: _isLoading ? null : _cancelAllNotifications,
              icon: const Icon(Icons.cancel),
              label: const Text('Batalkan Semua Notifikasi'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPendingCard() {
    return Card(
      elevation: 3,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Notifikasi Tertunda',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              'Exact alarm: ${_canScheduleExactNotifications == null ? 'memuat...' : (_canScheduleExactNotifications! ? 'aktif' : 'belum aktif')}',
              style: TextStyle(
                fontSize: 13,
                color:
                    _canScheduleExactNotifications == true
                        ? Colors.green.shade700
                        : Colors.red.shade700,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 8),
            SelectableText(
              'FCM token: ${_fcmToken == null ? 'belum tersedia' : _fcmToken!}',
              style: TextStyle(
                fontSize: 12,
                color:
                    _fcmToken == null
                        ? Colors.red.shade700
                        : Colors.green.shade700,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 12),
            if (_pendingNotifications.isEmpty)
              const Text('Belum ada notifikasi terjadwal.')
            else
              ..._pendingNotifications.map(
                (notification) => Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.grey.shade300),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(notification.title ?? '(tanpa judul)'),
                        const SizedBox(height: 4),
                        Text(notification.body ?? '(tanpa isi)'),
                        const SizedBox(height: 4),
                        Text(
                          'ID: ${notification.id}',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey.shade600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusCard() {
    final success =
        _lastStatus!.contains('terkirim') ||
        _lastStatus!.contains('dijadwalkan') ||
        _lastStatus!.contains('dibatalkan');

    return Card(
      color: success ? Colors.green.shade50 : Colors.red.shade50,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Text(
          _lastStatus!,
          style: TextStyle(
            fontWeight: FontWeight.w600,
            color: success ? Colors.green.shade800 : Colors.red.shade800,
          ),
        ),
      ),
    );
  }
}
