import 'dart:convert';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shinewash_employee/api/api.dart';
import 'package:shinewash_employee/models/employee_review.dart';
import 'package:shinewash_employee/models/employee_skill.dart';
import 'package:shinewash_employee/screens/appointment_process.dart';
import 'package:shinewash_employee/screens/edit_profile.dart';

import 'custom_drawer.dart';
import 'home_page.dart';

const darkBlue = Color(0xFF265E9E);
const extraDarkBlue = Color(0xFF91B4D8);
const ratingStar = Color(0xFFFECD03);

class EmployeeProfile extends StatefulWidget {
  @override
  _EmployeeProfileState createState() => _EmployeeProfileState();
}

class _EmployeeProfileState extends State<EmployeeProfile>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  var showSnipper = false;
  var image = '';
  // var _previousID;
  var name = '';
  var email = '';
  var description = '';
  var skills = [];
  int onGoing;
  int complete;
  List<int> skillLength = [];

  List<Review> r = List<Review>();

  List<Skill> s = List<Skill>();

  List<String> allImages = [];
  List<int> allImagesId = [];

  bool skilldatavisible = false;
  bool skilldatanotvisible = true;
  bool checkConnectivity;

  @override
  void initState() {
    super.initState();
    checkConnection();
    // _previousID = widget.previousEmployeeId;
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(_handleTabSelection);
    _getProfile();
    _getReview();
    showAllImage();
  }

  void _handleTabSelection() {
    setState(() {});
  }

  Future<void> checkConnection() async {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {
        setState(() {
          checkConnectivity = true;
        });
      } else {
        {
          setState(() {
            checkConnectivity = false;
          });
        }
      }
    });
  }

  Future<void> _getProfile() async {
    setState(() {
      showSnipper = true;
    });
    var res = await CallApi().getWithToken('employee');
    var body = json.decode(res.body);
    var theData = body['data'];
    // print('thedata is = $theData');
    image = theData['completeImage'];
    name = theData['name'];
    email = theData['email'];
    description = theData['description'];
    skills = theData['service'];
    onGoing = theData['ongoing'];
    complete = theData['complete'];
    // print('the skill is ${skills[0]['service_name']}');
    // print('the skill is $description');
    for (int i = 0; i < skills.length; i++) {
      Map<String, dynamic> map = skills[i];
      s.add(Skill.fromJson(map));
    }

    if (skills.length > 0) {
      skilldatavisible = true;
      skilldatanotvisible = false;
    } else {
      skilldatavisible = false;
      skilldatanotvisible = true;
    }
    skillLength = [];
    for (int j = 0; j < skills.length; j++) {
      skillLength.add(j);
    }
    setState(() {
      showSnipper = false;
    });
  }

  Future<Review> _getReview() async {
    setState(() {
      showSnipper = true;
    });
    var res = await CallApi().getWithToken('coworker_review');
    var body = json.decode(res.body);
    var theData = body['data'];
    var reviewis = theData;
    for (int i = 0; i < reviewis.length; i++) {
      Map<String, dynamic> map = reviewis[i];
      r.add(Review.fromjson(map));
    }
    setState(() {
      showSnipper = false;
    });
  }

  Future<void> showAllImage() async {
    setState(() {
      showSnipper = true;
    });
    var res = await CallApi().getWithToken('show_portfolio');
    var body = json.decode(res.body);
    var theData = body['data'];
    for (int i = 0; i < theData.length; i++) {
      allImages.add(theData[i]['image']);
      allImagesId.add(theData[i]['id']);
    }
    // print('all images is $allImages');
  }

  Future<void> deleteImage(id) async {
    setState(() {
      showSnipper = true;
    });
    var res = await CallApi().getWithToken('delete_portfolio/$id');
    var body = json.decode(res.body);
    // print('body is $body');
    Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => EmployeeProfile(),
        ));
    setState(() {
      showSnipper = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize:
            Size.fromHeight(MediaQuery.of(context).size.height / 2.9), //3.5
        child: ModalProgressHUD(
          inAsyncCall: showSnipper,
          child: SafeArea(
            child: CustomAppBar(
              tabController: _tabController,
              clipRRect: Center(
                child: Column(
                  children: [
                    Container(
                      // margin: EdgeInsets.only(top: MediaQuery.of(context).size.height / 16),
                      margin: EdgeInsets.only(top: 30.0, bottom: 5.0),
                      // color: Colors.red,
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.white, width: 3),
                          shape: BoxShape.circle),
                      height: 100.0,
                      width: 100.0,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: Image.network(
                          image,
                          fit: BoxFit.cover,
                          height:
                              MediaQuery.of(context).size.height / 3.5, //4.5
                          width: MediaQuery.of(context).size.width,
                          alignment: Alignment.topCenter,
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 5.0),
                      child: Text(
                        '$name',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontFamily: 'FivoSansMedium',
                        ),
                      ),
                    ),
                    Text(
                      '$email',
                      style: TextStyle(
                        color: Color(0xFF91B4D8),
                        fontSize: 14,
                        fontFamily: 'FivoSansRegular',
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      body: ModalProgressHUD(
          inAsyncCall: showSnipper,
          child: TabBarView(
            children: [
              //first tab
              Container(
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Container(
                    height: MediaQuery.of(context).size.height / 1.8,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '$description',
                          style: TextStyle(
                            color: darkBlue,
                            fontSize: 14,
                            fontFamily: 'FivoSansRegular',
                          ),
                        ),
                        SizedBox(
                          height: 20.0,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'SKILLS',
                              style: TextStyle(
                                color: darkBlue,
                                fontSize: 15,
                                fontFamily: 'FivoSansMedium',
                              ),
                            ),
                            Visibility(
                              visible: skilldatavisible,
                              child: Wrap(
                                  children: skillLength
                                      .map((i) => Container(
                                            margin: EdgeInsets.all(7.0),
                                            padding: EdgeInsets.all(7.0),
                                            decoration: BoxDecoration(
                                              // color: Colors.red,
                                              border: Border.all(
                                                  color: extraDarkBlue),
                                              borderRadius: BorderRadius.all(
                                                Radius.circular(5.0),
                                              ),
                                            ),
                                            child: Text(
                                              s[i].name,
                                              style: TextStyle(
                                                color: darkBlue,
                                                fontSize: 15,
                                                fontFamily: 'FivoSansMedium',
                                              ),
                                            ),
                                          ))
                                      .toList()),
                            ),
                            Visibility(
                              visible: skilldatanotvisible,
                              child: Container(
                                height: 100.0,
                                width: MediaQuery.of(context).size.width,
                                child: Center(
                                  child: Text(
                                    "No Skills Found",
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 16,
                                      fontFamily: 'FivoSansMedium',
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 20.0,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'TASK',
                              style: TextStyle(
                                color: darkBlue,
                                fontSize: 15,
                                fontFamily: 'FivoSansMedium',
                              ),
                            ),
                            SizedBox(
                              height: 15.0,
                            ),
                            InkWell(
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    'On Going Task',
                                    style: TextStyle(
                                      color: darkBlue,
                                      fontSize: 18,
                                      fontFamily: 'FivoSansMedium',
                                    ),
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        "$onGoing",
                                        style: TextStyle(
                                          color: extraDarkBlue,
                                          fontSize: 14,
                                          fontFamily: 'FivoSansRegular',
                                        ),
                                      ),
                                      Icon(
                                        Icons.chevron_right,
                                        color: extraDarkBlue,
                                        size: 30.0,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              onTap: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => AppointmentProcess(
                                          // selectIndex: 0,
                                          ),
                                    ));
                              },
                            ),
                            SizedBox(
                              height: 10.0,
                            ),
                            InkWell(
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    'Completed Task',
                                    style: TextStyle(
                                      color: darkBlue,
                                      fontSize: 18,
                                      fontFamily: 'FivoSansMedium',
                                    ),
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        '$complete',
                                        style: TextStyle(
                                          color: extraDarkBlue,
                                          fontSize: 14,
                                          fontFamily: 'FivoSansRegular',
                                        ),
                                      ),
                                      Icon(
                                        Icons.chevron_right,
                                        color: extraDarkBlue,
                                        size: 30.0,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              onTap: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => AppointmentProcess(
                                          // selectIndex: 1,
                                          ),
                                    ));
                              },
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 20.0,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              //second tab
              SingleChildScrollView(
                child: ModalProgressHUD(
                  inAsyncCall: showSnipper,
                  child: Container(
                    margin: EdgeInsets.only(top: 30.0),
                    // color: Colors.red,
                    child: r.length == 0
                        ? Container(
                            height: 100.0,
                            width: MediaQuery.of(context).size.width,
                            child: Center(
                                child: Text(
                              'No reviews',
                              style: TextStyle(
                                color: darkBlue,
                                fontSize: 16,
                                fontFamily: 'FivoSansMediumOblique',
                              ),
                            )))
                        : ListView.builder(
                            shrinkWrap: true,
                            physics: ClampingScrollPhysics(),
                            padding: EdgeInsets.zero,
                            scrollDirection: Axis.vertical,
                            itemCount: r.length,
                            itemBuilder: (context, index) {
                              Review review = r[index];
                              return ListTile(
                                leading: Container(
                                    padding: EdgeInsets.all(4.0),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(5.0),
                                      ),
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black26,
                                          blurRadius: 5.0,
                                          spreadRadius: 0.25,
                                        )
                                      ],
                                    ),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(5.0),
                                      ),
                                      child: Image.network(
                                        review.image,
                                        fit: BoxFit.fill,
                                        height: 50.0,
                                        width: 50.0,
                                      ),
                                    )),
                                title: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      review.name,
                                      style: TextStyle(
                                        color: darkBlue,
                                        fontSize: 16,
                                        fontFamily: 'FivoSansMedium',
                                      ),
                                    ),
                                    SizedBox(height: 5.0),
                                    Text(
                                      review.date,
                                      style: TextStyle(
                                        color: extraDarkBlue,
                                        fontSize: 12,
                                        fontFamily: 'FivoSansRegular',
                                      ),
                                    ),
                                    SizedBox(height: 5.0),
                                    Text(
                                      review.comment,
                                      style: TextStyle(
                                        color: extraDarkBlue,
                                        fontSize: 14,
                                        fontFamily: 'FivoSansRegular',
                                      ),
                                    ),
                                    SizedBox(height: 5.0),
                                    Align(
                                      alignment: Alignment.topLeft,
                                      child: RatingBar(
                                        ignoreGestures: true,
                                        initialRating: 5,
                                        minRating: 0,
                                        direction: Axis.horizontal,
                                        allowHalfRating: true,
                                        itemCount: 5,
                                        itemSize: 20,
                                        ratingWidget: RatingWidget(
                                          full: Icon(
                                            Icons.star,
                                            color: Color(0xFFFECD03),
                                          ),
                                          half: Icon(
                                            Icons.star_half,
                                            color: Color(0xFFFECD03),
                                          ),
                                          empty: Icon(
                                            Icons.star_border,
                                            color: Color(0xFFFECD03),
                                          ),
                                        ),
                                        maxRating: 5,
                                        onRatingUpdate: (rating) {
                                          print(rating);
                                        },
                                      ),
                                    ),
                                    Divider(
                                      height: 10.0,
                                      color: extraDarkBlue.withOpacity(0.5),
                                    )
                                  ],
                                ),
                              );
                            },
                          ),
                  ),
                ),
              ),
              //third tab
              Container(
                margin: EdgeInsets.all(15),
                child: allImages.length == 0
                    ? Container(
                        child: Center(
                            child: Text(
                          'data not found...',
                          style: TextStyle(fontSize: 20.0, color: darkBlue),
                        )),
                      )
                    : GridView.builder(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          crossAxisSpacing: 10.0,
                          mainAxisSpacing: 10.0,
                        ),
                        itemCount: allImages.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Stack(
                            children: [
                              Container(
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        color: Colors.white, width: 2.0),
                                    color: Colors.white,
                                    boxShadow: [
                                      BoxShadow(
                                          color: Colors.black26,
                                          spreadRadius: 0.5,
                                          blurRadius: 2,
                                          offset: Offset(0.5, 0.5))
                                    ]),
                                child: Image.network(
                                  '${allImages[index]}',
                                  fit: BoxFit.fitWidth,
                                  alignment: Alignment.center,
                                ),
                                // child: Image.asset(
                                //   'assets/images/portfolio${index + 1}.png',
                                //   fit: BoxFit.fill,
                                // ),
                              ),
                              Positioned(
                                  top: 3,
                                  right: 2,
                                  child: Container(
                                    height: 30.0,
                                    width: 30.0,
                                    child: IconButton(
                                        // margin:EdgeInsets.zero,
                                        padding: EdgeInsets.zero,
                                        icon: Icon(
                                          Icons.remove_circle,
                                          color: Colors.red,
                                        ),
                                        onPressed: () {
                                          print(allImagesId[index]);
                                          deleteImage(allImagesId[index]);
                                        }),
                                  )),
                            ],
                          );
                        },
                      ),
              ),
            ],
            controller: _tabController,
          )),
    );
  }
}

class CustomAppBar extends StatelessWidget {
  const CustomAppBar(
      {Key key,
      @required TabController tabController,
      this.height,
      this.clipRRect})
      : _tabController = tabController,
        super(key: key);

  final TabController _tabController;
  final double height;
  final Widget clipRRect;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: AppBar(
        flexibleSpace: clipRRect,
        elevation: 0,
        backgroundColor: Theme.of(context).primaryColor,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(50.0))),
        leading: IconButton(
          iconSize: 25.0,
          icon: Icon(Icons.chevron_left),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: Icon(
              Icons.edit,
              size: 22,
            ),
            onPressed: () {
              Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (context) => EditProfile(),
                  ));
            },
          ),
        ],
        bottom: PreferredSize(
          preferredSize: Size(MediaQuery.of(context).size.width, 70.0),
          child: Container(
            decoration: BoxDecoration(
                // color: Colors.transparent,
                color: Color(0xFFE9F0F7),
                borderRadius:
                    BorderRadius.vertical(bottom: Radius.circular(0.0))),
            child: TabBar(
              unselectedLabelColor: Color(0xFF265E9E),
              labelColor: Theme.of(context).primaryColor,
              labelStyle: TextStyle(
                color: Theme.of(context).primaryColor,
                fontSize: 18,
                fontFamily: 'FivoSansMedium',
              ),
              unselectedLabelStyle: TextStyle(
                color: Color(0xFF91B4D8),
                fontSize: 18,
                fontFamily: 'FivoSansMedium',
              ),
              indicatorColor: Colors.white,
              tabs: [
                Tab(
                  child: Text(
                    'Profile',
                  ),
                ),
                Tab(
                  child: Text(
                    'Review',
                  ),
                ),
                Tab(
                  child: Text(
                    'Portfolio',
                  ),
                ),
              ],
              controller: _tabController,
            ),
          ),
        ),
      ),
    );
  }
}
