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/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 WebMessageBroadcastPage extends StatefulWidget {
  final Map<String, dynamic> user;
  final List tenants;
  const WebMessageBroadcastPage(this.user, this.tenants, {super.key});

  @override
  State<WebMessageBroadcastPage> createState() => _WebMessageBroadcastPageState();
}

class _WebMessageBroadcastPageState extends State<WebMessageBroadcastPage> {
  List<String> selectedTenants = [];

  bool isDisabled = true;
  String? textContent;
  String _filePath = '';
  String _fileName = '';
  String _fileExt = '';
  PlatformFile? fileX;
  var _prevImg;
  File? file;
  int count = 0;
  bool isSending = false;
  

  selectTenant(code) {
    setState(() {
      if (selectedTenants.contains(code)) {
        selectedTenants.remove(code);
      } else {
        selectedTenants.add(code);
      }
    });
  }

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

  sendMyMessage() async {
    var recTenant = selectedTenants.join(',');
    var params = {'recipientTenant': recTenant, 'text': textContent};
    var data;
    if (file != null || fileX != null) {
      var _file = await MultipartFile.fromBytes(fileX!.bytes!, filename: fileX!.name);
      FormData formData = FormData.fromMap({
        'file': _file,
      });
      data = formData;
    }
    setState(() {
      isSending = true;
    });
    var res = await ApiAuthProvider().postData('/api/messages/broadcast', params, data);
    if (res != null) {
      Navigator.pop(context, 'pop');
    }
    else{
      setState(() {
        isSending = false;
      });
    }
  }

  @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(
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('composeMessage'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                GestureDetector(
                  child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                  onTap: ()=>navigateBack(context),
                )
              ],
            ),
          ),
          divider(),
          Expanded(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('selectRecipient'.tr(), style: TextStyle(color: textColor)),
                        SizedBox(height: 10),
                        Container(
                          width: double.infinity,
                          padding: EdgeInsets.symmetric(vertical: widget.tenants.isNotEmpty ? 12 : 20, horizontal: 20),
                          child: widget.tenants.isNotEmpty ? Column(
                            children: List.generate(widget.tenants.length, (i){
                              return GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.symmetric(vertical: 7),
                                  color: Colors.white,
                                  child: Row(
                                    children: [
                                      Icon(selectedTenants.contains(widget.tenants[i]['code'])?Icons.check_box_rounded:Icons.check_box_outline_blank_rounded, color: selectedTenants.contains(widget.tenants[i]['code'])?primaryColor:textColor.withValues(alpha: 0.15)),
                                      SizedBox(width: 20),
                                      Expanded(
                                        child: Container(
                                          padding: EdgeInsets.all(5),
                                          child: Row(
                                            children: [
                                              Container(
                                                width: 30, height: 30, alignment: Alignment.center,
                                                child: Text(widget.tenants[i]['name'][0], style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                                                decoration: BoxDecoration(
                                                    color: Color(U.getColor(widget.tenants[i]['code'])),
                                                    borderRadius: BorderRadius.all(Radius.circular(30))
                                                ),
                                              ),
                                              SizedBox(width: 10),
                                              Expanded(
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    Text(widget.tenants[i]['name'], style: TextStyle(color: textColor)),
                                                    Text(widget.tenants[i]['description'], style: TextStyle(color: textColor, fontSize: 12)),
                                                  ],
                                                ),
                                              )
                                            ],
                                          ),
                                          decoration: BoxDecoration(
                                              color: selectedTenants.contains(widget.tenants[i]['code'])?Color(0xff26DA17).withValues(alpha: 0.2):Colors.white,
                                              borderRadius: BorderRadius.all(Radius.circular(10))
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                onTap: ()=>selectTenant(widget.tenants[i]['code']),
                              );
                            }),
                          ) : Text('allInformantsInfo'.tr(), style: TextStyle(color: textColor)),
                          decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                        )
                      ],
                    ),
                  ),
                  SizedBox(width: 30),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('message'.tr(), style: TextStyle(color: textColor)),
                        SizedBox(height: 10),
                        SizedBox(
                          width: double.infinity,
                          child: TextField(
                            style: const TextStyle(fontSize: 14, color: Colors.black),
                            keyboardType: TextInputType.multiline,
                            minLines: 5,
                            maxLines: 5,
                            maxLength: 256,
                            decoration: InputDecoration(
                              counterText: '',
                              hintText: 'writeMessage'.tr()+'..',
                              hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                              filled: true,
                              fillColor: backgroundColor,
                              hoverColor: Colors.black.withValues(alpha: 0.1),
                              contentPadding: EdgeInsets.all(20),
                              border: InputBorder.none,
                              enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: textColor.withValues(alpha: 0.15))),
                              focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: primaryColor)),
                              isDense: true
                            ),
                            onChanged: (String value) {
                              buttonController(value);
                            },
                          ),
                        ),
                        SizedBox(height: 20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 7, horizontal: 15),
                                child: Row(
                                  children: [
                                    U.iconsax('paperclip-2', size: 20),
                                    SizedBox(width: 5),
                                    Text(_filePath == '' ? 'addAttachment'.tr() : 'editAttachment'.tr())
                                  ],
                                ),
                                decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(50))),
                              ),
                              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!;
                                    fileX = result.files.single;
                                    _prevImg = Image.memory(fileX!.bytes!);
                                  }
                                }
                                setState(() {});
                              }
                            ),
                            GestureDetector(
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 7, horizontal: 15),
                                child: Row(
                                  children: [
                                    Text('sendNow'.tr(), style: TextStyle(color: Colors.white)),
                                    SizedBox(width: 5),
                                    U.iconsax('bold/send-1', size: 20, color: Colors.white),
                                  ],
                                ),
                                decoration: BoxDecoration(color: isDisabled?Colors.black26:primaryColor, borderRadius: BorderRadius.all(Radius.circular(50))),
                              ),
                              onTap: isDisabled ? null : ()=>sendMyMessage(),
                            )
                          ],
                        ),
                        _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' ? _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: () {
                                  setState(() {
                                    _filePath = '';
                                    _fileName = '';
                                    fileX = null;
                                  });
                                },
                              )
                            ],
                          ),
                        ) : Container()
                      ],
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
