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

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mime/mime.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:peasmartcare/blocs/feedback_detail/feedback_detail_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/customer_info.dart';
import 'package:peasmartcare/components/full_photo.dart';
import 'package:peasmartcare/components/header_content.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/feedback_detail_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/utils/extension_file_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/error_box.dart';
import 'package:peasmartcare/widgets/loading.dart';

class FeedbackDetail extends StatefulWidget {
  @override
  _FeedbackDetailState createState() => _FeedbackDetailState();
}

class _FeedbackDetailState extends State<FeedbackDetail> {
  TextStyle textStyle = TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
  TextStyle errortyle = TextStyle(color: Colors.red[900], fontSize: 18);

  @override
  void initState() {
    context.read<FeedbackDetailBloc>().add(FeedbackDetailGetData());

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PEAAppBar(
        title: "เสียงของลูกค้า",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      body: BodyLayout(
        header: CustomerInfo(),
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                HeaderContent(
                  title: "เสียงของลูกค้า",
                  icon: ImageAsset.complaintImg,
                ),
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 50),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _userInfo(),
            Stack(
              children: <Widget>[
                HeaderContent(
                  title: "การไฟฟ้าที่ท่านให้ข้อเสนอแนะ/ข้อคิดเห็น",
                  icon: ImageAsset.complaintImg,
                  maxLines: 2,
                ),
                Positioned(
                  child: _peaLocation(),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _userInfo() {
    TextStyle textStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 18);
    TextStyle textLabelStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 20, fontWeight: FontWeight.bold);
    double betweebBoxSize = 5;
    return BlocListener<FeedbackDetailBloc, FeedbackDetailState>(
      listener: (context, state) {
        if (state is FeedbackDetailErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<FeedbackDetailBloc, FeedbackDetailState>(
        builder: (context, state) {
          if (state is FeedbackDetailLoading) {
            return Loading();
          } else if (state is FeedbackDetailLoaded) {
            FeedbackDetailModel feedback = state.result;
            return Center(
              child: Container(
                constraints: BoxConstraints(maxWidth: 500),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: 40,
                    ),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("ประเภทเสียงของลูกค้า", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.feedbackTypeName, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("ผู้ให้ข้อเสนอแนะ/ข้อคิดเห็น", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.name, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("บัตรประชาชน", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.idCard, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("อีเมล", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.email, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("สถานที่ติดต่อกลับ", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.contactLocation, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                  ],
                ),
              ),
            );
          } else if (state is FeedbackDetailError) {
            return ErrorBox(
              message: state.message,
            );
          }
          return EmptyBox();
        },
      ),
    );
  }

  Widget _peaLocation() {
    TextStyle textStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 18);
    TextStyle textFileStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 18, decoration: TextDecoration.underline);
    TextStyle textLabelStyle = TextStyle(color: Color(AppData.purpleColor), fontSize: 20, fontWeight: FontWeight.bold);
    double betweebBoxSize = 5;

    return BlocListener<FeedbackDetailBloc, FeedbackDetailState>(
      listener: (context, state) {
        if (state is FeedbackDetailErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<FeedbackDetailBloc, FeedbackDetailState>(
        builder: (context, state) {
          if (state is FeedbackDetailLoading) {
            return Loading();
          } else if (state is FeedbackDetailLoaded) {
            FeedbackDetailModel feedback = state.result;

            return Center(
              child: Container(
                constraints: BoxConstraints(maxWidth: 500),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: 110,
                    ),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("จังหวัด", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.province, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("การไฟฟ้า", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.branchName, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("สถานที่เกิดเหตุ", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.crimeScene, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("หมายเลขผู้ใช้ไฟฟ้า", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.caNumber, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("ประเภทข้อเสนอแนะ/ข้อคิดเห็น", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.suggestionTypeName, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("หัวข้อ", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.subjectSuggestionTypeName, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("รายละเอียด", style: textLabelStyle),
                              SizedBox(height: 5),
                              Text(feedback.detail, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: new BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("เอกสารแนบ", style: textLabelStyle),
                              SizedBox(height: 5),
                              feedback.attachmentFileList != null
                                  ? Column(
                                      children: feedback.attachmentFileList.map((item) {
                                        return InkWell(
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Text(
                                                item.fileName,
                                                style: textFileStyle,
                                              ),
                                              Divider(color: Colors.grey[400]),
                                            ],
                                          ),
                                          onTap: () async {
                                            // Uint8List bytes = base64.decode(item.fileContentBase64);
                                          
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                  builder: (context) => FullPhoto(
                                                        imageContent: item.fileUrl,
                                                        // filename: "${item.fileName}.${item.mimeType}",
                                                        filename: item.fileName,
                                                      )),
                                            );
                                            // String mimeType = lookupMimeType('file', headerBytes: bytes);
                                            // if (ExtensionFileUtil.fromMimeType(mimeType) != null) {
                                            //   String filePath = await _createFileFromString(item.fileContentBase64);

                                            //   OpenFile.open(filePath);
                                            // }
                                          },
                                        );
                                      }).toList(),
                                    )
                                  : EmptyBox(),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: betweebBoxSize),
                    Container(
                      constraints: BoxConstraints(minHeight: 100),
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25, right: 25),
                      child: Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        color: Color(AppData.whiteColor),
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: [
                                  Text("สถานะ", style: textLabelStyle),
                                  Text(" : "),
                                  Text(feedback.status,
                                      style: TextStyle(
                                        color: Color(AppData.purpleColor),
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold,
                                      )),
                                ],
                              ),
                              // Divider(color: Colors.grey[400]),
                              SizedBox(height: 10),
                              Text("การดำเนินการ", style: textLabelStyle),

                              SizedBox(height: 5),
                              feedback.feedbackStatusLogList != null
                                  ? Column(
                                      children: feedback.feedbackStatusLogList.map((item) {
                                        return Column(
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(item.status, style: textStyle),
                                            // (item.detail != null && item.detail != "") ? Text(item.detail, style: textStyle) : EmptyBox(heightFactor: 0),
                                            Text(item.date, style: textStyle),
                                            Divider(color: Colors.grey[400]),
                                          ],
                                        );
                                      }).toList(),
                                    )
                                  : EmptyBox(),
                              // Text(feedback.detail, style: textStyle),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          }
          return EmptyBox();
        },
      ),
    );
  }

  Future<String> _createFileFromString(String encodedStr) async {
    Uint8List bytes = base64.decode(encodedStr);

    String mimeType = lookupMimeType('file', headerBytes: bytes);

    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".${ExtensionFileUtil.fromMimeType(mimeType)}");
    await file.writeAsBytes(bytes);
    return file.path;
  }
}
