import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.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/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/modules/cleaner_module/widgets/multi_image_picker.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';

class CleanerChecklistWidget extends StatefulWidget {
  final List<ChecklistItem> checklistItems;
  final Function(List<ChecklistItem>)? onChecklistChanged;
  final List<String> capturedImages;
  final Function(List<String>)? onImagesChanged;
  final bool isClosed;

  const CleanerChecklistWidget({Key? key, required this.checklistItems, this.onChecklistChanged, required this.capturedImages, this.onImagesChanged, this.isClosed = false}) : super(key: key);

  @override
  State<CleanerChecklistWidget> createState() => _CleanerChecklistWidgetState();
}

class _CleanerChecklistWidgetState extends State<CleanerChecklistWidget> {
  @override
  Widget build(BuildContext context) {
    // Only show if checklist items are not empty
    if (widget.checklistItems.isEmpty) {
      return const SizedBox();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 12,
      children: [
        InfoHeader16Widget('Checklist'),
        ListView.separated(
                shrinkWrap: true,
                padding: EdgeInsets.zero,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (cxt, index) => _buildChecklistItem(context, widget.checklistItems[index]),
                separatorBuilder: (cxt, index) => const Divider().defaultStyle(context),
                itemCount: widget.checklistItems.length)
            .toShadowContainer(context),
        _buildImageCaptureWidget(context),
      ],
    );
  }

  Widget _buildChecklistItem(BuildContext context, ChecklistItem item) {
    return IgnorePointer(
      ignoring: widget.isClosed,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              AbsorbPointer(
                absorbing: true,
                child: Transform.scale(
                  scale: 1.2,
                  child: Checkbox(
                    value: item.isChecked,
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    side: BorderSide(color: AppColor.loadingColor(context), width: 1.0),
                    visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                    activeColor: AppColor.primary10,
                    onChanged: (bool? value) {},
                  ),
                ),
              ),
              10.width,
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: item.title,
                      style: AppTextStyles.bodyText2.copyWith(color: AppColor.lightTextColor(context)),
                    ),
                    if (item.isMandatory)
                      TextSpan(
                        text: ' *',
                        style: AppTextStyles.bodyText.copyWith(
                          color: Colors.red,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                  ],
                ),
              ).expanded,
            ],
          ).onPress(() {
            setState(() {
              item.isChecked = !item.isChecked;
              if (!item.isChecked) {
                item.commentController.clear();
              }
            });
            widget.onChecklistChanged?.call(widget.checklistItems);
          }),
          /*         ListTileTheme(
            horizontalTitleGap: 0,
            contentPadding: EdgeInsets.zero,
            minVerticalPadding: 0,
            child: Container(
              color: Colors.amberAccent,
              child: CheckboxListTile(
                value: item.isChecked,
                minVerticalPadding: 0,
                controlAffinity: ListTileControlAffinity.leading,
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                contentPadding: EdgeInsets.zero,
                checkboxScaleFactor: 1.2,
                side: BorderSide(color: Colors.black.withValues(alpha: .05)),
                visualDensity: const VisualDensity(horizontal: -0.0, vertical: -4.0),
                activeColor: AppColor.primary10,
                title: RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: item.title,
                        style: AppTextStyles.bodyText.copyWith(
                          color: context.isDark ? AppColor.neutral10 : AppColor.neutral120,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      if (item.isMandatory)
                        TextSpan(
                          text: ' *',
                          style: AppTextStyles.bodyText.copyWith(
                            color: Colors.red,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                    ],
                  ),
                ),
                onChanged: (bool? value) {
                  setState(() {
                    item.isChecked = value ?? false;
                    if (!item.isChecked) {
                      item.commentController.clear();
                    }
                  });
                  widget.onChecklistChanged?.call(widget.checklistItems);
                },
              ),
            ),
          ),*/
          if (item.isChecked) ...[
            12.height,
            AppTextFormField(
              controller: item.commentController,
              labelText: context.translation.comment,
              backgroundColor: AppColor.fieldBgColor(context),
              showShadow: false,
              labelStyle: AppTextStyles.textFieldLabelStyle,
              alignLabelWithHint: true,
              textInputType: TextInputType.multiline,
              onChange: (value) {
                item.comment = value;
                widget.onChecklistChanged?.call(widget.checklistItems);
              },
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildImageCaptureWidget(BuildContext context) {
    // Base64 image display and capture widget
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget('Captured Image'),
        8.height,
        _buildImageWidget(context),
      ],
    ).toShadowContainer(context);
  }

  static const int maxImages = 2;

  /// Build the image widget with loading indicator for network images
  Widget _buildImageWidget(BuildContext context) {
    if (widget.capturedImages.isEmpty) {
      // Show add image button when no image
      return GestureDetector(
        onTap: widget.isClosed
            ? null
            : () async {
                // Only allow camera - pick one image at a time
                final pickedFile = await ImagePicker().pickImage(
                  source: ImageSource.camera,
                  imageQuality: 70,
                  maxWidth: 800,
                  maxHeight: 800,
                );

                if (pickedFile != null) {
                  final bytes = await pickedFile.readAsBytes();
                  final base64Image = base64Encode(bytes);
                  final fileName = pickedFile.path.split("/").last;
                  final formattedImage = "$fileName|$base64Image";

                  // Add to existing images (max 2)
                  final updatedImages = List<String>.from(widget.capturedImages);
                  updatedImages.add(formattedImage);

                  widget.onImagesChanged?.call(updatedImages);
                }
              },
        child: Container(
          height: 120,
          width: 120,
          decoration: BoxDecoration(
            color: AppColor.fieldBgColor(context),
            borderRadius: BorderRadius.circular(8),
            border: Border.all(
              color: context.isDark ? AppColor.neutral20 : AppColor.neutral30,
              width: 2,
              style: BorderStyle.solid,
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.add_photo_alternate,
                size: 32,
                color: context.isDark ? AppColor.white10 : AppColor.black10,
              ),
              4.height,
              InfoTextLabelWidget(label: 'Add Image'),

              // Text(
              //   'Add Image',
              //   style: AppTextStyles.tinyFont.copyWith(
              //     color: context.isDark ? AppColor.white10 : AppColor.black10,
              //   ),
              // ),
            ],
          ),
        ),
      );
    }

    // Check if images are URLs from API (like ServiceRequestDetailView does)
    final bool hasApiImages = widget.capturedImages.any((img) => img.startsWith('http://') || img.startsWith('https://'));

    // If images are from API (URLs), use FilesList widget like ServiceRequestDetailView
    if (hasApiImages && widget.isClosed) {
      return FilesList(
        images: widget.capturedImages,
        showAsListView: false,
      );
    }

    // Otherwise, use MultiImagePicker for base64 images or when editing
    return MultiImagePicker(
      imageUrls: widget.capturedImages,
      enabled: !widget.isClosed,
      maxImages: 2,
      // Enforce max 2 images
      onImageTap: (index, imageUrl) {
        context.fullScreenImageViewer(_buildImageForViewing(imageUrl));
      },
      onDelete: (index) {
        // Handle image delete
        if (index >= 0) {
          setState(() {
            widget.capturedImages.removeAt(index);
          });
          widget.onImagesChanged?.call(widget.capturedImages);
        }
      },
      onAdd: (imageUrl) {
        // Handle new image addition
        setState(() {
          widget.capturedImages.add(imageUrl);
        });
        widget.onImagesChanged?.call(widget.capturedImages);
      },
    );
  }

  /// Build image widget for viewing based on source type
  Widget _buildImageForViewing(String imageUrl) {
    try {
      // Check if it's a URL from API
      if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        return Image.network(
          imageUrl,
          fit: BoxFit.contain,
          errorBuilder: (context, error, stackTrace) {
            return const Icon(Icons.broken_image, size: 48, color: Colors.white);
          },
        );
      }

      // Otherwise, it's base64 encoded
      final parts = imageUrl.split('|');
      final base64Data = parts.length > 1 ? parts[1] : imageUrl;
      return Image.memory(
        base64Decode(base64Data),
        fit: BoxFit.contain,
      );
    } catch (e) {
      return const Icon(Icons.broken_image, size: 48, color: Colors.white);
    }
  }

  @override
  void dispose() {
    // Note: Don't dispose controllers here as they're managed by ChecklistItem
    super.dispose();
  }
}

/// Model class for checklist items
class ChecklistItem {
  final int id;
  final String title;
  bool isChecked;
  String comment;
  final bool isMandatory;
  final TextEditingController commentController;

  ChecklistItem({
    required this.id,
    required this.title,
    required this.isChecked,
    required this.comment,
    this.isMandatory = false,
  }) : commentController = TextEditingController(text: comment);

  // Convert to JSON for API submission
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'isChecked': isChecked,
      'comment': commentController.text,
      'isMandatory': isMandatory,
    };
  }

  void dispose() {
    commentController.dispose();
  }
}
