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

class SimSelectionDialog extends StatefulWidget {
  final String phoneNumber;
  final String displayName;
  final Function(int simSlot) onSimSelected;

  const SimSelectionDialog({
    super.key,
    required this.phoneNumber,
    required this.displayName,
    required this.onSimSelected,
  });

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

class _SimSelectionDialogState extends State<SimSelectionDialog> {
  SimData? _simData;
  bool _isLoading = true;
  String? _error;
  int? _selectedSimSlot;

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

  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');
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Colors.grey[900],
      title: const Text(
        'Select SIM for Call',
        style: TextStyle(color: Colors.white),
      ),
      content: _buildContent(),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text(
            'Cancel',
            style: TextStyle(color: Colors.grey),
          ),
        ),
        if (_selectedSimSlot != null)
          TextButton(
            onPressed: () {
              widget.onSimSelected(_selectedSimSlot!);
              Navigator.of(context).pop();
            },
            child: const Text(
              'Switch SIM',
              style: TextStyle(color: Colors.blue),
            ),
          ),
      ],
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const SizedBox(
        height: 100,
        child: Center(
          child: CircularProgressIndicator(color: Colors.blue),
        ),
      );
    }

    if (_error != null) {
      return _buildErrorContent();
    }

    if (_simData?.cards.isEmpty ?? true) {
      return _buildFallbackContent();
    }

    return _buildSimList();
  }

  Widget _buildErrorContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const Icon(
          Icons.error_outline,
          color: Colors.red,
          size: 48,
        ),
        const SizedBox(height: 16),
        Text(
          'Error loading SIM cards',
          style: const TextStyle(color: Colors.white),
        ),
        const SizedBox(height: 8),
        Text(
          _error!,
          style: const TextStyle(color: Colors.grey, fontSize: 12),
        ),
        const SizedBox(height: 16),
        ElevatedButton(
          onPressed: _loadSimCards,
          child: const Text('Retry'),
        ),
      ],
    );
  }

  Widget _buildFallbackContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        _buildSimTile('SIM 1', 'Slot 0', 0),
        _buildSimTile('SIM 2', 'Slot 1', 1),
      ],
    );
  }

  Widget _buildSimList() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: _simData!.cards.map((card) {
        final index = _simData!.cards.indexOf(card);
        return _buildSimTile(
          _getSimDisplayName(card, index),
          _getSimSubtitle(card),
          card.slotIndex,
        );
      }).toList(),
    );
  }

  Widget _buildSimTile(String title, String subtitle, int slotIndex) {
    return RadioListTile<int>(
      title: Text(
        title,
        style: const TextStyle(color: Colors.white),
      ),
      subtitle: Text(
        subtitle,
        style: const TextStyle(color: Colors.grey),
      ),
      value: slotIndex,
      groupValue: _selectedSimSlot,
      onChanged: (value) {
        setState(() {
          _selectedSimSlot = value;
        });
      },
      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 &&
        (card.displayName == null || card.displayName.isEmpty)) {
      subtitleParts.add(card.carrierName);
    }

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

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