import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:test_sa/controllers/api_routes/urls.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';

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

  CleanerChecklistWidget({Key? key, required this.checklistItems, this.onChecklistChanged, this.capturedImageBase64, this.onImageCaptured, 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,
      children: [
        Text(
          'Checklist'.addTranslation,
          style: AppTextStyles.heading4.copyWith(
            color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
          ),
        ),
        16.height,
        ...widget.checklistItems.map((item) => _buildChecklistItem(context, item)).toList(),
        // 16.height,
        _buildImageCaptureWidget(context),
      ],
    );
  }

  Widget _buildChecklistItem(BuildContext context, ChecklistItem item) {
    return IgnorePointer(
      ignoring: widget.isClosed,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // Checkbox with title
          Row(
            children: [
              Checkbox(
                // visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                value: item.isChecked,
                activeColor: AppColor.primary10,
                onChanged: (bool? value) {
                  setState(() {
                    item.isChecked = value ?? false;
                    if (!item.isChecked) {
                      item.commentController.clear();
                    }
                  });
                  // Notify parent of changes
                  widget.onChecklistChanged?.call(widget.checklistItems);
                },
              ),
              8.width,
              Expanded(
                child: 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,
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          ),

          // Comment box - only visible when checked
          if (item.isChecked) ...[
            16.height,
            AppTextFormField(
              controller: item.commentController,
              labelText: context.translation.comment,
              backgroundColor: AppColor.fieldBgColor(context),
              showShadow: false,
              labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(
                color: context.isDark ? AppColor.white10 : AppColor.black10,
              ),
              alignLabelWithHint: true,
              textInputType: TextInputType.multiline,
              onChange: (value) {
                item.comment = value;
                // Notify parent of changes
                widget.onChecklistChanged?.call(widget.checklistItems);
              },
            ),
          ],
        ],
      ).toShadowContainer(context).paddingOnly(bottom: 16),
    );
  }

  Widget _buildImageCaptureWidget(BuildContext context) {
    // Base64 image display and capture widget
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Captured Image'.addTranslation,
          style: AppTextStyles.heading6.copyWith(
            color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
          ),
        ),
        8.height,
        _buildImageWidget(context),
      ],
    ).toShadowContainer(context);
  }

  /// Build the image widget with loading indicator for network images
  Widget _buildImageWidget(BuildContext context) {
    if (widget.capturedImageBase64 == null || widget.capturedImageBase64!.isEmpty) {
      // Show camera icon when no image
      return Container(
        height: 200,
        width: double.infinity,
        decoration: BoxDecoration(
          color: AppColor.fieldBgColor(context),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(
          Icons.camera_alt,
          size: 48,
          color: context.isDark ? AppColor.white10 : AppColor.black10,
        ),
      ).onPress(() async {
        final pickedFile = await ImagePicker().pickImage(source: ImageSource.camera, imageQuality: 70, maxWidth: 800, maxHeight: 800);
        if (pickedFile != null) {
          // Convert image to Base64 with filename prefix (same format as CM request)
          final bytes = await pickedFile.readAsBytes();
          final base64Image = base64Encode(bytes);
          final fileName = pickedFile.path.split("/").last;
          final formattedImage = "$fileName|$base64Image";

          // Update parent with captured image
          widget.onImageCaptured?.call(formattedImage);
        }
      });
    }

    Widget imageWidget;

    final imageString = widget.capturedImageBase64!;

    // First check if it's base64 encoded (contains | separator)
    if (imageString.contains('|')) {
      // Format: "filename|base64data"
      try {
        final base64Data = imageString.split('|').last;
        imageWidget = Image.memory(base64Decode(base64Data), fit: BoxFit.cover);
        return Stack(
          alignment: AlignmentDirectional.topEnd,
          children: [
            Container(
                    height: 200,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: AppColor.fieldBgColor(context),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: imageWidget)
                .onPress(() {
              context.fullScreenImageViewer(imageWidget);
            }),
            _delete(),
          ],
        );
      } catch (e) {
        debugPrint('Error decoding base64 image: $e');
        return _buildCameraIcon(context);
      }
    }

    // Check if it's a local file path
    if (_isLocalUrl(imageString)) {
      try {
        imageWidget = Image.file(File(imageString), fit: BoxFit.cover);
        return Stack(
          alignment: AlignmentDirectional.topEnd,
          children: [
            Container(
                    height: 200,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: AppColor.fieldBgColor(context),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: imageWidget)
                .onPress(() {
              context.fullScreenImageViewer(imageWidget);
            }),
            _delete(),
          ],
        );
      } catch (e) {
        debugPrint('Error loading local file: $e');
        return _buildCameraIcon(context);
      }
    }

    // If not local and not base64, it's a server filename - use NetworkImage with loading indicator
    final imageUrl = URLs.getFileUrl(imageString);
    if (imageUrl != null) {
      imageWidget = Image.network(
        imageUrl,
        fit: BoxFit.cover,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) {
            return child;
          }
          return Center(
            child: CircularProgressIndicator(
              color: AppColor.primary10,
              value: loadingProgress.expectedTotalBytes != null ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes! : null,
            ),
          );
        },
        errorBuilder: (context, error, stackTrace) {
          debugPrint('Error loading network image: $error');
          return _buildCameraIcon(context);
        },
      );
      return Stack(
        alignment: AlignmentDirectional.topEnd,
        children: [
          Container(
                  height: 200,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: AppColor.fieldBgColor(context),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: imageWidget)
              .onPress(() {
            context.fullScreenImageViewer(imageWidget);
          }),
          _delete(),
        ],
      );
    }

    return _buildCameraIcon(context);
  }

  /// Build camera icon widget
  Widget _buildCameraIcon(BuildContext context) {
    return Container(
      height: 200,
      width: double.infinity,
      decoration: BoxDecoration(
        color: AppColor.fieldBgColor(context),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Icon(
        Icons.camera_alt,
        size: 48,
        color: context.isDark ? AppColor.white10 : AppColor.black10,
      ),
    );
  }

  /// Check if the URL is a local file path
  /// Same logic as multi_image_picker_item.dart
  bool _isLocalUrl(String url) {
    if (url.isEmpty) return false;
    return url.startsWith("/") || url.startsWith("file://") || (url.length > 1 && url.substring(1).startsWith(':\\'));
  }

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

  Widget _delete() {
    if (widget.isClosed) return const SizedBox();
    return Container(
            height: 45.toScreenHeight,
            width: 45.toScreenHeight,
            margin: const EdgeInsets.only(top: 4, right: 4),
            decoration: BoxDecoration(
              color: (context.isDark ? AppColor.neutral20 : AppColor.neutral40).withValues(alpha: 0.4),
              border: Border.all(
                color: (context.isDark ? AppColor.neutral20 : AppColor.neutral40).withValues(alpha: 0.7),
              ),
              borderRadius: BorderRadius.circular(30),
              //boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
            ),
            child: "delete".toSvgAsset())
        .onPress(() {
      widget.onImageCaptured?.call(null);
    });
  }
}

/// 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) {
    // Update the controller text whenever comment changes
    commentController.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();
  }
}
