import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../constant/finance_design_system.dart';
import '../../../controller/home/captin/behavior_controller.dart';

class BehaviorPage extends StatelessWidget {
  const BehaviorPage({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(DriverBehaviorController());
    controller.fetchDriverBehavior();

    return Scaffold(
      backgroundColor: FinanceDesignSystem.backgroundColor,
      appBar: AppBar(
        title: Text('Driver Behavior'.tr,
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: FinanceDesignSystem.primaryDark)),
        centerTitle: true,
        backgroundColor: FinanceDesignSystem.cardColor,
        elevation: 0,
        iconTheme: IconThemeData(color: FinanceDesignSystem.primaryDark),
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return Center(
              child: CircularProgressIndicator(
                  color: FinanceDesignSystem.accentBlue));
        }

        double score = controller.overallScore.value;
        bool isExcellent = score >= 90;
        bool isGood = score >= 75 && score < 90;
        Color statusColor =
            isExcellent ? Colors.green : (isGood ? Colors.orange : Colors.red);
        String statusText = isExcellent
            ? 'Excellent'.tr
            : (isGood ? 'Good'.tr : 'Needs Improvement'.tr);

        return CustomScrollView(
          slivers: [
            SliverPadding(
              padding:
                  const EdgeInsets.all(FinanceDesignSystem.horizontalPadding),
              sliver: SliverList(
                delegate: SliverChildListDelegate([
                  // Overall Score Card
                  Container(
                    padding: const EdgeInsets.all(24),
                    decoration: BoxDecoration(
                      color: FinanceDesignSystem.cardColor,
                      borderRadius: BorderRadius.circular(24),
                      boxShadow: const [
                        BoxShadow(
                            color: Colors.black12,
                            blurRadius: 10,
                            offset: Offset(0, 4))
                      ],
                    ),
                    child: Column(
                      children: [
                        Icon(Icons.shield_rounded,
                            size: 48, color: statusColor),
                        const SizedBox(height: 16),
                        Text(
                          "Overall Behavior Score".tr,
                          style: FinanceDesignSystem.headingStyle,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          "${score.toStringAsFixed(1)} / 100",
                          style: TextStyle(
                            fontSize: 36,
                            fontWeight: FontWeight.bold,
                            color: statusColor,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 6),
                          decoration: BoxDecoration(
                            color: statusColor.withValues(alpha: 0.1),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Text(
                            statusText,
                            style: TextStyle(
                                color: statusColor,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 30),
                  Text("Last 10 Trips".tr,
                      style: FinanceDesignSystem.headingStyle),
                  const SizedBox(height: 16),
                ]),
              ),
            ),
            SliverPadding(
              padding: const EdgeInsets.symmetric(
                  horizontal: FinanceDesignSystem.horizontalPadding),
              sliver: SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    var trip = controller.lastTrips[index];
                    double tripScore =
                        double.tryParse(trip['behavior_score'].toString()) ?? 0;
                    Color tColor = tripScore >= 90
                        ? Colors.green
                        : (tripScore >= 75 ? Colors.orange : Colors.red);

                    return Container(
                      margin: const EdgeInsets.only(bottom: 12),
                      decoration: BoxDecoration(
                        color: FinanceDesignSystem.cardColor,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withValues(alpha: 0.02),
                            blurRadius: 10,
                            offset: const Offset(0, 4),
                          )
                        ],
                      ),
                      child: ListTile(
                        contentPadding: const EdgeInsets.all(16),
                        leading: Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: tColor.withValues(alpha: 0.1),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(Icons.drive_eta_rounded, color: tColor),
                        ),
                        title: Text(
                          "Trip ID: ${trip['trip_id']}",
                          style: const TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 16),
                        ),
                        subtitle: Padding(
                          padding: const EdgeInsets.only(top: 8.0),
                          child: Wrap(
                            spacing: 12,
                            runSpacing: 8,
                            children: [
                              _buildBadge(Icons.speed,
                                  "${trip['max_speed']} km/h", Colors.blue),
                              _buildBadge(
                                  Icons.warning_amber_rounded,
                                  "${trip['hard_brakes']} ${'Hard Brakes'.tr}",
                                  Colors.orange),
                              _buildBadge(
                                  Icons.map_rounded,
                                  "${trip['total_distance']} km",
                                  Colors.purple),
                            ],
                          ),
                        ),
                        trailing: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "${tripScore.toStringAsFixed(0)}",
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20,
                                  color: tColor),
                            ),
                            Text('Score'.tr,
                                style: const TextStyle(
                                    fontSize: 10, color: Colors.grey)),
                          ],
                        ),
                      ),
                    );
                  },
                  childCount: controller.lastTrips.length,
                ),
              ),
            ),
            const SliverToBoxAdapter(child: SizedBox(height: 40)),
          ],
        );
      }),
    );
  }

  Widget _buildBadge(IconData icon, String label, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: color),
          const SizedBox(width: 4),
          Text(label,
              style: TextStyle(
                  fontSize: 12, color: color, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }
}
