import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:timelines_plus/timelines_plus.dart';

class MobHistoryDetailPendingPage extends StatefulWidget {
  Map<String, dynamic> data;
  MobHistoryDetailPendingPage({required this.data, super.key});

  @override
  State<MobHistoryDetailPendingPage> createState() => _MobHistoryDetailPendingPageState();
}

class _MobHistoryDetailPendingPageState extends State<MobHistoryDetailPendingPage> {
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: backgroundColor,
        appBar: appBarTemplate(context: context, title: 'detail'.tr(), action: null),
        body: Column(
          children: [
            divider(),
            Expanded(
              child: widget.data.isNotEmpty?Container(
                alignment: Alignment.topCenter,
                width: U.bodyWidth(context),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(widget.data['title'], style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                            requestTiles(
                                image: widget.data['image'] ?? "null",
                                title: widget.data[U.langColumn(context, 'sub')],
                                subtitle: widget.data[U.langColumn(context, 'desc')]??'',
                                border: true
                            ),
                            SizedBox(height: 16),
                            widget.data['others']?Column(
                              children: [
                                textHorizontal('requestedFor'.tr(), widget.data['data']['user_id']),
                                SizedBox(height: 16),
                              ],
                            ):Container(),
                            textHorizontal('location'.tr(), widget.data['location']),
                            SizedBox(height: 16),
                            divider(opacity: 0.05),
                            SizedBox(height: 16),
                            attachment_new(widget.data['imageList']),
                            SizedBox(height: 16),
                            textVertical('note'.tr(), widget.data['note'] != '' ? widget.data['note'] : '-'),
                            SizedBox(height: 24),
                          ],
                        ),
                      ),
                      separator(),
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('activity'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                            SizedBox(height: 16),
                            Text('timeline'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
                            SizedBox(height: 16),
                            timeline('stateRequested'.tr(), widget.data['datetimeRequest'] != null ? convertDate(widget.data['datetimeRequest'], context.locale.toString()) : '-', current: false, first: true),
                            timeline('pending'.tr(), widget.data['datetimeRequest'] != null ? convertDate(widget.data['datetimeRequest'], context.locale.toString()) : '-', current: true, first: false),
                          ],
                        ),
                      ),
                      Padding(padding: EdgeInsets.symmetric(horizontal: 16), child: divider(opacity: 0.05)),
                      SizedBox(height: 16),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16),
                        child: Row(
                          children: [
                            Expanded(child: Text('state'.tr(), style: TextStyle(color: textColor, fontSize: 14))),
                            Container(
                              width: 25, height: 25,
                              decoration: BoxDecoration(image: DecorationImage(image: AssetImage('assets/image/general/Hourglass.png'), fit: BoxFit.cover)),
                            ),
                            SizedBox(width: 5),
                            Text('pending'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.85), fontSize: 14)),
                          ],
                        ),
                      ),
                      SizedBox(height: 16),
                      separator(),
                    ],
                  ),
                ),
              ):loadingTemplate(),
            ),
            divider(),
            widget.data.isNotEmpty?Container(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16), color: Colors.white,
              child: Container(
                alignment: Alignment.bottomCenter,
                width: U.bodyWidth(context),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('pending_info_detail'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
                    SizedBox(height: 10),
                    buttonTemplate(text: 'cancel_pending'.tr(), backgroundColor: textColor.withValues(alpha: 0.1), textColor: textColor.withValues(alpha: 0.75), borderColor: textColor.withValues(alpha: 0.20), action: ()async{
                      dialogConfirm(context: context, title: 'buttonCancel'.tr(), text: 'confirmCancel'.tr(), actionYes: ()async{
                        showLoading(context);

                        List list = jsonDecode(sharedPreferencesManager.getString(SharedPreferencesManager.keyPendingData)!);
                        list.removeWhere((element) => element['uniqueId'] == widget.data['uniqueId']);
                        await sharedPreferencesManager.putString(SharedPreferencesManager.keyPendingData, jsonEncode(list));

                        closeLoading(context);
                        navigateBack(context, exc: true);
                      });
                    })
                  ],
                ),
              ),
            ):Container()
          ],
        )
    );
  }

  Widget attachment_new(List images){
    var imageWidth = ((U.bodyWidth(context)-32)/5)-5;

    List imageList = [];
    images.forEach((element) {
      imageList.add(base64Decode(element));
    });

    return imageList.length > 0 ? Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('image'.tr(), style: TextStyle(color: textColor)),
        SizedBox(height: 5),
        Row(
          children: List.generate(imageList.length, (i){
            return GestureDetector(
                child: Container(
                  width: imageWidth, height: imageWidth, alignment: Alignment.topRight,
                  margin: EdgeInsets.only(right: i == 4 ? 0 : 6),
                  decoration: BoxDecoration(
                      color: Colors.black12, borderRadius: BorderRadius.all(Radius.circular(5)), border: Border.all(color: Colors.black26, width: 0.5),
                      image: DecorationImage(image: MemoryImage(imageList[i]), fit: BoxFit.cover)
                  ),
                ),
                onTap: ()=>navigateTo(context, PhotoPreviewGallery(title: 'image'.tr(), imageList: imageList, startIndex: i, isUrl: false))
            );
          }),
        )
      ],
    ) : textVertical('image'.tr(), 'noImgAttach'.tr());
  }

  Widget timeline(label, text, {bool first = false, bool current = false}) {
    return TimelineTile(
      nodeAlign: TimelineNodeAlign.start,
      contents: Container(
        margin: EdgeInsets.fromLTRB(15, 10, 0, 10),
        child: Row(
          children: [
            Text(label, style: TextStyle(fontSize: 14, color: textColor.withValues(alpha: 0.85))),
            SizedBox(width: 5),
            Expanded(child: Text(text, style: TextStyle(fontSize: 13, color: textColor), textAlign: TextAlign.end)),
          ],
        ),
      ),
      node: TimelineNode(
        indicator: DotIndicator(color: current ? Color(0xffBEC1C1) : Color(0xffE8E8E8)),
        startConnector: SolidLineConnector(color: first ? Colors.transparent : Color(0xffE8E8E8)),
        endConnector: SolidLineConnector(color: current ? Colors.transparent : Color(0xffE8E8E8)),
      ),
    );
  }
}
