import 'dart:io';

import 'package:dio/dio.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.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';

class MobMessageBroadcastPage extends StatefulWidget {
  final user;
  final recipient;
  const MobMessageBroadcastPage(this.user, this.recipient, {super.key});

  @override
  State<MobMessageBroadcastPage> createState() => _MobMessageBroadcastPageState();
}

class _MobMessageBroadcastPageState extends State<MobMessageBroadcastPage> {
  final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();

  bool _isDisabled = true;
  List data = [];
  String listOfTenant = '';
  String? textContent;
  String _filePath = '';
  String _fileName = '';
  String _fileExt = '';
  PlatformFile? fileX;
  var _prevImg;
  File? file;
  int count = 0;
  bool _isSending = false;

  _buttonController(value) {
    textContent = value;
    bool activate = true;
    if (value.length == 0) {
      activate = false;
    }
    setState(() {
      _isDisabled = !activate;
    });
  }

  _sendMyMessage() async {
    var recTenant = listOfTenant;
    var params = {'recipientTenant': recTenant, 'text': textContent};
    var data;
    if (file != null || fileX != null) {
      var _file;
      _file = kIsWeb ? await MultipartFile.fromBytes(fileX!.bytes!, filename: fileX!.name) : await MultipartFile.fromFile(_filePath);
      FormData formData = FormData.fromMap({
        'file': _file,
      });
      data = formData;
    }
    setState(() {
      _isSending = true;
    });
    var res = await _apiAuthProvider.postData('/api/messages/broadcast', params, data);
    // print("res : ${res.toString()}");
    if (res != null && mounted) {
      Navigator.pop(context, 'pop');
    }
    else{
      setState(() {
        _isSending = false;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    data = widget.recipient;
    if (data.isNotEmpty) {
      // int? totalLength = 96;
      data.sort((a, b) => (a['name'].length).compareTo(b['name'].length));
      listOfTenant = data.map((e) => e['code']).join(',');
      // data.forEach((e) {
      //   totalLength = (totalLength! - e['name'].length) as int?;
      //   totalLength! >= 0 ? count++ : null;
      //   listOfTenant += ',' + e['code'];
      // });
    }
//    print(data);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBarTemplate(context: context, title: 'composeMessage'.tr(), action: [
        !_isSending ? Padding(
          padding: EdgeInsets.only(right: 20),
          child: GestureDetector(
            child: U.iconsax('bold/send-1', size: 30, color: _isDisabled ? primaryColor.withValues(alpha: 0.5):primaryColor),
            onTap: _isDisabled ? null : ()=>_sendMyMessage(),
          ),
        ):Container()
      ]),
      body: !_isSending ? Column(
        children: [
          divider(),
          Expanded(
            child: Container(
                alignment: Alignment.topCenter,
                width: U.bodyWidth(context),
                padding: EdgeInsets.fromLTRB(15, 15, 15, 0),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      widget.recipient != null ? Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(top: 4),
                            child: Text('to'.tr()),
                          ),
                          data.isNotEmpty?Expanded(
                              child: Wrap(
                                children: List.generate(data.length, (i) {
                                  return Container(
                                    decoration: BoxDecoration(color: Color(U.getColor(data[i]['code'])), borderRadius: BorderRadius.all(Radius.circular(2))),
                                    padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                                    margin: EdgeInsets.fromLTRB(8, 0, 0, 8),
                                    child: Text(data[i]['name'], style: TextStyle(color: Colors.white)),
                                  );
                                }),
                              )
                          ):Container(
                            decoration: BoxDecoration(color: Color(U.getColor('allInformants')), borderRadius: BorderRadius.all(Radius.circular(2))),
                            padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                            margin: EdgeInsets.fromLTRB(8, 0, 0, 8),
                            child: Text(
                              "allInformants".tr(),
                              style: TextStyle(color: Colors.white),
                            ),
                          )
                        ],
                      ) : Container(),
                      SizedBox(height: 16),
                      Text('message'.tr()),
                      SizedBox(height: 8),
                      TextField(
                        maxLines: null,
                        maxLength: 256,
                        decoration: InputDecoration(
                            border: OutlineInputBorder(),
                            focusedBorder: OutlineInputBorder(
                              borderSide: const BorderSide(color: Colors.black45),
                            )),
                        onChanged: (String value) async {
                          _buttonController(value);
                        },
                      ),
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Container(
                          child: GestureDetector(
                              child: Container(
                                child: Row(
                                  children: [
                                    Icon(Icons.attach_file_outlined),
                                    SizedBox(
                                      width: 4,
                                    ),
                                    Text(_filePath == '' ? 'addAttachment'.tr() : 'editAttachment'.tr())
                                  ],
                                ),
                              ),
                              onTap: () async {
                                var allowedExt = ['jpg', 'pdf', 'png', 'jpeg'];
                                _filePath = '';
                                _fileName = '';
                                FilePickerResult? result = await FilePicker.platform.pickFiles(
                                  type: FileType.custom,
                                  allowedExtensions: allowedExt,
                                  withReadStream: false,
                                );
                                if (result != null) {
                                  PlatformFile _file = result.files.first;
                                  if (!allowedExt.contains(_file.extension)) {
                                    final snackBar = SnackBar(
                                        content: Row(
                                          children: [
                                            Icon(
                                              Icons.warning,
                                              color: Colors.yellow,
                                              size: 18,
                                            ),
                                            SizedBox(
                                              width: 8,
                                            ),
                                            Text(
                                              'unsupportedFile'.tr(),
                                              style: TextStyle(),
                                              overflow: TextOverflow.fade,
                                              maxLines: 2,
                                            )
                                          ],
                                        ));
                                    ScaffoldMessenger.of(context).showSnackBar(snackBar);
                                  } else {
                                    _fileName = _file.name;
                                    _fileExt = _file.extension!;
                                    if (!kIsWeb) {
                                      file = File(result.files.single.path!);
                                      _filePath = _file.path!;
                                    } else {
                                      fileX = result.files.single;
                                      _prevImg = Image.memory(fileX!.bytes!);
                                    }
                                  }
                                }
                                setState(() {});
                              }),
                        ),
                      ),
                      _fileName != '' ? Padding(
                        padding: EdgeInsets.only(top: 12),
                        child: Text(_fileName, overflow: TextOverflow.ellipsis),
                      ) : Container(),
                      _filePath != '' || fileX != null ? Padding(
                        padding: EdgeInsets.only(top: 12, bottom: 12),
                        child: Stack(
                          children: [
                            _fileExt != 'pdf' ? !kIsWeb ? Image.file(File(_filePath)) : _prevImg != null ? _prevImg : Container() : Padding(
                              padding: EdgeInsets.only(top: 6, left: 8),
                              child: Row(
                                children: [
                                  Icon(Icons.picture_as_pdf),
                                  SizedBox(width: 6),
                                  Text('pdfFile'.tr())
                                ],
                              ),
                            ),
                            GestureDetector(
                              child: Container(
                                width: double.infinity,
                                height: 36,
                                padding: EdgeInsets.only(top: 6, right: 8),
                                decoration: BoxDecoration(color: Colors.transparent.withValues(alpha: 0.5), gradient: LinearGradient(end: Alignment.bottomCenter, begin: Alignment.center, colors: [Color(0xffDADADA), Colors.white])),
                                child: Align(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      Text('delete'.tr()),
                                      Icon(Icons.clear)
                                    ],
                                  ),
                                  alignment: Alignment.topRight,
                                ),
                              ),
                              onTap: () {
                                // print('delete please!');
                                setState(() {
                                  _filePath = '';
                                  _fileName = '';
                                  fileX = null;
                                });
                              },
                            )
                          ],
                        ),
                      ) : Container()
                    ],
                  ),
                )
            ),
          )
        ],
      ):loadingTemplateNoVoid(),
    );
  }
}
