import 'dart:developer';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import '../../bloc/devices_manager_bloc.dart';
import '../../feature/devices/device_model.dart';
import '../extension/context_extension.dart';
import '../services/language_services.dart';

import '../constant/app/app_constants.dart';

class SharedPieChart extends StatefulWidget {
  const SharedPieChart({super.key, required this.deviceByState, required this.devicesManagerBloc});

  final Map<String, List<Device>> deviceByState;
  final DevicesManagerBloc devicesManagerBloc;

  @override
  State<SharedPieChart> createState() => _SharedPieChartState();
}

class _SharedPieChartState extends State<SharedPieChart> {
  int lastTouchedIndex = 1000;

  @override
  Widget build(BuildContext context) {
    TextStyle titleStyle = const TextStyle(
      color: Colors.white,
      fontSize: 20,
      fontWeight: FontWeight.bold,
    );
    List<Map<String, dynamic>> states = [
      {
        'count': widget.deviceByState[ApplicationConstants.OFFLINE_STATE]?.length ?? 0,
        'color': Colors.grey
      },
      {
        'count': widget.deviceByState[ApplicationConstants.NORMAL_STATE]?.length ?? 0,
        'color': Colors.green
      },
      {
        'count': widget.deviceByState[ApplicationConstants.WARNING_STATE]?.length ?? 0,
        'color': Colors.red
      },
      {
        'count': widget.deviceByState[ApplicationConstants.INPROGRESS_STATE]?.length ?? 0,
        'color': Colors.yellow
      },
      {
        'count': widget.deviceByState[ApplicationConstants.ERROR_STATE]?.length ?? 0,
        'color': Colors.black
      },
    ];
    int offlineCount = widget.deviceByState[ApplicationConstants.OFFLINE_STATE]?.length ?? 0;
    int normalCount = widget.deviceByState[ApplicationConstants.NORMAL_STATE]?.length ?? 0;
    int warningCount = widget.deviceByState[ApplicationConstants.WARNING_STATE]?.length ?? 0;
    int inProgressCount = widget.deviceByState[ApplicationConstants.INPROGRESS_STATE]?.length ?? 0;
    int errorCount = widget.deviceByState[ApplicationConstants.ERROR_STATE]?.length ?? 0;
    return AspectRatio(
      aspectRatio: 1.5,
      child: Row(
        children: <Widget>[
          const SizedBox(
            height: 18,
          ),
          Expanded(
            child: AspectRatio(
              aspectRatio: 1,
              child: PieChart(
                PieChartData(
                  pieTouchData: PieTouchData(
                    enabled: true,
                    touchCallback: (FlTouchEvent event, pieTouchResponse) {
                      if (!event.isInterestedForInteractions ||
                          pieTouchResponse == null ||
                          pieTouchResponse.touchedSection == null) {
                        return;
                      }
                      int newTouchedIndex = pieTouchResponse.touchedSection!.touchedSectionIndex;
                      updateDevicesOnTapPieChart(newTouchedIndex,states);
                    },
                  ),
                  sections: states
                      .where((state) => state['count'] != 0)
                      .map((state) => PieChartSectionData(
                            color: state['color'],
                            value: (state['count'] as int).toDouble(),
                            title: state['count'].toString(),
                            radius: context.dynamicWidth(0.2),
                            titleStyle: titleStyle,
                          ))
                      .toList(),
                  centerSpaceRadius: context.dynamicWidth(0.05),
                  sectionsSpace: 2,
                ),
              ),
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              if (offlineCount != 0)
                Column(
                  children: [
                    Indicator(
                      color: Colors.grey,
                      text: appLocalization(context).inactive_devices_message,
                      isSquare: true,
                    ),
                    SizedBox(
                      height: context.lowValue,
                    ),
                  ],
                ),
              if (normalCount != 0)
                Column(
                  children: [
                    Indicator(
                      color: Colors.green,
                      text: appLocalization(context).active_devices_message,
                      isSquare: true,
                    ),
                    SizedBox(
                      height: context.lowValue,
                    ),
                  ],
                ),
              if (warningCount != 0)
                Column(
                  children: [
                    Indicator(
                      color: Colors.red,
                      text: appLocalization(context).warning_devices_message,
                      isSquare: true,
                    ),
                    SizedBox(
                      height: context.lowValue,
                    ),
                  ],
                ),
              if (inProgressCount != 0)
                Column(
                  children: [
                    Indicator(
                      color: Colors.yellow,
                      text: appLocalization(context).in_progress_message,
                      isSquare: true,
                    ),
                    SizedBox(
                      height: context.lowValue,
                    ),
                  ],
                ),
              if (errorCount != 0)
                Indicator(
                  color: Colors.black,
                  text: appLocalization(context).error_message_uppercase,
                  isSquare: true,
                ),
            ],
          ),
          const SizedBox(
            width: 10,
          ),
        ],
      ),
    );
  }

  void updateDevicesOnTapPieChart(int touchedIndex, List<Map<String, dynamic>> states) {
    final filteredStates = states.where((state) => state['count'] != 0).toList();

    if (touchedIndex >= 0 && touchedIndex < filteredStates.length) {
      final originalIndex = states.indexOf(filteredStates[touchedIndex]);

      if (originalIndex != lastTouchedIndex) {
        lastTouchedIndex = originalIndex;
        log("Update PieChart On Tap Function");
        log("Touched Index: $touchedIndex, Original Index: $originalIndex");
        
        switch (originalIndex) {
          case 0: // OFFLINE_STATE
            log("Touched Index device state = -1");
            widget.devicesManagerBloc.getDeviceByState(context,-1);
            break;
          case 1: // NORMAL_STATE
            log("Touched Index Get device state = 0");
            widget.devicesManagerBloc.getDeviceByState(context,0);
            break;
          case 2: // WARNING_STATE
            log("Touched Index Get device state = 1");
            widget.devicesManagerBloc.getDeviceByState(context,1);
            break;
          case 3: // INPROGRESS_STATE
            log("Touched Index Get device state = 2");
            widget.devicesManagerBloc.getDeviceByState(context,2);
            break;
          case 4: // ERROR_STATE
            log("Touched Index Get device state = 3");
            widget.devicesManagerBloc.getDeviceByState(context,3);
            break;
        }
      }
    }
  }
}

class Indicator extends StatelessWidget {
  const Indicator({
    super.key,
    required this.color,
    required this.text,
    required this.isSquare,
    this.size = 16,
    this.textColor,
  });

  final Color color;
  final String text;
  final bool isSquare;
  final double size;
  final Color? textColor;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          width: size,
          height: size,
          decoration: BoxDecoration(
            shape: isSquare ? BoxShape.rectangle : BoxShape.circle,
            color: color,
          ),
        ),
        SizedBox(
          width: context.lowValue,
        ),
        Text(
          text,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: textColor,
          ),
        )
      ],
    );
  }
}
