import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/foundation.dart'
    show kIsWeb, defaultTargetPlatform, TargetPlatform;
import 'controller/functions/device_analyzer.dart';

// --- CompatibilityDetailCard Widget (كما هو) ---
class CompatibilityDetailCard extends StatelessWidget {
  final Map<String, dynamic> detail;
  const CompatibilityDetailCard({super.key, required this.detail});

  Color _getStatusColor(bool status, int achieved, int max) {
    if (!status) return Colors.red.shade400;
    if (achieved < max) return Colors.orange.shade600;
    return Colors.teal;
  }

  IconData _getIconForLabel(String label) {
    if (label.contains('رام')) return Icons.memory;
    if (label.contains('معالج') || label.contains('CPU'))
      return Icons.developer_board;
    if (label.contains('تخزين') || label.contains('كتابة'))
      return Icons.sd_storage_outlined;
    if (label.contains('أندرويد')) return Icons.android;
    if (label.contains('خدمات')) return Icons.g_mobiledata;
    if (label.contains('حساسات') || label.contains('Gyroscope'))
      return Icons.sensors;
    return Icons.smartphone;
  }

  @override
  Widget build(BuildContext context) {
    final bool status = detail['status'] ?? false;
    final String label = detail['label'] ?? "";
    final int achievedScore = detail['achieved_score'] ?? 0;
    final int maxScore = detail['max_score'] ?? 1;
    final Color color = _getStatusColor(status, achievedScore, maxScore);
    final double progress =
        (maxScore > 0) ? (achievedScore / maxScore).clamp(0.0, 1.0) : 0.0;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 7),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
              color: Colors.grey.withOpacity(0.08),
              blurRadius: 15,
              offset: const Offset(0, 5))
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(_getIconForLabel(label),
                  color: Colors.grey.shade600, size: 20),
              const SizedBox(width: 8),
              Expanded(
                child: Text(label,
                    style: TextStyle(
                        fontSize: 15,
                        color: Colors.grey.shade800,
                        fontWeight: FontWeight.w600)),
              ),
              Text("$achievedScore/$maxScore ${"points".tr}",
                  style: TextStyle(
                      color: color, fontWeight: FontWeight.bold, fontSize: 14)),
            ],
          ),
          const SizedBox(height: 12),
          LinearProgressIndicator(
            value: progress,
            backgroundColor: Colors.grey.shade200,
            color: color,
            minHeight: 6,
            borderRadius: BorderRadius.circular(3),
          ),
        ],
      ),
    );
  }
}

// --- Main Page Widget (Android-only) ---
class DeviceCompatibilityPage extends StatefulWidget {
  const DeviceCompatibilityPage({super.key});
  @override
  State<DeviceCompatibilityPage> createState() =>
      _DeviceCompatibilityPageState();
}

class _DeviceCompatibilityPageState extends State<DeviceCompatibilityPage> {
  int score = 0;
  List<Map<String, dynamic>> details = [];
  bool isLoading = true;

  bool get _isAndroid =>
      !kIsWeb && defaultTargetPlatform == TargetPlatform.android;

  @override
  void initState() {
    super.initState();
    if (_isAndroid) {
      _initializePage();
    } else {
      // منصّة غير أندرويد: لا تعمل أي تحليلات
      setState(() => isLoading = false);
    }
  }

  Future<void> _initializePage() async {
    final result = await DeviceAnalyzer().analyzeDevice();
    if (!mounted) return;
    setState(() {
      score = result['score'];
      details = List<Map<String, dynamic>>.from(result['details']);
      isLoading = false;
    });
  }

  Color _getColorForScore(int value) {
    if (value >= 80) return Colors.teal;
    if (value >= 60) return Colors.orange.shade700;
    return Colors.red.shade600;
  }

  String _getScoreMessage(int value) {
    if (value >= 80) return "Your device provides excellent performance".tr;
    if (value >= 60) return "Your device is good and very suitable".tr;
    if (value >= 40) return "Compatible, you may notice some slowness".tr;
    return "The app may not work optimally".tr;
  }

  @override
  Widget build(BuildContext context) {
    // حظر الصفحة على غير أندرويد
    if (!_isAndroid) {
      return Scaffold(
        backgroundColor: const Color(0xFFF7F8FC),
        appBar: AppBar(
          title: Text("Device Compatibility".tr,
              style: const TextStyle(
                  color: Colors.black87, fontWeight: FontWeight.bold)),
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0,
          iconTheme: const IconThemeData(color: Colors.black87),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.phone_iphone, size: 56, color: Colors.grey),
                const SizedBox(height: 12),
                Text("This page is only available for Android devices".tr,
                    style: TextStyle(fontSize: 16)),
                const SizedBox(height: 8),
                ElevatedButton(
                  onPressed: () => Get.back(),
                  child: Text("Back".tr),
                ),
              ],
            ),
          ),
        ),
      );
    }

    return Scaffold(
      backgroundColor: const Color(0xFFF7F8FC),
      appBar: AppBar(
        title: Text("Device Compatibility".tr,
            style:
                const TextStyle(color: Colors.black87, fontWeight: FontWeight.bold)),
        centerTitle: true,
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.black87),
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator(color: Colors.teal))
          : Column(
              children: [
                _buildScoreHeader(),
                Expanded(
                  child: ListView.builder(
                    padding: const EdgeInsets.only(top: 10, bottom: 20),
                    itemCount: details.length,
                    itemBuilder: (context, i) =>
                        CompatibilityDetailCard(detail: details[i]),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.teal,
                      minimumSize: const Size(double.infinity, 50),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                      elevation: 0,
                    ),
                    onPressed: () => Get.back(),
                    child: Text("Continue to App".tr,
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white)),
                  ),
                ),
              ],
            ),
    );
  }

  /// الهيدر
  Widget _buildScoreHeader() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      height: 220,
      child: Stack(
        alignment: Alignment.center,
        children: [
          PieChart(
            PieChartData(
              sectionsSpace: 4,
              centerSpaceRadius: 80,
              startDegreeOffset: -90,
              sections: [
                PieChartSectionData(
                    color: _getColorForScore(score),
                    value: score.toDouble(),
                    title: '',
                    radius: 25),
                PieChartSectionData(
                    color: Colors.grey.shade200,
                    value: (100 - score).toDouble().clamp(0, 100),
                    title: '',
                    radius: 25),
              ],
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("$score%",
                  style: TextStyle(
                      fontSize: 52,
                      fontWeight: FontWeight.bold,
                      color: _getColorForScore(score))),
              const SizedBox(height: 4),
              Text(_getScoreMessage(score),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Colors.grey.shade700,
                      fontSize: 16,
                      fontWeight: FontWeight.w500)),
            ],
          ),
        ],
      ),
    );
  }
}
