// lib/features/guardian_dashboard/guardian_ai_config_screen.dart
// ignore_for_file: use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../../app/injection_container.dart';
import '../../../core/network/api_client.dart';

Dio get _api => sl<ApiClient>().dio;

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

  @override
  State<GuardianAiConfigScreen> createState() => _GuardianAiConfigScreenState();
}

class _GuardianAiConfigScreenState extends State<GuardianAiConfigScreen> {
  bool _loading = true;
  bool _saving = false;
  String? _error;
  bool _needsPairing = false;

  // Config values
  double _confidenceThreshold = 0.5;
  double _alertDistanceClose = 1.5;
  double _alertDistanceMedium = 3.0;
  int _maxInferenceFps = 5;
  String _enabledLabels = 'ALL';

  static const _labelOptions = ['ALL', 'PERSON', 'VEHICLE', 'OBSTACLE'];

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

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
      _needsPairing = false;
    });
    try {
      final paired = await _hasActivePairing();
      if (!paired) {
        setState(() {
          _needsPairing = true;
          _loading = false;
        });
        return;
      }

      final res = await _api
          .get('/guardian/ai-config')
          .timeout(const Duration(seconds: 8));
      final data = res.data['data'];
      if (data is Map) {
        setState(() {
          _confidenceThreshold =
              (data['confidenceThreshold'] as num?)?.toDouble() ?? 0.5;
          _alertDistanceClose =
              (data['alertDistanceClose'] as num?)?.toDouble() ?? 1.5;
          _alertDistanceMedium =
              (data['alertDistanceMedium'] as num?)?.toDouble() ?? 3.0;
          _maxInferenceFps = (data['maxInferenceFps'] as num?)?.toInt() ?? 5;
          _enabledLabels = data['enabledLabels']?.toString() ?? 'ALL';
        });
      }
    } on DioException catch (e) {
      setState(() {
        _error = e.response?.data?['message']?.toString() ??
            'Gagal memuat konfigurasi AI.';
      });
    } catch (e) {
      setState(() => _error = 'Timeout / error: $e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _save() async {
    setState(() => _saving = true);
    try {
      await _api.put('/guardian/ai-config', data: {
        'confidenceThreshold': _confidenceThreshold,
        'alertDistanceClose': _alertDistanceClose,
        'alertDistanceMedium': _alertDistanceMedium,
        'maxInferenceFps': _maxInferenceFps,
        'enabledLabels': _enabledLabels,
      }).timeout(const Duration(seconds: 8));
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Konfigurasi AI berhasil disimpan'),
            backgroundColor: Color(0xFF16A34A),
          ),
        );
      }
    } on DioException catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(e.response?.data?['message']?.toString() ??
                'Gagal menyimpan konfigurasi.'),
            backgroundColor: const Color(0xFFDC2626),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: $e'),
            backgroundColor: const Color(0xFFDC2626),
          ),
        );
      }
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  Future<bool> _hasActivePairing() async {
    try {
      final res = await _api
          .get('/shared/pairing/status')
          .timeout(const Duration(seconds: 5));
      final data = res.data['data'];
      if (data is Map) return data['status'] == 'ACTIVE';
    } catch (_) {}
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // ── Header ──────────────────────────────────────────────────────
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'AI Config',
                        style: GoogleFonts.outfit(
                          fontSize: 22,
                          fontWeight: FontWeight.w800,
                          color: const Color(0xFF0F172A),
                        ),
                      ),
                      Text(
                        'Konfigurasi deteksi YOLO untuk User',
                        style: GoogleFonts.inter(
                          fontSize: 13,
                          color: const Color(0xFF64748B),
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  onPressed: () => context.go('/guardian/benchmark'),
                  icon: const Icon(Icons.speed_outlined),
                  tooltip: 'Benchmark',
                  color: const Color(0xFF64748B),
                ),
                IconButton(
                  onPressed: _loading ? null : _load,
                  icon: const Icon(Icons.refresh_rounded),
                  tooltip: 'Refresh',
                  color: const Color(0xFF64748B),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // ── Body ─────────────────────────────────────────────────────────
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : _needsPairing
                      ? _buildNoPairingPanel()
                      : _error != null
                          ? _buildErrorPanel()
                          : _buildConfigForm(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildConfigForm() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // ── Confidence Threshold ──────────────────────────────────────────
          _SectionCard(
            title: 'Confidence Threshold',
            subtitle:
                'Minimal keyakinan AI untuk menganggap objek sebagai obstacle',
            icon: Icons.tune_outlined,
            iconColor: const Color(0xFF1A56DB),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('Nilai saat ini:',
                        style: GoogleFonts.inter(
                            fontSize: 13, color: const Color(0xFF64748B))),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        color: const Color(0xFF1A56DB).withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        _confidenceThreshold.toStringAsFixed(2),
                        style: GoogleFonts.jetBrainsMono(
                          fontSize: 14,
                          fontWeight: FontWeight.w700,
                          color: const Color(0xFF1A56DB),
                        ),
                      ),
                    ),
                  ],
                ),
                Slider(
                  value: _confidenceThreshold,
                  min: 0.1,
                  max: 0.9,
                  divisions: 8,
                  activeColor: const Color(0xFF1A56DB),
                  onChanged: (v) => setState(() => _confidenceThreshold = v),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('0.1 (sensitif)',
                        style: GoogleFonts.inter(
                            fontSize: 11, color: const Color(0xFF94A3B8))),
                    Text('0.9 (ketat)',
                        style: GoogleFonts.inter(
                            fontSize: 11, color: const Color(0xFF94A3B8))),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),

          // ── Alert Distances ───────────────────────────────────────────────
          _SectionCard(
            title: 'Jarak Peringatan',
            subtitle: 'Batas jarak (meter) untuk level peringatan',
            icon: Icons.radar_outlined,
            iconColor: const Color(0xFFD97706),
            child: Column(
              children: [
                // Close
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [
                      Container(
                        width: 8,
                        height: 8,
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: Color(0xFFDC2626),
                        ),
                      ),
                      const SizedBox(width: 6),
                      Text('Jarak Dekat',
                          style: GoogleFonts.inter(
                              fontSize: 13, color: const Color(0xFF0F172A))),
                    ]),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        color: const Color(0xFFDC2626).withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '${_alertDistanceClose.toStringAsFixed(1)} m',
                        style: GoogleFonts.jetBrainsMono(
                          fontSize: 13,
                          fontWeight: FontWeight.w700,
                          color: const Color(0xFFDC2626),
                        ),
                      ),
                    ),
                  ],
                ),
                Slider(
                  value: _alertDistanceClose,
                  min: 0.5,
                  max: 3.0,
                  divisions: 5,
                  activeColor: const Color(0xFFDC2626),
                  onChanged: (v) => setState(() => _alertDistanceClose = v),
                ),
                const SizedBox(height: 8),
                // Medium
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [
                      Container(
                        width: 8,
                        height: 8,
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: Color(0xFFD97706),
                        ),
                      ),
                      const SizedBox(width: 6),
                      Text('Jarak Sedang',
                          style: GoogleFonts.inter(
                              fontSize: 13, color: const Color(0xFF0F172A))),
                    ]),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        color: const Color(0xFFD97706).withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '${_alertDistanceMedium.toStringAsFixed(1)} m',
                        style: GoogleFonts.jetBrainsMono(
                          fontSize: 13,
                          fontWeight: FontWeight.w700,
                          color: const Color(0xFFD97706),
                        ),
                      ),
                    ),
                  ],
                ),
                Slider(
                  value: _alertDistanceMedium,
                  min: 1.0,
                  max: 8.0,
                  divisions: 7,
                  activeColor: const Color(0xFFD97706),
                  onChanged: (v) => setState(() => _alertDistanceMedium = v),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),

          // ── Max Inference FPS ─────────────────────────────────────────────
          _SectionCard(
            title: 'Max Inference FPS',
            subtitle:
                'Maksimal frame per detik untuk inferensi AI (lebih tinggi = lebih boros baterai)',
            icon: Icons.speed_outlined,
            iconColor: const Color(0xFF059669),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('FPS saat ini:',
                        style: GoogleFonts.inter(
                            fontSize: 13, color: const Color(0xFF64748B))),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(
                        color: const Color(0xFF059669).withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '$_maxInferenceFps fps',
                        style: GoogleFonts.jetBrainsMono(
                          fontSize: 14,
                          fontWeight: FontWeight.w700,
                          color: const Color(0xFF059669),
                        ),
                      ),
                    ),
                  ],
                ),
                Slider(
                  value: _maxInferenceFps.toDouble(),
                  min: 1,
                  max: 30,
                  divisions: 29,
                  activeColor: const Color(0xFF059669),
                  onChanged: (v) =>
                      setState(() => _maxInferenceFps = v.toInt()),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('1 fps (hemat baterai)',
                        style: GoogleFonts.inter(
                            fontSize: 11, color: const Color(0xFF94A3B8))),
                    Text('30 fps (real-time)',
                        style: GoogleFonts.inter(
                            fontSize: 11, color: const Color(0xFF94A3B8))),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),

          // ── Enabled Labels ────────────────────────────────────────────────
          _SectionCard(
            title: 'Label yang Diaktifkan',
            subtitle: 'Jenis objek yang akan dideteksi AI',
            icon: Icons.label_outline,
            iconColor: const Color(0xFF7C3AED),
            child: Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _labelOptions.map((label) {
                final selected = _enabledLabels == label;
                return GestureDetector(
                  onTap: () => setState(() => _enabledLabels = label),
                  child: Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    decoration: BoxDecoration(
                      color: selected ? const Color(0xFF7C3AED) : Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(
                        color: selected
                            ? const Color(0xFF7C3AED)
                            : const Color(0xFFE2E8F0),
                      ),
                    ),
                    child: Text(
                      label,
                      style: GoogleFonts.inter(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color:
                            selected ? Colors.white : const Color(0xFF64748B),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
          const SizedBox(height: 24),

          // ── Save button ───────────────────────────────────────────────────
          SizedBox(
            width: double.infinity,
            child: FilledButton.icon(
              onPressed: _saving ? null : _save,
              icon: _saving
                  ? const SizedBox(
                      width: 18,
                      height: 18,
                      child: CircularProgressIndicator(
                          strokeWidth: 2, color: Colors.white))
                  : const Icon(Icons.save_outlined),
              label: Text(_saving ? 'Menyimpan...' : 'Simpan Konfigurasi'),
              style: FilledButton.styleFrom(
                backgroundColor: const Color(0xFF1A56DB),
                padding: const EdgeInsets.symmetric(vertical: 14),
                textStyle: GoogleFonts.inter(
                    fontSize: 14, fontWeight: FontWeight.w600),
              ),
            ),
          ),
          const SizedBox(height: 8),
        ],
      ),
    );
  }

  Widget _buildNoPairingPanel() {
    return Center(
      child: Container(
        padding: const EdgeInsets.all(24),
        margin: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: const Color(0xFFFFFBEB),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: const Color(0xFFFDE68A)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.link_off, color: Color(0xFFD97706), size: 52),
            const SizedBox(height: 14),
            Text(
              'Belum Pairing',
              style: GoogleFonts.outfit(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: const Color(0xFF92400E),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Hubungkan akun Guardian dengan User terlebih dahulu untuk mengatur konfigurasi AI.',
              style: GoogleFonts.inter(
                  fontSize: 13, color: const Color(0xFF92400E)),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorPanel() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.wifi_off, size: 52, color: Color(0xFF94A3B8)),
          const SizedBox(height: 14),
          Text(
            _error!,
            textAlign: TextAlign.center,
            style:
                GoogleFonts.inter(fontSize: 13, color: const Color(0xFF64748B)),
          ),
          const SizedBox(height: 18),
          FilledButton.icon(
            onPressed: _load,
            icon: const Icon(Icons.refresh),
            label: const Text('Coba lagi'),
            style: FilledButton.styleFrom(
                backgroundColor: const Color(0xFF1A56DB)),
          ),
        ],
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
//  SECTION CARD
// ─────────────────────────────────────────────────────────────────────────────

class _SectionCard extends StatelessWidget {
  final String title;
  final String subtitle;
  final IconData icon;
  final Color iconColor;
  final Widget child;

  const _SectionCard({
    required this.title,
    required this.subtitle,
    required this.icon,
    required this.iconColor,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: const Color(0xFFE2E8F0)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.03),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(children: [
            Container(
              width: 34,
              height: 34,
              decoration: BoxDecoration(
                color: iconColor.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(icon, color: iconColor, size: 18),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: GoogleFonts.outfit(
                      fontSize: 14,
                      fontWeight: FontWeight.w700,
                      color: const Color(0xFF0F172A),
                    ),
                  ),
                  Text(
                    subtitle,
                    style: GoogleFonts.inter(
                      fontSize: 11,
                      color: const Color(0xFF94A3B8),
                    ),
                  ),
                ],
              ),
            ),
          ]),
          const SizedBox(height: 16),
          const Divider(height: 1, color: Color(0xFFF1F5F9)),
          const SizedBox(height: 12),
          child,
        ],
      ),
    );
  }
}
