import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; // ConsumerState
import 'package:mobile_scanner/mobile_scanner.dart';
import '../theme/app_colors.dart';
import '../widgets/sake_radar_chart.dart';
// Provider
import '../providers/navigation_provider.dart'; // Check if this tab is active
import '../main.dart'; // RouteObserver

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

  @override
  ConsumerState<ScanARScreen> createState() => _ScanARScreenState();
}


class _ScanARScreenState extends ConsumerState<ScanARScreen> 
    with SingleTickerProviderStateMixin, WidgetsBindingObserver, AutomaticKeepAliveClientMixin, RouteAware {
  
  MobileScannerController? _controller;
  bool _isScanning = true;
  bool _isInitializing = false;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // Initial start handled by checking tab/visibility usually, but here we init safely
    _initializeControllerSafe();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  // --- RouteAware ---
  @override
  void didPushNext() {
    _stopScanner();
  }

  @override
  void didPopNext() {
    // Only reinitialize if we are currently on Scan Tab (Index 1)
    final currentIndex = ref.read(currentTabIndexProvider);
    if (currentIndex == 1) {
      _initializeControllerSafe();
    }
  }

  Future<void> _initializeControllerSafe() async {
    if (_isInitializing) return;
    if (mounted) setState(() => _isInitializing = true);

    try {
      // Dispose old controller if exists
      await _controller?.dispose();
      _controller = null;

      // Small delay to ensure camera resource is released
      await Future.delayed(const Duration(milliseconds: 100));

      // Create new controller
      // MobileScannerController starts immediately upon construction
      // It does NOT have a value.isInitialized property like CameraController
      _controller = MobileScannerController();

      if (mounted) {
        setState(() {
          _isInitializing = false;
        });
      }
      debugPrint('✅ Scanner: Controller created successfully');

    } catch (e) {
      debugPrint('❌ Scanner: Error during initialization: $e');
      if (mounted) {
        setState(() {
          _isInitializing = false;
          _controller = null;
        });
      }
    }
  }

  void _stopScanner() {
    _controller?.dispose();
    _controller = null;
    if (mounted) setState(() {});
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      _stopScanner();
    } else if (state == AppLifecycleState.resumed) {
      _initializeControllerSafe();
    }
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    _controller?.dispose(); // Synchronous dispose
    super.dispose();
  }

  void _onDetect(BarcodeCapture capture) {
    if (!_isScanning) return;

    final List<Barcode> barcodes = capture.barcodes;
    for (final barcode in barcodes) {
      if (barcode.rawValue != null) {
        try {
          final Map<String, dynamic> data = jsonDecode(barcode.rawValue!);
          // Check for key fields to validate it's our QR
          if (data.containsKey('id') && data.containsKey('n')) {
             _isScanning = false; // Stop scanning logic
             // Show Card
             _showDigitalCard(data);
             break; 
          }
        } catch (e) {
          // Not JSON or not our format
        }
      }
    }
  }

  void _showDigitalCard(Map<String, dynamic> data) async {
    // Play sound? (Optional)
    
    await showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => _DigitalSakeCardDialog(data: data),
    );

    // Resume scanning after dialog closes
    if (mounted) {
      setState(() {
        _isScanning = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // ✅ AutomaticKeepAliveClientMixinに必要
    final appColors = Theme.of(context).extension<AppColors>()!;

    // Watch for tab changes
    ref.listen(currentTabIndexProvider, (previous, next) {
      if (previous != next) {
        if (next == 1) { // Entered Scan Tab
           _initializeControllerSafe();
        } else { // Left Scan Tab
           _stopScanner();
        }
      }
    });

    // 初期化中はローディング表示、または失敗時はエラー表示
    if (_isInitializing || _controller == null) {
      return Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const CircularProgressIndicator(color: Colors.white),
              const SizedBox(height: 16),
              Text(
                _isInitializing ? '起動中...' : 'カメラの初期化に失敗しました',
                style: const TextStyle(color: Colors.white),
              ),
              if (!_isInitializing)
                Padding(
                  padding: const EdgeInsets.only(top: 16),
                  child: TextButton(
                    onPressed: _initializeControllerSafe, // Retry
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.white,
                      side: const BorderSide(color: Colors.white),
                    ),
                    child: const Text('再試行'),
                  ),
                ),
            ],
          ),
        ),
      );
    }

    return Scaffold(
      body: Stack(
        children: [
          Container(color: Colors.black), // Prevent white flash during init
          MobileScanner(
            controller: _controller!,
            onDetect: _onDetect,
          ),
          // Overlay Design
          Container(
            decoration: BoxDecoration(
              border: Border.symmetric(
                horizontal: BorderSide(color: Colors.black.withValues(alpha: 0.5), width: 100),
                vertical: BorderSide(color: Colors.black.withValues(alpha: 0.5), width: 40),
              ),
            ),
          ),
          Center(
            child: Container(
              width: 280,
              height: 280,
              decoration: BoxDecoration(
                border: Border.all(color: appColors.brandPrimary.withValues(alpha: 0.8), width: 2),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: appColors.brandPrimary.withValues(alpha: 0.4),
                    blurRadius: 20,
                    spreadRadius: 2,
                  ),
                ],
              ),
              child: Stack(
                children: [
                   // Corners
                   Positioned(top: 0, left: 0, child: _Corner(isTop: true, isLeft: true)),
                   Positioned(top: 0, right: 0, child: _Corner(isTop: true, isLeft: false)),
                   Positioned(bottom: 0, left: 0, child: _Corner(isTop: false, isLeft: true)),
                   Positioned(bottom: 0, right: 0, child: _Corner(isTop: false, isLeft: false)),
                   // Center Animation (Scanner line) - simplified
                   Center(
                     child: Container(
                       height: 2,
                       color: Colors.white.withValues(alpha: 0.5),
                     ),
                   )
                ],
              ),
            ),
          ),
          const Positioned(
            top: 60,
            left: 0,
            right: 0,
            child: Text(
              '銘柄カードのQRをスキャン',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
                shadows: [Shadow(color: Colors.black, blurRadius: 4)],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _Corner extends StatelessWidget {
  final bool isTop;
  final bool isLeft;

  const _Corner({required this.isTop, required this.isLeft});

  @override
  Widget build(BuildContext context) {
    const double size = 32; // Slightly larger for rounded look
    const double thickness = 4;
    const double radius = 16;
    
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.only(
          topLeft: isTop && isLeft ? const Radius.circular(radius) : Radius.zero,
          topRight: isTop && !isLeft ? const Radius.circular(radius) : Radius.zero,
          bottomLeft: !isTop && isLeft ? const Radius.circular(radius) : Radius.zero,
          bottomRight: !isTop && !isLeft ? const Radius.circular(radius) : Radius.zero,
        ),
        border: Border(
          top: isTop ? const BorderSide(color: Colors.white, width: thickness) : BorderSide.none,
          bottom: !isTop ? const BorderSide(color: Colors.white, width: thickness) : BorderSide.none,
          left: isLeft ? const BorderSide(color: Colors.white, width: thickness) : BorderSide.none,
          right: !isLeft ? const BorderSide(color: Colors.white, width: thickness) : BorderSide.none,
        ),
      ),
    );
  }
}

class _DigitalSakeCardDialog extends StatelessWidget {
  final Map<String, dynamic> data;

  const _DigitalSakeCardDialog({required this.data});

  @override
  Widget build(BuildContext context) {
    final appColors = Theme.of(context).extension<AppColors>()!;
    // Unpack data
    final name = data['n'] ?? '不明';
    final brewery = data['b'] ?? '不明';
    final prefecture = data['p']?.toString() ?? '不明';
    
    // Stats for chart
    // aroma unused

    // Wait, toQrJson: s=sweetness, y=body, a=alcohol.
    // Radar Chart needs: aroma, bitterness, sweetness, acidity, body.
    // We only have S, Y, A. (Sweetness, Body, Alcohol).
    // We'll map them visually or just show what we have.
    // A proper implementation plan would fetch the full data if available, but offline we only use QR data.
    // Let's map: 
    // Sweetness -> Sweetness
    // Body -> Body
    // Alcohol -> Bitterness? (High alcohol often behaves like dry/bitter) 
    // Aroma -> Default 3
    // Acidity -> Default 3
    // Or just show stars.
    // The user praised the Radar Chart, so let's try to populate it even partially.
    
    final sweetness = (data['s'] as num?)?.toInt() ?? 3;
    final body = (data['y'] as num?)?.toInt() ?? 3;
    final alcohol = (data['a'] as num?)?.toInt() ?? 3;

    final radarData = {
      'aroma': 3,
      'bitterness': alcohol, // Proxy
      'sweetness': sweetness,
      'acidity': 3,
      'body': body,
    };

    return Dialog(
      backgroundColor: Colors.transparent,
      elevation: 0,
      child: TweenAnimationBuilder<double>(
        duration: const Duration(milliseconds: 500),
        curve: Curves.elasticOut,
        tween: Tween(begin: 0.5, end: 1.0),
        builder: (context, scale, child) {
           return Transform.scale(scale: scale, child: child);
        },
        child: Container(
          width: 320,
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            gradient: const LinearGradient(
               begin: Alignment.topLeft,
               end: Alignment.bottomRight,
               colors: [Color(0xFFE3F2FD), Color(0xFFF3E5F5)], // Light Blue to Light Purple
            ),
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
               BoxShadow(color: Colors.black.withValues(alpha: 0.2), blurRadius: 20, spreadRadius: 5),
            ],
            border: Border.all(color: Colors.white, width: 2),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Badge
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                   color: appColors.brandPrimary,
                   borderRadius: BorderRadius.circular(20),
                ),
                child: Text('New Discovery!', style: TextStyle(color: appColors.surfaceSubtle, fontWeight: FontWeight.bold, fontSize: 12)),
              ),
              const SizedBox(height: 16),
              
              // Name
              Text(
                name,
                style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, height: 1.2),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),
              Text(
                '$brewery / $prefecture',
                style: const TextStyle(fontSize: 14, color: Colors.grey),
              ),
               
              const SizedBox(height: 20),
              
              // Chart
              SizedBox(
                height: 180,
                child: SakeRadarChart(
                tasteStats: radarData,
                primaryColor: appColors.brandPrimary,
              ),
              ),
              
              const SizedBox(height: 24),
              
              // Actions
              ElevatedButton.icon(
                onPressed: () => Navigator.pop(context),
                icon: const Icon(Icons.check),
                label: const Text('閉じる'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: appColors.brandPrimary,
                  foregroundColor: appColors.surfaceSubtle,
                  minimumSize: const Size(double.infinity, 48),
                   shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
