import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_quill/flutter_quill.dart' as quill;
import 'package:marco/controller/directory/add_comment_controller.dart';
import 'package:marco/helpers/widgets/my_spacing.dart';
import 'package:marco/helpers/widgets/my_text.dart';
import 'package:marco/helpers/widgets/Directory/comment_editor_card.dart';

class AddCommentBottomSheet extends StatefulWidget {
  final String contactId;

  const AddCommentBottomSheet({super.key, required this.contactId});

  @override
  State<AddCommentBottomSheet> createState() => _AddCommentBottomSheetState();
}

class _AddCommentBottomSheetState extends State<AddCommentBottomSheet> {
  late final AddCommentController controller;
  late final quill.QuillController quillController;

  @override
  void initState() {
    super.initState();
    controller = Get.put(AddCommentController(contactId: widget.contactId));
    quillController = quill.QuillController.basic();
  }

  @override
  void dispose() {
    quillController.dispose();
    Get.delete<AddCommentController>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: MediaQuery.of(context).viewInsets,
      child: Container(
        decoration: BoxDecoration(
          color: Theme.of(context).cardColor,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
          boxShadow: const [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 12,
              offset: Offset(0, -2),
            ),
          ],
        ),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 16, 20, 32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Center(
                child: Container(
                  width: 40,
                  height: 5,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade300,
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              ),
              MySpacing.height(12),
              Center(child: MyText.titleMedium("Add Comment", fontWeight: 700)),
              MySpacing.height(24),
              CommentEditorCard(
                controller: quillController,
                onCancel: () => Get.back(),
                onSave: (editorController) async {
                  final delta = editorController.document.toDelta();
                  final htmlOutput = _convertDeltaToHtml(delta);
                  controller.updateNote(htmlOutput);
                  await controller.submitComment();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _convertDeltaToHtml(dynamic delta) {
    final buffer = StringBuffer();
    bool inList = false;

    for (var op in delta.toList()) {
      final data = op.data?.toString() ?? '';
      final attr = op.attributes ?? {};

      final isListItem = attr.containsKey('list');
      final trimmedData = data.trim();

      if (isListItem && !inList) {
        buffer.write('<ul>');
        inList = true;
      }

      if (!isListItem && inList) {
        buffer.write('</ul>');
        inList = false;
      }

      if (isListItem && trimmedData.isEmpty) continue;

      if (isListItem) buffer.write('<li>');

      if (attr.containsKey('bold')) buffer.write('<strong>');
      if (attr.containsKey('italic')) buffer.write('<em>');
      if (attr.containsKey('underline')) buffer.write('<u>');
      if (attr.containsKey('strike')) buffer.write('<s>');
      if (attr.containsKey('link')) buffer.write('<a href="${attr['link']}">');

      buffer.write(trimmedData.replaceAll('\n', ''));

      if (attr.containsKey('link')) buffer.write('</a>');
      if (attr.containsKey('strike')) buffer.write('</s>');
      if (attr.containsKey('underline')) buffer.write('</u>');
      if (attr.containsKey('italic')) buffer.write('</em>');
      if (attr.containsKey('bold')) buffer.write('</strong>');

      if (isListItem) {
        buffer.write('</li>');
      } else if (data.contains('\n')) {
        buffer.write('<br>');
      }
    }

    if (inList) buffer.write('</ul>');
    return buffer.toString();
  }
}
