import 'dart:convert';
import 'dart:typed_data';

import 'package:camera/camera.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:page_transition/page_transition.dart';
import 'package:photo_view/photo_view.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/layouts/components/camera.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:image/image.dart' as img;

class PhotoChat extends StatefulWidget {
  final data;
  final ImageSource? media;
  final bool? isBroadcast;
  final Uint8List? image;

  PhotoChat(this.data, this.media, this.isBroadcast, this.image);

  @override
  _PhotoChatState createState() => _PhotoChatState();
}

class _PhotoChatState extends State<PhotoChat> {
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  TextEditingController controllerPesan = new TextEditingController();
  Uint8List? image;

  Future getImage() async {
//    print('photochat in');
    XFile? pickedFile;
    if(widget.media == ImageSource.camera){
      await availableCameras().then((camera) => Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: OpenCamera(cameras: camera))).then((value) async{
        if(value!=null){
          pickedFile = value;
        }
      }));
    }
    else{
      pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
    }

    if (pickedFile != null) {
      var imagess = img.decodeImage(await pickedFile!.readAsBytes());
      var imgPercent = (1000 / (imagess!.width / 100)).toDouble();
      if (imagess.width > 1000) {
        imagess = img.copyResize(imagess, width: ((imagess.width / 100) * imgPercent).toInt(), height: ((imagess.height / 100) * imgPercent).toInt());
      }
      var compressed = img.encodeJpg(imagess, quality: 60);
      setState(() => image = compressed);
    } else {
      Navigator.of(context).pop(null);
    }
  }

  @override
  void initState() {
    if (widget.image == null) {
      getImage();
    } else {
      image = widget.image!;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        elevation: 0,
        bottomOpacity: 0,
        titleSpacing: 0,
        title: Text('sendPicture'.tr(), style: TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
        backgroundColor: Colors.black.withValues(alpha: 0.4),
        leading: GestureDetector(
          child: U.iconsax('arrow-left', color: Colors.white),
          onTap: () => Navigator.of(context).pop(),
        ),
      ),
      body: Center(
        child: Container(
          width: U.bodyWidth(context),
          child: Stack(
            children: [
              Container(
                  child: image != null ? PhotoView(
                    maxScale: 5.0,
                    minScale: 0.3,
                    imageProvider: MemoryImage(kIsWeb ? widget.image! : image!),
                  )
                      : Container()),
              Container(
                alignment: Alignment.bottomCenter,
                child: Container(
//              width: double.infinity,
                  padding: const EdgeInsets.all(10),
                  color: Colors.black54,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(right: 5),
                          child: TextField(
                              controller: controllerPesan,
                              maxLength: 256,
                              buildCounter: (BuildContext? context, {int? currentLength, int? maxLength, bool? isFocused}) => null,
                              style: TextStyle(color: Colors.white, fontSize: 15),
                              keyboardType: TextInputType.multiline,
                              minLines: 1,
                              maxLines: 5,
                              decoration: InputDecoration(
                                hintText: 'writeMessage'.tr(),
                                hintStyle: TextStyle(fontSize: 15, color: Colors.white54),
                                contentPadding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                                border: InputBorder.none,
                              )),
                        ),
                      ),
                      Expanded(
                        flex: 0,
                        child: SizedBox(
                            width: 50,
                            height: 50,
                            child: ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all<Color>(primaryColor),
                                shape: MaterialStateProperty.all<RoundedRectangleBorder>(RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(50),
                                )),
                                elevation: MaterialStateProperty.all(2),
                                padding: MaterialStateProperty.all(const EdgeInsets.only(left: 1)),
                              ),
                              child: Image.asset('assets/image/icon/Send.png', width: 25, height: 25),
                              onPressed: () async {
                                var data = widget.data;
                                data['text'] = controllerPesan.text.trim();
                                data['images'] = kIsWeb ? base64Encode(widget.image!) : base64Encode(image!);

                                Navigator.of(context).pop(data);
                              },
                            )),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}