import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:peasmartcare/blocs/coordinator_list/coordinator_list_bloc.dart';
import 'package:peasmartcare/models/coordinator_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/coordinator/coordinator_add_edit.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/error_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/not_found_box.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class CoordinatorList extends StatefulWidget {
  @override
  _CoordinatorListState createState() => _CoordinatorListState();
}

class _CoordinatorListState extends State<CoordinatorList> {
  @override
  void initState() {
    context.read<CoordinatorListBloc>().add(CoordinatorListGetList());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<CoordinatorListBloc, CoordinatorListState>(
      listener: (context, state) {
        if (state is CoordinatorListLoaded) {
          if (state.deleteSuccess != null && state.deleteSuccess) {
            SweetAlert.show(
              context,
              subtitle: "ลบข้อมูลสำเร็จ",
              style: SweetAlertStyle.success,
            );

            context.read<CoordinatorListBloc>().add(CoordinatorListGetList());
          } else if (state.deleteSuccess != null && !state.deleteSuccess) {
            SweetAlert.show(
              context,
              subtitle: "ลบข้อมูลไม่สำเร็จ",
              style: SweetAlertStyle.error,
            );
          }
        } else if (state is CoordinatorListErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<CoordinatorListBloc, CoordinatorListState>(
        builder: (context, state) {
          if (state is CoordinatorListLoading) {
            return Loading();
          } else if (state is CoordinatorListLoaded) {
            List<CoordinatorModel> resultList = state.result;
            return Column(
              children: resultList.map((item) {
                return Slidable(
                  enabled: false,
                  actionPane: SlidableBehindActionPane(),
                  actionExtentRatio: 0.25,
                  child: _buildTable(item),
                  secondaryActions: <Widget>[
                    Container(
                      padding: EdgeInsets.only(top: 5, bottom: 5),
                      child: Card(
                        child: IconSlideAction(
                          color: Colors.blue,
                          icon: Icons.edit,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => CoordinatorAddEdit(
                                        coordinator: item,
                                      )),
                            );
                          },
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 5, bottom: 5),
                      child: Card(
                        child: IconSlideAction(
                          color: Colors.red,
                          icon: Icons.delete,
                          onTap: () {
                            SweetAlert.show(
                              context,
                              title: "ต้องการลบข้อมูลใช่หรือไม่",
                              style: SweetAlertStyle.confirm,
                              showCancelButton: true,
                              onPress: (bool isConfirm) {
                                if (isConfirm) {
                                  SweetAlert.show(context, subtitle: "กำลังลบ...", style: SweetAlertStyle.loading);

                                  context.read<CoordinatorListBloc>().add(
                                        CoordinatorListOnDelete(
                                          id: item.id,
                                        ),
                                      );
                                  return false;
                                }
                              },
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                );
              }).toList(),
            );
          } else if (state is CoordinatorListNotFound) {
            return NotFoundBox();
          } else if (state is CoordinatorListError) {
            return ErrorBox(
              message: state.message,
            );
          }

          return EmptyBox();
        },
      ),
    );
  }

  Widget _buildTable(CoordinatorModel item) {
    Size deviceSize = MediaQuery.of(context).size;
    return Container(
      padding: const EdgeInsets.all(5),
      child: Card(
        elevation: 3,
        child: Container(
            padding: EdgeInsets.all(15),
            width: deviceSize.width - 40,
            child: Row(
              children: [
                Container(
                  width: deviceSize.width - 100,
                  child: Table(
                    columnWidths: {0: FixedColumnWidth(120)},
                    children: [
                      TableRow(
                        children: [
                          TableCell(
                            child: Text("ชื่อผู้ติดต่อ"),
                          ),
                          TableCell(
                            child: Text("${item.fullname}"),
                          ),
                        ],
                      ),
                      TableRow(
                        children: [
                          TableCell(
                            child: Text("ตำแหน่ง"),
                          ),
                          TableCell(
                            child: Text(item.position),
                          ),
                        ],
                      ),
                      TableRow(
                        children: [
                          TableCell(
                            child: Text("หมายเลขโทรศัพท์"),
                          ),
                          TableCell(
                            child: Text(item.phone),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      InkWell(
                        child: Icon(
                          Icons.edit,
                          color: Colors.blue,
                        ),
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => CoordinatorAddEdit(
                                coordinator: item,
                              ),
                            ),
                          );
                        },
                      ),
                      SizedBox(height: 20),
                      InkWell(
                        child: Icon(
                          Icons.delete,
                          color: Colors.red,
                        ),
                        onTap: () {
                          SweetAlert.show(
                            context,
                            title: "ต้องการลบข้อมูลใช่หรือไม่",
                            style: SweetAlertStyle.confirm,
                            showCancelButton: true,
                            onPress: (bool isConfirm) {
                              if (isConfirm) {
                                SweetAlert.show(context, subtitle: "กำลังลบ...", style: SweetAlertStyle.loading);

                                context.read<CoordinatorListBloc>().add(
                                      CoordinatorListOnDelete(
                                        id: item.id,
                                      ),
                                    );
                                return false;
                              }
                            },
                          );
                        },
                      )
                    ],
                  ),
                )
              ],
            )),
      ),
    );
  }
}
