import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/itg/itg_summary_data.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/field_goups_model.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/fields_model.dart';
import 'package:mohem_flutter_app/widgets/item_detail_view_widget.dart';

class RequestDetailFragment extends StatelessWidget {
  List<Fields> fields;
  List<FieldGoups>? fieldGoups;
  String taskID;
  ItgTimeCardSummaryData? summaryData;

  RequestDetailFragment({Key? key, this.fields = const <Fields>[], this.fieldGoups = const <FieldGoups>[], this.taskID = "", this.summaryData}) : super(key: key);
  double itemHeight = 0;
  double itemWidth = 0;

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    itemHeight = (size.height - kToolbarHeight - 24) / 9;
    itemWidth = size.width / 2;
    List<Widget> uiList = [detailView(fields)];
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(21),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    width: double.infinity,
                    // height: double.infinity,
                    child: fields.isEmpty ? LocaleKeys.noDataAvailable.tr().toText16().center : ListView(shrinkWrap: true, children: uiList),
                  ),
                  12.height,
                  if (taskID.toLowerCase().contains("vida"))
                    Column(
                      children: [
                        fieldGoups![2].title!.toText14(),
                        6.height,
                        detailView(fieldGoups![2].fields!),
                        12.height,
                        fieldGoups![3].title!.toText14(),
                        6.height,
                        detailView(fieldGoups![3].fields!),
                        12.height,
                        fieldGoups![4].title!.toText14(),
                        6.height,
                        detailView(fieldGoups![4].fields!),
                      ],
                    ),
                  if (summaryData != null && summaryData!.summeries != null && summaryData!.summeries!.isNotEmpty) buildStatsDashboard(summaryData: summaryData),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget leaveTypeHorizontalList() {
    return SizedBox(
      // height: 120,
      child: ListView(
        shrinkWrap: true,
        scrollDirection: Axis.vertical,
        physics: const NeverScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
        children: [
          _buildLeaveTypeChip(
            title: 'Half-Day Leave',
            value: summaryData?.summeries?.first.unpaiDLeaves.toString() ?? "0",
            textColor: const Color(0xFF3B3D4A),
            topIcon: "assets/icons/itg/calendar-remove.svg",
          ),
          const SizedBox(height: 12),
          _buildLeaveTypeChip(
            title: 'Unauthorised Leave',
            value: summaryData?.summeries?.first.unauthorizeDLeaves.toString() ?? "0",
            textColor: const Color(0xFF3B3D4A),
            topIcon: "assets/icons/itg/knight-shield.svg",
          ),
          const SizedBox(height: 12),
          _buildLeaveTypeChip(title: 'Sick Leave', value: summaryData?.summeries?.first.sicKLeaves.toString() ?? "0", textColor: const Color(0xFF3B3D4A), topIcon: "assets/icons/itg/stethoscope.svg"),
          const SizedBox(height: 12),
          _buildLeaveTypeChip(title: 'Paid Leave', value: summaryData?.summeries?.first.paiDLeaves.toString() ?? "0", textColor: const Color(0xFF3B3D4A), topIcon: "assets/icons/itg/calendar.svg"),
          const SizedBox(height: 12),
          _buildLeaveTypeChip(
            title: 'Unpaid Leave',
            value: summaryData?.summeries?.first.unpaiDLeaves.toString() ?? "0",
            textColor: const Color(0xFF3B3D4A),
            topIcon: "assets/icons/itg/money-not-found.svg",
          ),
          const SizedBox(height: 12),
          _buildLeaveTypeChip(
            title: 'Public Holidays',
            value: summaryData?.summeries?.first.publiCHolidays.toString() ?? "0",
            textColor: const Color(0xFF3B3D4A),
            topIcon: "assets/icons/itg/finger-print-remove.svg",
          ),
        ],
      ),
    );
  }

  Widget _buildLeaveTypeChip({required String title, required String value, required Color textColor, Color? valueColor, String? topIcon, String? bottomIcon, Widget? child}) {
    return Container(
      padding: const EdgeInsets.all(10),
      height: 110,
      decoration: BoxDecoration(
        color: const Color(0xFFEAF1F4),
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 4),
          )
        ],
      ),
      child: child ??
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              if (topIcon != null) ...[
                Row(
                  children: [
                    Expanded(child: title.toText13(color: textColor)),
                    SvgPicture.asset(topIcon, width: 24),
                  ],
                ),
                const SizedBox(height: 21),
              ] else ...[
                title.toText13(color: textColor),
                const SizedBox(height: 8),
              ],
              Row(children: [value.toText24(color: valueColor ?? textColor, isBold: true), const SizedBox(width: 10), if (bottomIcon != null) SvgPicture.asset(bottomIcon, width: 24)]),
            ],
          ),
    );
  }

  Widget buildStatsDashboard({required ItgTimeCardSummaryData? summaryData}) {
    return Column(
      children: [
        // First row with 2 boxes
        Row(
          children: [
            buildStatBox(
              title: 'Missing Swipes',
              value: summaryData?.summeries?.first.missinGSwipesDays.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/finger-print-remove.svg",
            ),
            const SizedBox(width: 15),
            buildStatBox(title: 'Total Shortage', value: summaryData?.summeries?.first.shortagEHrs ?? "0", textColor: const Color(0xFF3B3D4A), topIcon: "assets/icons/itg/time-quarter-pass.svg"),
          ],
        ),
        const SizedBox(height: 15),
        // Second row with 2 boxes
        Row(
          children: [
            buildLateInEarlyOutBox(
              lateInValue: summaryData?.summeries?.first.latEInHrs ?? "0",
              earlyOutValue: summaryData?.summeries?.first.earlYOutHrs ?? "0",
              topIcon: "assets/icons/itg/coming-soon.svg",
            ),
            const SizedBox(width: 15),
            buildStatBox(
              title: 'Uncovered Shortage',
              value: summaryData?.summeries?.first.uncovereDShortageHrs.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              valueColor: const Color(0xFFEB5757),
              topIcon: "assets/icons/itg/time-quarter.svg",
              bottomIcon: "assets/icons/itg/alert.svg",
            ),
          ],
        ),
        const SizedBox(height: 15),

        Row(
          children: [
            buildStatBox(
              title: 'Half-Day Leave',
              value: summaryData?.summeries?.first.unpaiDLeaves.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/calendar-remove.svg",
            ),
            const SizedBox(width: 15),
            buildStatBox(
              title: 'Unauthorised Leave',
              value: summaryData?.summeries?.first.unauthorizeDLeaves.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/knight-shield.svg",
            ),
          ],
        ),
        const SizedBox(height: 15),
        Row(
          children: [
            buildStatBox(
              title: 'Sick Leave',
              value: summaryData?.summeries?.first.sicKLeaves.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/stethoscope.svg",
            ),
            const SizedBox(width: 15),
            buildStatBox(
              title: 'Paid Leave',
              value: summaryData?.summeries?.first.paiDLeaves.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/calendar.svg",
            ),
          ],
        ),

        const SizedBox(height: 15),
        Row(
          children: [
            buildStatBox(
              title: 'Unpaid Leave',
              value: summaryData?.summeries?.first.unpaiDLeaves.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/money-not-found.svg",
            ),
            const SizedBox(width: 15),
            buildStatBox(
              title: 'Public Holidays',
              value: summaryData?.summeries?.first.publiCHolidays.toString() ?? "0",
              textColor: const Color(0xFF3B3D4A),
              topIcon: "assets/icons/itg/finger-print-remove.svg",
            ),
          ],
        ),
        const SizedBox(height: 15),
      ],
    );
  }

  Widget buildStatBox({required String title, required String value, required Color textColor, Color? valueColor, String? topIcon, String? bottomIcon, Widget? child}) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(10),
        height: 110,
        decoration: BoxDecoration(
          color: const Color(0xFFEAF1F4),
          borderRadius: BorderRadius.circular(8),
          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 8, offset: const Offset(0, 4))],
        ),
        child: child ??
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (topIcon != null) ...[
                  Row(children: [Expanded(child: title.toText13(color: textColor)), SvgPicture.asset(topIcon, width: 24)]),
                  Expanded(child: SizedBox(),),
                ] else ...[
                  title.toText13(color: textColor),
                  const SizedBox(height: 8),
                ],
                Row(children: [value.toText24(color: valueColor ?? textColor, isBold: true), const SizedBox(width: 10), if (bottomIcon != null) SvgPicture.asset(bottomIcon, width: 20)]),
              ],
            ),
      ),
    );
  }

  Widget buildLateInEarlyOutBox({required String lateInValue, required String earlyOutValue, required String topIcon}) {
    return buildStatBox(
      title: 'Late In / Early Out',
      textColor: const Color(0xFFEB5757),
      topIcon: topIcon,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(children: ["Late In / Early Out".toText13(color: const Color(0xFF3B3D4A)), const Expanded(child: SizedBox()), SvgPicture.asset(topIcon, width: 24)]),
          Expanded(child: SizedBox(),),
          RichText(
            text: TextSpan(
              style: const TextStyle(fontSize: 13),
              children: <TextSpan>[
                const TextSpan(text: 'Late In : ', style: TextStyle(color: Color(0xFF767676), fontSize: 14)),
                TextSpan(text: lateInValue, style: const TextStyle(color: Color(0xFF3B3D4A), fontSize: 16, fontWeight: FontWeight.w700)),
              ],
            ),
          ),
          RichText(
            text: TextSpan(
              style: const TextStyle(fontSize: 13),
              children: <TextSpan>[
                const TextSpan(text: 'Early Out : ', style: TextStyle(color: Color(0xFF767676), fontSize: 14)),
                TextSpan(text: earlyOutValue, style: const TextStyle(color: Color(0xFF3B3D4A), fontSize: 16, fontWeight: FontWeight.w700)),
              ],
            ),
          ),
        ],
      ),
      value: '',
    );
  }

  Widget detailView(List<Fields> fieldsF) {
    List<Fields> fields = List.from(fieldsF);

    bool isOdd = false;
    if (fields.length % 2 != 0) {
      isOdd = true;
      fields.add(new Fields());
    }

    int descriptionFormatIndex = fields.indexWhere((element) => element.title == "Description Format" || element.title == "Description Format"); // todo add arabic in future
    Widget? descriptionFormatView;
    if (descriptionFormatIndex >= 0) {
      Fields descriptionFormat = fields[descriptionFormatIndex];
      fields.removeAt(descriptionFormatIndex);

      descriptionFormatView = ItemDetailViewGridItem(
        2,
        descriptionFormat.title,
        descriptionFormat.value == null ? (descriptionFormat.multipleValue?.join(", ") ?? "") : descriptionFormat.value ?? "",
        type: descriptionFormat.type,
        maxLine: 0,
      );
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GridView.builder(
          itemCount: fields.length,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            if (fields[index].value == null) {
              return ItemDetailViewGridItem(
                index,
                fields[index].title,
                fields[index].multipleValue?.join(", ") ?? "",
                isNeedToShowEmptyDivider: (fields.length == index + 1)
                    ? isOdd
                        ? true
                        : false
                    : false,
                type: fields[index].type,
              );
            }
            return ItemDetailViewGridItem(
              index,
              fields[index].title,
              fields[index].value ?? "",
              isNeedToShowEmptyDivider: (fields.length == index + 1)
                  ? isOdd
                      ? true
                      : false
                  : false,
              type: fields[index].type,
            );
          },
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: (itemWidth / itemHeight)),
        ),
        if (descriptionFormatView != null) descriptionFormatView,
      ],
    ).objectContainerView();
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (cxt, index) {
        if (fields[index].value == null) {
          return ItemDetailView(fields[index].title!, fields[index].multipleValue?.join(", ") ?? "");
        }
        return ItemDetailView(fields[index].title!, fields[index].value ?? "");
      },
      separatorBuilder: (cxt, index) => 4.height,
      itemCount: fields.length,
    ).objectContainerView();
  }
}
