import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:camera/camera.dart';
import '../../../core/secure_storage.dart';
import '../../auth/presentation/login_screen.dart';
import '../../../../main.dart';

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

  @override
  State<UserDashboardScreen> createState() => _UserDashboardScreenState();
}

class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerProviderStateMixin {
  CameraController? _camCtrl;
  late AnimationController _radarCtrl;
  late Animation<double> _radarAnim;

  @override
  void initState() {
    super.initState();
    _radarCtrl = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);
    _radarAnim = Tween<double>(begin: 0.9, end: 1.08).animate(
      CurvedAnimation(parent: _radarCtrl, curve: Curves.easeInOut),
    );
    _initCamera();
  }

  Future<void> _initCamera() async {
    if (cameras.isEmpty) return;
    _camCtrl = CameraController(cameras[0], ResolutionPreset.high, enableAudio: false);
    await _camCtrl!.initialize();
    if (mounted) setState(() {});
  }

  Future<void> _logout() async {
    await SecureStorage().deleteToken();
    if (mounted) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (_) => const LoginScreen()),
        (_) => false,
      );
    }
  }

  @override
  void dispose() {
    _camCtrl?.dispose();
    _radarCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final topPad = MediaQuery.of(context).padding.top;
    final botPad = MediaQuery.of(context).padding.bottom;

    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(children: [
        // 1. Camera feed
        SizedBox.expand(
          child: (_camCtrl != null && _camCtrl!.value.isInitialized)
              ? CameraPreview(_camCtrl!)
              : Container(
                  decoration: const BoxDecoration(color: Color(0xFF0A1520)),
                ),
        ),

        // 2. Grid overlay
        SizedBox.expand(child: CustomPaint(painter: _GridPainter())),

        // 3. Green scan gradient
        AnimatedBuilder(
          animation: _radarCtrl,
          builder: (_, __) => SizedBox.expand(
            child: DecoratedBox(
              decoration: BoxDecoration(
                gradient: RadialGradient(
                  colors: [
                    Colors.transparent,
                    const Color(0xFF10B981).withValues(alpha: 0.05 + _radarCtrl.value * 0.08),
                  ],
                  stops: const [0.5, 1.0],
                  radius: 1.4,
                ),
              ),
            ),
          ),
        ),

        // 4. Scan line
        AnimatedBuilder(
          animation: _radarCtrl,
          builder: (_, __) => Positioned(
            top: size.height * (0.3 + _radarCtrl.value * 0.35),
            left: 0,
            right: 0,
            child: Container(
              height: 1.5,
              decoration: BoxDecoration(
                color: const Color(0xFF60EFAB).withValues(alpha: 0.25),
              ),
            ),
          ),
        ),

        // 5. Top status bar
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Container(
            padding: EdgeInsets.fromLTRB(16, topPad + 8, 16, 12),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Colors.black87, Colors.transparent],
              ),
            ),
            child: Row(children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.54),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(
                    color: const Color(0xFF60EFAB).withValues(alpha: 0.3),
                  ),
                ),
                child: Row(children: [
                  Container(
                    width: 6,
                    height: 6,
                    decoration: const BoxDecoration(
                      color: Color(0xFF60EFAB),
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 7),
                  Text(
                    'Memindai area...',
                    style: GoogleFonts.inter(
                      color: Colors.white,
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ]),
              ),
              const Spacer(),
              IconButton(
                onPressed: _logout,
                icon: const Icon(Icons.power_settings_new, color: Colors.white, size: 26),
                style: IconButton.styleFrom(
                  backgroundColor: Colors.redAccent.withValues(alpha: 0.8),
                ),
              ),
            ]),
          ),
        ),

        // 6. Center radar
        Center(
          child: AnimatedBuilder(
            animation: _radarAnim,
            builder: (_, __) => Transform.scale(
              scale: _radarAnim.value,
              child: SizedBox(
                width: 100,
                height: 100,
                child: CustomPaint(painter: _RadarPainter()),
              ),
            ),
          ),
        ),

        // 7. Obstacle alert card
        Positioned(
          bottom: 160,
          left: 16,
          right: 16,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.6),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: const Color(0xFFF59E0B).withValues(alpha: 0.3),
              ),
            ),
            child: Row(children: [
              Container(
                width: 28,
                height: 28,
                decoration: BoxDecoration(
                  color: const Color(0x33F59E0B),
                  borderRadius: BorderRadius.circular(7),
                ),
                child: const Icon(Icons.warning_amber_rounded, color: Color(0xFFF59E0B), size: 16),
              ),
              const SizedBox(width: 10),
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text('Obstacle ahead',
                    style: GoogleFonts.inter(
                        color: Colors.white, fontSize: 13, fontWeight: FontWeight.w500)),
                Text('2.1m — Haptic alert sent',
                    style: GoogleFonts.inter(color: Colors.white60, fontSize: 11)),
              ]),
            ]),
          ),
        ),

        // 8. Bottom action buttons
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: Container(
            padding: EdgeInsets.fromLTRB(16, 16, 16, botPad + 20),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.bottomCenter,
                end: Alignment.topCenter,
                colors: [Colors.black87, Colors.transparent],
              ),
            ),
            child: Column(children: [
              Row(children: [
                Expanded(child: _bigBtn(const Color(0xCC1A56DB), Icons.mic, () {})),
                const SizedBox(width: 12),
                Expanded(child: _bigBtn(const Color(0xCCDC2626), Icons.phone_in_talk, () {})),
              ]),
              const SizedBox(height: 8),
              Text(
                'Vol+ terima panggilan  •  Vol- ping darurat',
                style: GoogleFonts.inter(fontSize: 10, color: Colors.white30),
              ),
            ]),
          ),
        ),
      ]),
    );
  }

  Widget _bigBtn(Color color, IconData icon, VoidCallback onTap) {
    return ElevatedButton(
      onPressed: onTap,
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        elevation: 0,
        padding: const EdgeInsets.symmetric(vertical: 22),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      ),
      child: Icon(icon, size: 40, color: Colors.white),
    );
  }
}

class _GridPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.white.withValues(alpha: 0.04)
      ..strokeWidth = 0.5;
    for (double x = 0; x < size.width; x += 25) {
      canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint);
    }
    for (double y = 0; y < size.height; y += 25) {
      canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

class _RadarPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.2;
    for (final r in [48.0, 34.0, 20.0]) {
      paint.color = const Color(0xFF60EFAB).withValues(alpha: 0.15 + (50 - r) / 100);
      canvas.drawCircle(center, r, paint);
    }
    paint
      ..style = PaintingStyle.fill
      ..color = const Color(0xFF60EFAB);
    canvas.drawCircle(center, 5, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}