import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../features/chat/presentation/pages/chat_page.dart';
import '../../features/chat/presentation/providers/chat_providers.dart';
import 'robot_avatar.dart';

// ---------------------------------------------------------------------------
// Provider: maps AgentStatus → RobotState for the floating button
// ---------------------------------------------------------------------------

final robotStateProvider = Provider<RobotState>((ref) {
  final chatState = ref.watch(chatProvider);
  return switch (chatState.agentStatus) {
    AgentStatus.idle => RobotState.idle,
    AgentStatus.thinking => RobotState.thinking,
    AgentStatus.executing => RobotState.executing,
    AgentStatus.awaitingApproval => RobotState.alert,
    AgentStatus.error => RobotState.alert,
  };
});

// ---------------------------------------------------------------------------
// Floating robot FAB
// ---------------------------------------------------------------------------

class FloatingRobotFab extends ConsumerWidget {
  const FloatingRobotFab({super.key});

  void _openChat(BuildContext context) {
    Navigator.of(context).push(
      PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) =>
            const ChatPage(),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          final tween = Tween(
            begin: const Offset(0, 1),
            end: Offset.zero,
          ).chain(CurveTween(curve: Curves.easeOutCubic));
          return SlideTransition(
            position: animation.drive(tween),
            child: child,
          );
        },
        transitionDuration: const Duration(milliseconds: 350),
        fullscreenDialog: true,
      ),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final robotState = ref.watch(robotStateProvider);

    return GestureDetector(
      onTap: () => _openChat(context),
      child: Container(
        width: 64,
        height: 64,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: const Color(0xFF1E293B),
          boxShadow: [
            BoxShadow(
              color: _glowColor(robotState).withOpacity(0.5),
              blurRadius: 16,
              spreadRadius: 2,
            ),
          ],
        ),
        child: Center(
          child: RobotAvatar(
            state: robotState,
            size: 52,
          ),
        ),
      ),
    );
  }

  Color _glowColor(RobotState state) => switch (state) {
        RobotState.idle => const Color(0xFF6366F1),
        RobotState.thinking => const Color(0xFFF59E0B),
        RobotState.executing => const Color(0xFFF97316),
        RobotState.speaking => const Color(0xFF0EA5E9),
        RobotState.alert => const Color(0xFFEF4444),
      };
}
