import 'dart:convert';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:open_file/open_file.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:url_launcher/url_launcher.dart';

class WebReqSuccessPage extends StatefulWidget {
  Map<String, dynamic> user;
  final String ticketNo;
  final bool fromSearch;
  WebReqSuccessPage({required this.user, required this.ticketNo, this.fromSearch = false, super.key});

  @override
  State<WebReqSuccessPage> createState() => _WebReqSuccessPageState();
}

class _WebReqSuccessPageState extends State<WebReqSuccessPage> {
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();

  Map<String, dynamic> list = {};

  @override
  void initState() {
    getMission();
    // TODO: implement initState
    super.initState();
  }

  getMission() async{
    var data = await apiAuthProvider.getData('/api/requestHistories/'+widget.ticketNo, null, context);
    if(data != null) {
      if (data['datetimeScheduled'] != null && data['datetimeScheduled'] != '' && data['noteFormat'] == 'DATE') {
        var date = data['datetimeScheduled'];
        data['datetimeScheduled'] = DateFormat('dd MMM yyyy HH:mm', 'id').format(DateTime.parse(date));
      }

      if (data['noteStart'] == 'escalationNoteBySystem'){
        data['noteStart'] = 'escalationNoteBySystem'.tr();
      }

      setState((){
        list = data;
      });
    }
  }

  backAction(){
    int count = 0;
    int page = widget.fromSearch ? 3 : 2;
    Navigator.of(context).popUntil((_) => count++ >= page);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: Column(
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Text('detail'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
          ),
          divider(),
          Expanded(
            child: list.isNotEmpty?SingleChildScrollView(
              padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(list[U.langColumn(context, 'requestGroupDescription')], style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w600)),
                  SizedBox(height: 16),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.all(20),
                          decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  imageTiles(imageUrl: list['_requestImage'] ?? "null", width: 110, height: 90),
                                  SizedBox(width: 20),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(list[U.langColumn(context, 'requestSubject')], style: TextStyle(color: textColor, fontWeight: FontWeight.w600), maxLines: 2, overflow: TextOverflow.ellipsis),
                                        dashed(),
                                        Text(list[U.langColumn(context, '_subjectDescription')]??'', style: TextStyle(color: textColor), maxLines: 3, overflow: TextOverflow.ellipsis)
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 20),
                              textHorizontal('ticketNumber'.tr(), list['ticketNo'], copy: true),
                              SizedBox(height: 16),
                              renderRequested(),
                              textHorizontal('location'.tr(), list['ipphoneExtLocation']),
                              SizedBox(height: 16),
                              divider(opacity: 0.05),
                              SizedBox(height: 16),
                              list['autoResponse'] ? Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('note'.tr(), style: TextStyle(color: textColor)),
                                  SizedBox(height: 5),
                                  list['responseText']!=null&&list['responseText']!=''?Linkify(
                                    text: list['responseText'], style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w300),
                                    onOpen: (link) async {
                                      if (await canLaunchUrl(Uri.parse(link.url))) {
                                        await launchUrl(Uri.parse(link.url));
                                      }
                                    },
                                  ):Container(),
                                  list['responseAttachment']!=null&&list['responseAttachment']!=''?list['_isPdf']?GestureDetector(
                                      child: Container(
                                          width: double.infinity,
                                          margin: EdgeInsets.only(top: 8),
                                          decoration: BoxDecoration(
                                            color: Colors.white,
                                            border: Border.all(color: Colors.deepOrange),
                                            borderRadius: BorderRadius.all(Radius.circular(12)),
                                          ),
                                          child: Center(
                                            child: Column(
                                              children: [
                                                Icon(Icons.picture_as_pdf, color: Colors.deepOrange, size: 50),
                                                Text('seeAttachment'.tr(), style: TextStyle(color: Colors.black45, fontSize: 12))
                                              ],
                                            ),
                                          )
                                      ),
                                      onTap: () async{
                                        var filePath = await token.getPath()+'/TelNow/Files/';
                                        if(!File(filePath+getFileName(list['responseAttachment'])).existsSync()){
                                          // print("file isnot ready yet");
                                          await apiAuthProvider.downloadImage(list['responseAttachment'], filePath+getFileName(list['responseAttachment']));
                                        }
                                        await OpenFile.open(filePath+getFileName(list['responseAttachment']));
                                      }
                                  ):LayoutBuilder(
                                    builder: (context, constraints) {
                                      return GestureDetector(
                                          child: Container(
                                            child:Image.network(list['_mobileResponseAttachment'], fit: BoxFit.cover, width: double.infinity, height: constraints.maxWidth/(1.7), loadingBuilder:(BuildContext? context, Widget? child,ImageChunkEvent? loadingProgress) {
                                              if (loadingProgress == null) return child!;
                                              return Container(
                                                height: constraints.maxWidth/(1.7),
                                                child: Center(
                                                  child: CircularProgressIndicator(
                                                    value: loadingProgress.expectedTotalBytes != null ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes! : null,
                                                  ),
                                                ),
                                              );
                                            },
                                            ),
                                          ),
                                          onTap: ()=>navigateTo(context, PhotoPreview('image'.tr(), list['_mobileResponseAttachment'], true))
                                      );
                                    },
                                  ):Container()
                                ],
                              ) : attachment_new(list),

                              list['autoResponse'] ? Container() : SizedBox(height: 16),
                              list['autoResponse'] ? Container() : textVertical('note'.tr(), list['requestNote'] != '' ? list['requestNote'] : '-'),
                              list['autoResponse'] ? Container() : SizedBox(height: 16),
                              list['autoResponse'] || list['datetimeScheduled'] == null || list['datetimeScheduled'] == '' ? Container() : Text("${"scheduleMessage".tr()} ${list['datetimeScheduled']}."),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(width: 30),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            infoContainer('reqSuccessMsg'.tr()),
                            SizedBox(height: 16),
                            buttonTemplate(text: 'btnWait'.tr(), action: ()=>backAction(), width: double.infinity)
                          ],
                        )
                      )
                    ],
                  )
                ],
              ),
            ):loadingTemplate(),
          )
        ],
      ),
    );
  }

  Widget renderRequested(){
    if(list['receptionistId'] != null){
      if(widget.user['roomAttendant'] && widget.user['userId'] != list['informantUserId'] && widget.user['userId'] == list['receptionistId']){
        return Column(
          children: [
            textHorizontal('requestedFor'.tr(), list['informantName']??'-'),
            SizedBox(height: 16),
          ],
        );
      }

      if(widget.user['userId'] == list['informantUserId'] && widget.user['userId'] != list['receptionistId']){
        return Column(
          children: [
            textHorizontal('requestedBy'.tr(), list['receptionistName']??'-'),
            SizedBox(height: 16),
          ],
        );
      }
    }

    return Container();
  }

  getFileName(pdfUrl){
    var imgSplit = pdfUrl.toString().split('/');
    return imgSplit[imgSplit.length-1];
  }

  Widget attachment_new(list){
    List imageList = [];
    if(list['_attachment'] != null){
      for(var i = 1; i <= 5; i++){
        if(list['_attachment']['_mobileRequestAtt$i'] != null){
          imageList.add({'thumb': list['_attachment']['_mobileRequestThumb$i'], 'image': list['_attachment']['_mobileRequestAtt$i']});
        }
      }
    }

    return imageList.length > 0 ? Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('image'.tr(), style: TextStyle(color: textColor)),
        SizedBox(height: 5),
        LayoutBuilder(
          builder: (context, constraints) {
            var imageWidth = ((constraints.maxWidth-32)/5)-5;
            return 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: imageList[i]['thumb'] != null ? DecorationImage(image: NetworkImage(imageList[i]['thumb']), fit: BoxFit.cover) : DecorationImage(image: AssetImage('assets/image/error/ImageNotFound.png'), fit: BoxFit.cover)
                      ),
                    ),
                    onTap: ()=>navigateTo(context, PhotoPreviewGallery(title: 'image'.tr(), imageList: imageList, startIndex: i))
                );
              }),
            );
          },
        )
      ],
    ) : textVertical('image'.tr(), 'noImgAttach'.tr());
  }
}

// -----------------------------------------------------------------------------------------------------------------------------

class WebReqSuccessPendingPage extends StatefulWidget {
  Map<String, dynamic> data;
  final bool fromSearch;
  WebReqSuccessPendingPage({required this.data, this.fromSearch = false, super.key});

  @override
  State<WebReqSuccessPendingPage> createState() => _WebReqSuccessPendingPageState();
}

class _WebReqSuccessPendingPageState extends State<WebReqSuccessPendingPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: Column(
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Text('detail'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
          ),
          divider(),
          Expanded(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
              child: widget.data.isNotEmpty?Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(widget.data['title'], style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w600)),
                  SizedBox(height: 16),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.all(20),
                        decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                imageTiles(imageUrl: widget.data['image'] ?? "null", width: 110, height: 90),
                                SizedBox(width: 20),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(widget.data[U.langColumn(context, 'sub')], style: TextStyle(color: textColor, fontWeight: FontWeight.w600), maxLines: 2, overflow: TextOverflow.ellipsis),
                                      dashed(),
                                      Text(widget.data[U.langColumn(context, 'desc')]??'', style: TextStyle(color: textColor), maxLines: 3, overflow: TextOverflow.ellipsis)
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 20),
                            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(width: 30),
                      Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                width: double.infinity,
                                padding: EdgeInsets.all(12),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Icon(Icons.warning_amber_rounded, color: Colors.red),
                                    SizedBox(height: 5),
                                    Text('pending_info_success'.tr(), style: TextStyle(color: textColor), textAlign: TextAlign.center)
                                  ],
                                ),
                                decoration: BoxDecoration(
                                    color: Colors.red.withValues(alpha: 0.1),
                                    border: Border.all(color: Colors.red),
                                    borderRadius: BorderRadius.all(Radius.circular(12))
                                ),
                              ),
                              SizedBox(height: 16),
                              buttonTemplate(text: 'btnWait'.tr(), action: ()=>backAction(), width: double.infinity)
                            ],
                          )
                      )
                    ],
                  )
                ],
              ):loadingTemplate(),
            ),
          )
        ],
      ),
    );
  }

  Widget attachment_new(List images){
    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),
        LayoutBuilder(
          builder: (context, constraints) {
            var imageWidth = ((constraints.maxWidth-32)/5)-5;
            return 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());
  }

  backAction(){
    int count = 0;
    int page = widget.fromSearch ? 3 : 2;
    Navigator.of(context).popUntil((_) => count++ >= page);
  }
}

