import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sim_data_new/sim_data.dart';

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

  @override
  _SettingsSimPageState createState() => _SettingsSimPageState();
}

class _SettingsSimPageState extends State<SettingsSimPage> {
  int _selectedSim = 0;
  SimData? _simData;
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadSimCards();
    _loadDefaultSim();
  }

  void _loadSimCards() async {
    try {
      final simData = await SimDataPlugin.getSimData();
      setState(() {
        _simData = simData;
        _isLoading = false;
        _error = null;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
      print('Error loading SIM cards: $e');
    }
  }

  void _loadDefaultSim() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _selectedSim = prefs.getInt('default_sim_slot') ?? 0;
    });
  }

  void _onSimChanged(int? value) async {
    if (value != null) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt('default_sim_slot', value);
      setState(() {
        _selectedSim = value;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text('Default SIM'),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(
          color: Colors.blue,
        ),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.red,
              size: 64,
            ),
            const SizedBox(height: 16),
            Text(
              'Error loading SIM cards',
              style: const TextStyle(color: Colors.white, fontSize: 18),
            ),
            const SizedBox(height: 8),
            Text(
              _error!,
              style: const TextStyle(color: Colors.grey, fontSize: 14),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                  _error = null;
                });
                _loadSimCards();
              },
              child: const Text('Retry'),
            ),
            const SizedBox(height: 16),
            Text(
              'Fallback to default options:',
              style: const TextStyle(color: Colors.grey, fontSize: 14),
            ),
            const SizedBox(height: 8),
            _buildFallbackSimList(),
          ],
        ),
      );
    }

    if (_simData == null || _simData!.cards.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.sim_card_alert,
              color: Colors.orange,
              size: 64,
            ),
            const SizedBox(height: 16),
            const Text(
              'No SIM cards detected',
              style: TextStyle(color: Colors.white, fontSize: 18),
            ),
            const SizedBox(height: 8),
            const Text(
              'Using default options:',
              style: TextStyle(color: Colors.grey, fontSize: 14),
            ),
            const SizedBox(height: 16),
            _buildFallbackSimList(),
          ],
        ),
      );
    }

    return ListView.builder(
      itemCount: _simData!.cards.length,
      itemBuilder: (context, index) {
        final card = _simData!.cards[index];
        return RadioListTile<int>(
          title: Text(
            _getSimDisplayName(card, index),
            style: const TextStyle(color: Colors.white),
          ),
          subtitle: Text(
            _getSimSubtitle(card),
            style: const TextStyle(color: Colors.grey),
          ),
          value: card.slotIndex,
          groupValue: _selectedSim,
          onChanged: _onSimChanged,
          activeColor: Colors.blue,
        );
      },
    );
  }

  Widget _buildFallbackSimList() {
    return Column(
      children: [
        RadioListTile<int>(
          title: const Text('SIM 1', style: TextStyle(color: Colors.white)),
          value: 0,
          groupValue: _selectedSim,
          onChanged: _onSimChanged,
          activeColor: Colors.blue,
        ),
        RadioListTile<int>(
          title: const Text('SIM 2', style: TextStyle(color: Colors.white)),
          value: 1,
          groupValue: _selectedSim,
          onChanged: _onSimChanged,
          activeColor: Colors.blue,
        ),
      ],
    );
  }

  String _getSimDisplayName(dynamic card, int index) {
    if (card.displayName != null && card.displayName.isNotEmpty) {
      return card.displayName;
    }
    if (card.carrierName != null && card.carrierName.isNotEmpty) {
      return card.carrierName;
    }
    return 'SIM ${index + 1}';
  }

  String _getSimSubtitle(dynamic card) {
    List<String> subtitleParts = [];

    if (card.phoneNumber != null && card.phoneNumber.isNotEmpty) {
      subtitleParts.add(card.phoneNumber);
    }

    if (card.carrierName != null && card.carrierName.isNotEmpty) {
      subtitleParts.add(card.carrierName);
    }

    if (subtitleParts.isEmpty) {
      subtitleParts.add('Slot ${card.slotIndex}');
    }

    return subtitleParts.join(' • ');
  }
}
