import 'dart:developer';

import 'package:flutter/material.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/technical_inspection_asset_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/asset_delivery_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';

class InspectionCheckListView extends StatefulWidget {
  final List<InspectionChecklistItem>? initialValues;

  const InspectionCheckListView({super.key, this.initialValues});

  @override
  State<InspectionCheckListView> createState() => _InspectionCheckListViewState();
}

class _InspectionCheckListViewState extends State<InspectionCheckListView> {
  late List<InspectionChecklistItem> checklist;

  @override
  void initState() {
    super.initState();
    checklist = AssetDeliveryUtils.inspectionChecklist.map((e) => InspectionChecklistItem(title: e.title)).toList();

    if (widget.initialValues != null && widget.initialValues!.isNotEmpty) {
      for (final item in checklist) {
        final matched = widget.initialValues!.firstWhere(
          (e) => e.title == item.title,
          orElse: () => InspectionChecklistItem(),
        );
        item.status = matched.status; // null-safe
      }
    }
  }

  void updateStatus(int index, String value) {
    setState(() {
      checklist[index].status = value;
    });
  }

  List<InspectionChecklistItem> get selectedValues => checklist.where((e) => e.status != null).toList();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(
        title: 'Asset Check List'.addTranslation,
      ),
      body: Column(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: List.generate(
              checklist.length,
              (index) {
                final model = checklist[index];
                return inspectionStatusRadioWidget(
                  model: model,
                  index: index,
                  context: context,
                );
              },
            ),
          ).toShadowContainer(
            context,
            borderRadius: 20,
            margin: const EdgeInsets.only(top: 12, left: 12, right: 12),
          ),
          const Spacer(),
          FooterActionButton.footerContainer(
            context: context,
            child: AppFilledButton(
              buttonColor: AppColor.primary10,
              label: 'Save'.addTranslation,
              maxWidth: true,
              onPressed: () {
                Navigator.pop(context, selectedValues);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget inspectionStatusRadioWidget({required int index, required InspectionChecklistItem model, required BuildContext context}) {
    bool status = (model.status == null) ? false : (model.status != null ? (model.status == 'true' ? true : false) : false);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          // ' (${index+1})  ${model.title}',
          model.title ?? '',
          softWrap: true,
          // maxLines: 1,
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? Colors.white : AppColor.white936, height: 1.5),
        ),
        7.height,
        // Column(
        //   crossAxisAlignment: CrossAxisAlignment.start,
        //   children: [
        //
        //     (status ? 'Pass' : 'Fail').bodyText2(context).custom(color: AppColor.neutral120, fontWeight: FontWeight.w500),
        //   ],
        // ).expanded,
        GestureDetector(
          onTap: () {
            setState(() {
              status = !status;
              model.status = status.toString();
            });
            updateStatus(index, status.toString());
          },
          child: Container(
            width: 99.toScreenWidth,
            height: 40.toScreenHeight,
            padding: EdgeInsetsDirectional.all(4.toScreenHeight),
            decoration: BoxDecoration(
              color: AppColor.fieldBgColor(context),
              borderRadius: BorderRadius.circular(5),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                buildToggleOption(
                  label: "PASS",
                  isActive: status,
                  activeColor: AppColor.green20,
                  inactiveColor: Colors.transparent,
                  textColor: status
                      ? AppColor.green50
                      : context.isDark
                          ? Colors.white
                          : AppColor.black20,
                ),
                buildToggleOption(
                  label: "FAIL",
                  isActive: !status,
                  activeColor: AppColor.red20,
                  inactiveColor: Colors.transparent,
                  textColor: status
                      ? context.isDark
                          ? Colors.white
                          : AppColor.black20
                      : AppColor.red30,
                ),
              ],
            ),
          ),
        ),
      ],
    ).paddingOnly(top: 14);
  }

  Widget buildToggleOption({
    required String label,
    required bool isActive,
    required Color activeColor,
    required Color inactiveColor,
    required Color textColor,
  }) {
    return Container(
      width: 44.toScreenWidth,
      height: 30.toScreenHeight,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: isActive ? activeColor : inactiveColor,
        borderRadius: BorderRadius.circular(3),
      ),
      child: label.bodyText2(context).custom(color: textColor),
    );
  }

//older widget ...
// return Column(
//   crossAxisAlignment: CrossAxisAlignment.start,
//   children: [
//     Text(
//       item.title ?? '',
//       style: AppTextStyles.heading6.copyWith(
//         color: context.isDark ? AppColor.neutral30 : AppColor.black10,
//       ),
//     ),
//     Row(
//       children: [
//         Expanded(
//           child: RadioListTile<String>(
//             title: const Text('Pass'),
//             value: 'PASS',
//             groupValue: item.status,
//             onChanged: (v) => updateStatus(index, v!),
//           ),
//         ),
//         Expanded(
//           child: RadioListTile<String>(
//             title: const Text('Fail'),
//             value: 'FAIL',
//             groupValue: item.status,
//             onChanged: (v) => updateStatus(index, v!),
//           ),
//         ),
//       ],
//     ),
//   ],
// );
}
