import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/asset_delivery_module/models/history_model.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

class AssetDeliveryHistoryLogView extends StatefulWidget {
  final int? tableItemId;

  const AssetDeliveryHistoryLogView({Key? key, this.tableItemId}) : super(key: key);

  @override
  State<AssetDeliveryHistoryLogView> createState() => _AssetDeliveryHistoryLogViewState();
}

class _AssetDeliveryHistoryLogViewState extends State<AssetDeliveryHistoryLogView> {
  List<AssetDeliveryHistoryModel> history = [];
  bool loading = false;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  void getInitialData() async {
    setState(() {
      loading = true;
    });
    history = await Provider.of<AssetDeliveryProvider>(context, listen: false).getHistory(tableItemId: widget.tableItemId);
    if (mounted) {
      setState(() {
        loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      // appBar: DefaultAppBar(
      //   title: 'History Log'.addTranslation,
      //   onBackPress: () {
      //     Navigator.pop(context);
      //   },
      // ),
      body: loading
          ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
          : Stack(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 122.toScreenWidth),
                  child: VerticalDivider(
                    color: AppColor.borderColor(context),
                    thickness: 2,
                    width: 20,
                    indent: 10,
                    endIndent: 10,
                  ),
                ),
                SafeArea(
                  child: Builder(builder: (cxt) {
                    List<Widget> items = [];
                    String lastStatus = "";
                    DateTime? nextDate;
                    for (int i = 0; i < history.length; i++) {
                      var object = history[i];
                      String currentStatus = object.status!.name!;
                      if (lastStatus.isEmpty) {
                        lastStatus = currentStatus;
                      }
                      if (lastStatus == currentStatus) {
                        if (i + 1 < history.length) {
                          nextDate = history[i + 1].createdDate;
                          String timeDifference = CMRequestUtils.calculateTimeDifference(object.createdDate!, nextDate!);
                          object.timeDifference = timeDifference;
                        } else {
                          object.timeDifference = ''; // Empty string for the last action
                        }
                        items.add(historyLogCard(cxt, object));
                      } else {
                        items.add(statusCard(cxt, lastStatus));
                        lastStatus = currentStatus;
                        if (i + 1 < history.length) {
                          nextDate = history[i + 1].createdDate;
                          String timeDifference = CMRequestUtils.calculateTimeDifference(object.createdDate!, nextDate!);
                          object.timeDifference = timeDifference;
                        } else {
                          object.timeDifference = ''; // Empty string for the last action
                        }
                        items.add(historyLogCard(cxt, object));
                      }
                    }
                    items.add(statusCard(cxt, lastStatus));
                    return SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(children: items),
                    );
                  }),
                ),
              ],
            ),
    );
  }

  Widget historyLogCard(BuildContext context, AssetDeliveryHistoryModel object) {
    String title = object.status!.name!;

    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Align(
          alignment: Alignment.centerLeft,
          child: Text(
            object.createdDate.toString().toServiceRequestCardFormat,
            textAlign: TextAlign.end,
            style: AppTextStyles.tinyFont.copyWith(color: AppColor.labelTextStyleColor(context)),
          ),
        ).expanded,
        Expanded(
          flex: 2,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              InfoHeaderWidget(title),
              // object.timeDifference.isNotEmpty ? object.timeDifference?.tinyFont(context).custom(color: context.isDark ? AppColor.neutral10 : AppColor.neutral120) : const SizedBox(),
            ],
          ),
        ),
      ],
    ).toShadowContainer(context, padding: 16).paddingOnly(bottom: 16);
  }

  Widget statusCard(BuildContext context, String status) {
    return SizedBox(
      width: 153.toScreenWidth,
      child: StatusLabel(
        radius: 4,
        label: statusText(status.toLowerCase()),
        labelInCenter: true,
        textColor: AppColor.neutral50,
        backgroundColor: AppColor.orange30,
      ),
    ).paddingOnly(bottom: 16, start: 40);
  }

//Todo Need to check status text we have
  String statusText(String status) {
    if (status == "new" || status == "open") {
      return "New".addTranslation;
    } else if (status == "in progress") {
      return "Status update to In Progress".addTranslation;
    } else if (status == "closed") {
      return "Status update to Closed".addTranslation;
    } else if (status == "completed") {
      return "Status update to Completed".addTranslation;
    } else if (status == "fixed") {
      return "Status update to Fixed".addTranslation;
    } else if (status == "reject") {
      return "Status update to Rejected".addTranslation;
    } else
      return status;
  }
}
