/**
 * Author: Aparna Dulal
 * profile: https://github.com/ambikadulal
  */
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:naim/classes/Auth.dart';
import 'package:naim/classes/appdata.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/widgets/image_picker_handler.dart';
import 'package:naim/widgets/input.dart';
import 'package:path/path.dart' as pp;
import 'package:http/http.dart' as http;

import '../classes/cipher.dart';
import 'auth/createpass.dart';
import 'home.dart';

class BroadCastPage extends StatefulWidget {
  @override
  BroadCastPage();
  _BroadCastPageState createState() => _BroadCastPageState();
}

class _BroadCastPageState extends State<BroadCastPage> {
  TextEditingController titleController = TextEditingController();

  TextEditingController messageController = TextEditingController();

  bool showPassword = false;
  bool isSaving = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void setState(fn) {
    if (mounted) {
      super.setState(fn);
    }
  }

  @override
  Widget build(BuildContext context) {
    appData.context = context;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: appColors.backgroundColor(context),
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: appColors.armyColor(context),
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      body: Container(
        color: appColors.backgroundColor(context),
        padding: const EdgeInsets.only(left: 16, top: 15, right: 16),
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child: ListView(
            children: [
              Center(
                child: Text(
                  "Send Broadcast",
                  style: TextStyle(
                      fontSize: 25,
                      fontWeight: FontWeight.w500,
                      color: appColors.armyColor(context)),
                ),
              ),
              const SizedBox(
                height: 25,
              ),
              Center(
                child: Container(
                  width: 130,
                  height: 130,
                  decoration: BoxDecoration(
                      border: Border.all(
                          width: 4, color: appColors.armyColor(context)),
                      boxShadow: [
                        BoxShadow(
                            spreadRadius: 2,
                            blurRadius: 10,
                            color: Colors.black.withOpacity(0.1),
                            offset: const Offset(0, 10))
                      ],
                      shape: BoxShape.circle,
                      image: const DecorationImage(
                          fit: BoxFit.cover, image: AssetImage(appLogo))),
                ),
              ),
              const SizedBox(
                height: 35,
              ),
              buildTextField("Title", "", false, titleController),
              buildTextField("Message", "", false, messageController),
              const SizedBox(
                height: 35,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  getOutlinedButton(appColors.armyColor(context), "CANCEL", () {
                    Navigator.of(context).pop();
                  }),
                  const SizedBox(
                    width: 20,
                  ),
                  getElevatedButton(appColors.armyColor(context),
                      isSaving ? "Please Wait..." : "SEND BROADCAST", () {
                    if (!isSaving) {
                      updateProfile(context);
                    }
                  }),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  updateProfile(BuildContext context) async {
    setState(() {
      isSaving = true;
    });
    bool bGo = true;
    String msg = "";
    if (messageController.text.isEmpty) {
      bGo = false;
      msg = "Please enter a message";
    } else if (titleController.text.isEmpty) {
      bGo = false;
      msg = "Please enter message title";
    }

    if (!bGo) {
      setState(() {
        isSaving = false;
      });
      showAlert(context, AlertDialogType.ERROR, "Sorry", msg);
      return;
    }

    var request =
        http.MultipartRequest("POST", Uri.parse(appApi + "broadcast"));

    request.fields["message"] =
        encryptIt(messageController.text, appData.strPwd).base64;
    request.fields["title"] =
        encryptIt(titleController.text, appData.strPwd).base64;

    request.fields["token"] = appData.dbUser['token'];
    request.send().then((response) {
      http.Response.fromStream(response).then((onValue) {
        print(onValue.body);
        try {
          var data = json.decode(onValue.body);
          if (data["result"] != null) {
            if (data["result"] == "success") {
              print('it was success');
              showAlert(context, AlertDialogType.SUCCESS, "Success",
                  "Broadcast Sent");
              titleController.clear();
              messageController.clear();
            } else {
              showAlert(context, AlertDialogType.ERROR, "Error",
                  data["data"]["message"]);
            }
          }
        } catch (e) {
          print("Error: " + e.toString());
          showAlert(context, AlertDialogType.ERROR, "Error", e.toString());
        }
      });
    });

    setState(() {
      isSaving = false;
    });
  }

  Widget buildTextField(String labelText, String placeholder,
      bool isPasswordTextField, TextEditingController controller,
      {bool isMultiline = false}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 35.0),
      child: TextField(
        keyboardType:
            isMultiline ? TextInputType.multiline : TextInputType.text,
        maxLength: 160,
        style: TextStyle(color: appColors.textColor(context)),
        maxLines: isMultiline ? 4 : 1,
        controller: controller,
        obscureText: isPasswordTextField ? showPassword : false,
        decoration: InputDecoration(
          suffixIcon: isPasswordTextField
              ? IconButton(
                  onPressed: () {
                    setState(() {
                      showPassword = !showPassword;
                    });
                  },
                  icon: const Icon(
                    Icons.remove_red_eye,
                    color: Colors.grey,
                  ),
                )
              : null,
          contentPadding: const EdgeInsets.only(bottom: 3),
          labelText: labelText,
          labelStyle: TextStyle(
            fontSize: 17,
            fontWeight: FontWeight.bold,
            color: appColors.textColorSecondary(context),
          ),
          floatingLabelBehavior: FloatingLabelBehavior.always,
          hintText: placeholder,
          hintStyle: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: appColors.textColorSecondary(context),
          ),
        ),
      ),
    );
  }
}
