import 'dart:convert';

import 'package:app_petty_cash/model/auth_model.dart';
import 'package:app_petty_cash/model/company_model.dart';
import 'package:app_petty_cash/screen/change_company/list_company_provider.dart';
import 'package:app_petty_cash/widget/sankbar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../app/route.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/custom_drawer.dart';

class ChangeCompanyScreen extends HookConsumerWidget {
  const ChangeCompanyScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final listCompany = useState<List<CompanyModel>>([
      CompanyModel(companyid: "1", companyname: "SAS"),
      CompanyModel(companyid: "2", companyname: "SIM")
    ]);
    final isLoading = useState(false);
    final selectedCompanyID = useState("0");
    final selectedCompanyName = useState("");
    final auth = ref.watch(currentUserProvider);
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final userID = ref.read(currentUserProvider)?.model.M_UserID ?? "0";
        if (userID == "0") {
          //not login
          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => true);

          //  Navigator.popAndPushNamed(context, loginRoute);
          return;
        }
        ref.read(ListCompanyProvider.notifier).getListCompany(userID: userID);
      });
      return () {};
    }, []);

    ref.listen(
      ListCompanyProvider,
      (previous, next) {
        if (next is ListCompanyStateLoading) {
          isLoading.value = true;
        } else if (next is ListCompanyStateError) {
          // print(next.message);
          isLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is ListCompanyStateDone) {
          print(jsonEncode(next.model));
          // print(next.model.length);
          listCompany.value = next.model;
          selectedCompanyID.value = auth?.model.M_CompanyID ?? "0";
          isLoading.value = false;
        }
      },
    );
    return Padding(
      padding: EdgeInsets.only(
        top: Constant.getActualYPhone(context: context, y: 30),
      ),
      child: Scaffold(
        appBar: AppBar(
          //  centerTitle: true,
          title: Text(
            'Change Company',
            style: TextStyle(color: Constant.textWhite),
          ),
          backgroundColor: Constant.pcBtnBackgroundColor,
          iconTheme: IconThemeData(
            color: Constant.textWhite,
          ),
        ),
        drawer: CustomDrawer(),
        body: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(20),
            child: isLoading.value
                ? Container(
                    height: MediaQuery.of(context).size.height,
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  )
                : Column(
                    children: listCompany.value
                        .map((e) => Container(
                              margin: EdgeInsets.only(bottom: 20),
                              child: InkWell(
                                onTap: () async {
                                  selectedCompanyID.value = e.companyid ?? "0";
                                  selectedCompanyName.value =
                                      e.companyname ?? "0";
                                  final shared =
                                      await SharedPreferences.getInstance();
                                  final oldData = jsonDecode(
                                      shared.getString(Constant.bearerName) ??
                                          "");
                                  print(oldData['token']);

                                  final newModel = AuthDoctorModel.fromJson(
                                      oldData['model']);
                                  newModel.M_CompanyID = e.companyid ?? "0";
                                  newModel.M_CompanyName = e.companyname ?? "";
                                  final token = jsonEncode({
                                    "date": oldData['date'],
                                    "model": newModel,
                                    "token": oldData['token']
                                  });
                                  final newAuthData = AuthModel(
                                      token: oldData['token'], model: newModel);
                                  await shared.setString(
                                      Constant.bearerName, token);
                                  ref.read(currentUserProvider.notifier).state =
                                      newAuthData;
                                  Navigator.pushNamed(context, homeRoute);
                                },
                                child: Card(
                                  shadowColor:
                                      selectedCompanyID.value == e.companyid
                                          ? Constant.bgIconHistory
                                          : Colors.white,
                                  surfaceTintColor:
                                      selectedCompanyID.value == e.companyid
                                          ? Constant.bgIconHistory
                                          : Colors.white,
                                  // elevation: selectedCompanyID.value == e.companyid
                                  //     ? 0
                                  //     : 1,
                                  elevation: 10,
                                  color: selectedCompanyID.value == e.companyid
                                      ? Constant.bgIconHistory
                                      : Colors.white,
                                  child: Container(
                                      padding: EdgeInsets.all(20),
                                      width: MediaQuery.of(context).size.width,
                                      child: Row(
                                        children: [
                                          Expanded(
                                              flex: 1,
                                              child: Icon(
                                                Icons.corporate_fare,
                                                color:
                                                    selectedCompanyID.value ==
                                                            e.companyid
                                                        ? Constant.textRed
                                                        : Colors.black,
                                                size: 30,
                                              )),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          Expanded(
                                            flex: 8,
                                            child: Text(e.companyname ?? "",
                                                softWrap: true,
                                                maxLines: 3,
                                                // overflow: ,
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        color: selectedCompanyID
                                                                    .value ==
                                                                e.companyid
                                                            ? Constant.textRed
                                                            : Colors.black,
                                                        fontSize: 25)),
                                          ),
                                        ],
                                      )),
                                ),
                              ),
                            ))
                        .toList()
                    // [
                    //   Card(
                    //     shadowColor: Colors.white,
                    //     // surfaceTintColor: Colors.white,
                    //     elevation: 0,
                    //     color: Constant.bgIconHistory,
                    //     child: Container(
                    //         padding: EdgeInsets.all(10),
                    //         width: MediaQuery.of(context).size.width,
                    //         child: Row(
                    //           children: [
                    //             Icon(Icons.corporate_fare),
                    //             SizedBox(
                    //               width: 10,
                    //             ),
                    //             Text("Company",
                    //                 style: Constant.body1(context: context)
                    //                     .copyWith(color: Constant.textRed)),
                    //           ],
                    //         )),
                    //   )
                    // ],
                    ),
          ),
        ),
      ),
    );
  }
}
