import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dialer/services/call_service.dart';
import 'package:dialer/services/obfuscate_service.dart';
import 'package:dialer/widgets/username_color_generator.dart';
import 'package:dialer/features/call/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();
  bool icingProtocolOk = true;

  void _toggleIcingProtocol() {
    setState(() {
      icingProtocolOk = !icingProtocolOk;
    });
  }

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

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

  @override
  Widget build(BuildContext context) {
    const double avatarRadius = 45.0;
    const double nameFontSize = 24.0;
    const double statusFontSize = 16.0;

    return Scaffold(
      body: Container(
        color: Colors.black,
        child: SafeArea(
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const SizedBox(height: 35),
                    ObfuscatedAvatar(
                      imageBytes: widget.thumbnail,
                      radius: avatarRadius,
                      backgroundColor: generateColorFromName(widget.displayName),
                      fallbackInitial: widget.displayName,
                    ),
                    const SizedBox(height: 4),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          icingProtocolOk ? Icons.lock : Icons.lock_open,
                          color: icingProtocolOk ? Colors.green : Colors.red,
                          size: 16,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          'Icing protocol: ${icingProtocolOk ? "ok" : "ko"}',
                          style: TextStyle(
                            color: icingProtocolOk ? Colors.green : Colors.red,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      _obfuscateService.obfuscateData(widget.displayName),
                      style: const TextStyle(
                        fontSize: nameFontSize,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      widget.phoneNumber,
                      style: const TextStyle(fontSize: statusFontSize, color: Colors.white70),
                    ),
                    const Text(
                      'Incoming Call...',
                      style: TextStyle(fontSize: statusFontSize, color: Colors.white70),
                    ),
                  ],
                ),
              ),
              const Spacer(),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 32.0, vertical: 16.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    GestureDetector(
                      onTap: _declineCall,
                      child: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: const BoxDecoration(
                          color: Colors.red,
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.call_end,
                          color: Colors.white,
                          size: 32,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: _answerCall,
                      child: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: const BoxDecoration(
                          color: Colors.green,
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.call,
                          color: Colors.white,
                          size: 32,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
    );
  }
}