import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:typed_data';
import '../../../domain/services/call_service.dart';
import '../../../domain/services/obfuscate_service.dart';
import 'package:dialer/presentation/common/widgets/username_color_generator.dart';
import 'call_page.dart';

class IncomingCallPage extends StatefulWidget {
  final String displayName;
  final String phoneNumber;
  final Uint8List? thumbnail;

  const IncomingCallPage({
    super.key,
    required this.displayName,
    required this.phoneNumber,
    this.thumbnail,
  });

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

class _IncomingCallPageState extends State<IncomingCallPage> {
  static const MethodChannel _channel = MethodChannel('call_service');
  final ObfuscateService _obfuscateService = ObfuscateService();
  final CallService _callService = CallService();

  void _answerCall() async {
    try {
      final result = await _channel.invokeMethod('answerCall');
      debugPrint('IncomingCallPage: Answer call result: $result');
      
      if (result["status"] == "answered") {
        if (!mounted) return;
        
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => CallPage(
              displayName: widget.displayName,
              phoneNumber: widget.phoneNumber,
              thumbnail: widget.thumbnail,
            ),
          ),
        );
      }
    } catch (e) {
      debugPrint("IncomingCallPage: Error answering call: $e");
      if (!mounted) return;
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Error answering call: $e")),
      );
    }
  }

  void _declineCall() async {
    try {
      await _callService.hangUpCall(context);
    } catch (e) {
      debugPrint("IncomingCallPage: Error declining call: $e");
      if (!mounted) return;
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Error declining call: $e")),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            const Spacer(),
            ObfuscatedAvatar(
              imageBytes: widget.thumbnail,
              radius: 60,
              backgroundColor: generateColorFromName(widget.displayName),
              fallbackInitial: widget.displayName,
            ),
            const SizedBox(height: 24),
            Text(
              _obfuscateService.obfuscateData(widget.displayName),
              style: const TextStyle(
                fontSize: 28,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              widget.phoneNumber,
              style: const TextStyle(fontSize: 18, color: Colors.white70),
            ),
            const SizedBox(height: 16),
            const Text(
              'Incoming Call',
              style: TextStyle(fontSize: 20, color: Colors.white70),
            ),
            const Spacer(),
            Padding(
              padding: const EdgeInsets.only(bottom: 48.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildActionButton(
                    icon: Icons.call_end,
                    color: Colors.red,
                    onPressed: _declineCall,
                    label: 'Decline',
                  ),
                  _buildActionButton(
                    icon: Icons.call,
                    color: Colors.green,
                    onPressed: _answerCall,
                    label: 'Answer',
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildActionButton({
    required IconData icon,
    required Color color,
    required VoidCallback onPressed,
    required String label,
  }) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          onTap: onPressed,
          child: Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 32,
            ),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          label,
          style: const TextStyle(color: Colors.white),
        ),
      ],
    );
  }
}