import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

import '../../api/api_auth_provider.dart';
import '../../cubit/tab_history_cubit.dart';
import '../../utils/U.dart';
import '../../utils/extensions.dart';

class RateMission extends StatefulWidget {
  final BuildContext parentContext;
  final Map<String, dynamic> list;
  final List<dynamic> rating;
  final int index;
  final TabState state;

  const RateMission({
    super.key,
    required this.parentContext,
    required this.list,
    required this.index,
    required this.rating,
    required this.state,
  });

  @override
  State<RateMission> createState() => _RateMissionState();
}

class _RateMissionState extends State<RateMission> {
  int tempRating = 0;
  String description = '';
  String ratingAspect = '';
  late TextEditingController controllerOptOther;
  late List aspectList;

  @override
  void initState() {
    super.initState();
    controllerOptOther = TextEditingController();

    String locale = widget.parentContext.locale.toString();
    aspectList = widget.list['_ratingAspect${locale[0].toUpperCase()}${locale[1]}'] != null &&
        widget.list['_ratingAspect${locale[0].toUpperCase()}${locale[1]}'].trim() != ''
        ? widget.list['_ratingAspect${locale[0].toUpperCase()}${locale[1]}'].split(';')
        : [];

    if (aspectList.isNotEmpty) {
      aspectList.add('OTHER_OPTION');
    } else {
      ratingAspect = 'OTHER_OPTION';
    }
  }

  @override
  void dispose() {
    controllerOptOther.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    HistoryModule historyModule = Provider.of<HistoryModule>(context, listen: false);
    return AlertDialog(
      backgroundColor: Colors.transparent,
      contentPadding: EdgeInsets.zero,
      content: Container(
        decoration: BoxDecoration(
          color: secondaryColor,
          borderRadius: BorderRadius.circular(25),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Bagian header
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(widget.list[U.langColumn(context, 'requestSubject')],
                      style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
                  const SizedBox(height: 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('${'ticketNumber'.tr()}: ${widget.list['ticketNo']}',
                          style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                      Text(convertDate(widget.list['datetimeRequest'], context.locale.toString()),
                          style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                    ],
                  ),
                ],
              ),
            ),

            // Bagian rating
            Container(
              padding: const EdgeInsets.fromLTRB(30, 15, 30, 15),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(25)),
              child: Column(
                children: [
                  Text('satisfactionAsk'.tr(), style: const TextStyle(fontSize: 16)),
                  const SizedBox(height: 12),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: List.generate(widget.rating.length, (i) {
                      return Expanded(
                        child: GestureDetector(
                          child: Image(
                            image: AssetImage(widget.rating[i]['image'].toString()),
                            color: Colors.white.withValues(alpha: tempRating == widget.rating[i]['key'] ? 1 : 0.3),
                            colorBlendMode: BlendMode.modulate,
                          ),
                          onTap: () {
                            setState(() {
                              tempRating = widget.rating[i]['key'] as int;
                              description = widget.rating[i]['label'] as String;
                            });
                          },
                        ).withHover(),
                      );
                    }),
                  ),
                  const SizedBox(height: 6),
                  Text(description,
                      style: const TextStyle(color: textColor, fontSize: 14, fontWeight: FontWeight.w300),
                      textAlign: TextAlign.center),

                  // Bagian aspek tambahan
                  if (tempRating != 0) ...[
                    const SizedBox(height: 20),
                    separator(),
                    const SizedBox(height: 20),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('${'whatMakesYou'.tr()} $description?', style: const TextStyle(fontSize: 16)),
                        const SizedBox(height: 12),
                        Wrap(
                          runSpacing: 10,
                          spacing: 10,
                          children: List.generate(aspectList.length, (i) {
                            return GestureDetector(
                              child: Container(
                                padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                                decoration: BoxDecoration(
                                  color: aspectList[i] == ratingAspect
                                      ? primaryColor.withValues(alpha: 0.3)
                                      : Colors.white,
                                  border: Border.all(
                                      color: aspectList[i] == ratingAspect ? primaryColor : textColor),
                                  borderRadius: const BorderRadius.all(Radius.circular(50)),
                                ),
                                child: Text(aspectList[i] == 'OTHER_OPTION' ? 'letMeWrite'.tr() : aspectList[i],
                                    style: const TextStyle(color: textColor)),
                              ),
                              onTap: () {
                                setState(() {
                                  ratingAspect = ratingAspect == aspectList[i] ? '' : aspectList[i];
                                });
                              },
                            ).withHover();
                          }),
                        ),
                        if (ratingAspect == 'OTHER_OPTION')
                          TextFormField(
                            maxLines: 1,
                            maxLength: 50,
                            autofocus: true,
                            controller: controllerOptOther,
                            style: const TextStyle(fontSize: 14, color: Colors.black),
                            decoration: InputDecoration(
                              counterText: '',
                              hintText: 'writeHere'.tr(),
                              hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                              filled: true,
                              fillColor: Colors.white,
                              isDense: true,
                              contentPadding: const EdgeInsets.all(13),
                              prefixIcon: Padding(
                                padding: const EdgeInsets.only(left: 13, right: 13),
                                child: U.iconsax('edit-2', color: textColor, size: 22),
                              ),
                              enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(12),
                                  borderSide: BorderSide(color: const Color(0xff262626).withValues(alpha: 0.5))),
                              focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(12),
                                  borderSide: const BorderSide(color: primaryColor)),
                            ),
                          ),
                      ],
                    ),
                  ],

                  // Tombol aksi
                  const SizedBox(height: 20),
                  Opacity(
                    opacity: tempRating > 0 ? 1 : 0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                          child: buttonTemplate(
                            text: 'textCancel'.tr(),
                            backgroundColor: Colors.black12,
                            borderColor: Colors.black12,
                            textColor: textColor,
                            height: 40,
                            action: () => navigateBack(context),
                          ),
                        ),
                        const SizedBox(width: 20),
                        Expanded(
                          child: buttonTemplate(
                            text: 'save_rating'.tr(),
                            backgroundColor: primaryColor,
                            borderColor: primaryColor,
                            height: 40,
                            action: () async {
                              if (tempRating > 0) {
                                var data = {
                                  "ticketNo": widget.list['ticketNo'],
                                  "rateSatisfy": tempRating,
                                };
                                if (ratingAspect != 'OTHER_OPTION') {
                                  data['aspect'] = ratingAspect;
                                } else if (controllerOptOther.text.isNotEmpty) {
                                  data['aspect'] = controllerOptOther.text;
                                }

                                var res = await ApiAuthProvider()
                                    .postData('/api/requestHistories/rateSatisfy', null, data);
                                if (res != null) {
                                  widget.parentContext.read<DoneCubit>().setSatisfaction(widget.index, tempRating);
                                  navigateBack(context);
                                }
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
