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

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.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 MobReqSuccessPage extends StatefulWidget {
  final Map<String, dynamic> user;
  final String ticketNo;
  final bool fromSearch;
  const MobReqSuccessPage({required this.user, required this.ticketNo, this.fromSearch = false, super.key});

  @override
  State<MobReqSuccessPage> createState() => _MobReqSuccessPageState();
}

class _MobReqSuccessPageState extends State<MobReqSuccessPage> {
  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);
    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);
  }

  bool _timeLimit = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        elevation: 0,
        bottomOpacity: 0,
        backgroundColor: backgroundColor,
        leading: GestureDetector(
          child: Icon(Icons.close_rounded, color: textColor),
          onTap: ()=>backAction(),
        ),
        titleSpacing: 0,
        title: Text('detail'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
      ),
      body: Column(
        children: [
          divider(),
          Expanded(
            child: list.isNotEmpty?Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(list[U.langColumn(context, 'requestGroupDescription')], style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                    requestTiles(
                        image: list['_requestImage'] ?? "null",
                        title: list[U.langColumn(context, 'requestSubject')],
                        subtitle: list[U.langColumn(context, '_subjectDescription')]??'',
                        border: true
                    ),
                    SizedBox(height: 16),
                    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(
                            onTap: kIsWeb ? () async{
                              Uri _url = Uri.parse(list['_mobileResponseAttachment']);
                              await canLaunchUrl(_url) ? await launchUrl(_url) : print('Could not launch $_url');
                              // html.window.open(list['responseAttachment'], '_blank');
                            } : () 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']));
                            },
                            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))
                                    ],
                                  ),
                                )
                            )
                        ):GestureDetector(
                            child: Image.network(list['_mobileResponseAttachment'], fit: BoxFit.cover, width: double.infinity, height: U.bodyWidth(context)/(kIsWeb?2.1:1.7), loadingBuilder:(BuildContext? context, Widget? child,ImageChunkEvent? loadingProgress) {
                              if (loadingProgress == null) return child!;
                              return Container(
                                height: U.bodyWidth(context)/(kIsWeb?2.1: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(height: 24),
                    infoContainer('reqSuccessMsg'.tr())
                  ],
                ),
              ),
            ):_timeLimit ? showButton(context) : loadingTemplate(() {if(mounted) setState(()=>_timeLimit=true);},),
          ),
          list.isNotEmpty?Column(
            children: [
              divider(),
              SafeArea(
                child: Container(
                  alignment: Alignment.bottomCenter,
                  width: U.bodyWidth(context), color: Colors.white,
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                  child: buttonTemplate(text: 'btnWait'.tr(), action: ()=>backAction()),
                ),
              )
            ],
          ):Container()
        ],
      ),
    );
  }

  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){
    var imageWidth = ((U.bodyWidth(context)-32)/5)-5;
    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),
        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 MobReqSuccessPendingPage extends StatefulWidget {
  final Map<String, dynamic> data;
  final bool fromSearch;
  const MobReqSuccessPendingPage({required this.data, this.fromSearch = false, super.key});

  @override
  State<MobReqSuccessPendingPage> createState() => _MobReqSuccessPendingPageState();
}

class _MobReqSuccessPendingPageState extends State<MobReqSuccessPendingPage> {
  bool _timeLimit = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        elevation: 0,
        bottomOpacity: 0,
        backgroundColor: backgroundColor,
        leading: GestureDetector(
          child: Icon(Icons.close_rounded, color: textColor),
          onTap: ()=>backAction(),
        ),
        titleSpacing: 0,
        title: Text('detail'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
      ),
      body: Column(
        children: [
          divider(),
          Expanded(
            child: widget.data.isNotEmpty?Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: SingleChildScrollView(
                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),
                    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))
                      ),
                    )
                  ],
                ),
              ),
            ):_timeLimit ? showButton(context) : loadingTemplate(() {if(mounted) setState(()=>_timeLimit=true);},),
          ),
          Column(
            children: [
              divider(),
              SafeArea(
                child: Container(
                  alignment: Alignment.bottomCenter,
                  width: U.bodyWidth(context), color: Colors.white,
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                  child: buttonTemplate(text: 'btnWait'.tr(), action: ()=>backAction()),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  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());
  }

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

