import 'dart:convert';
import 'dart:io' as io show Directory, File;
import 'package:flutter_quill/flutter_quill.dart' hide Text;
import 'package:flutter/material.dart';
import 'package:flutter_quill/flutter_quill.dart' hide Text;
import 'package:flutter_quill_extensions/flutter_quill_extensions.dart';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_quill/flutter_quill.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_quill/flutter_quill_internal.dart';
import 'package:flutter_quill/quill_delta.dart';
import 'package:flutter_quill_extensions/flutter_quill_extensions.dart';
import 'package:frontend/Screens/myTemplates/quill_delta_sample.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:path/path.dart' as path;
import 'package:responsive_builder/responsive_builder.dart';

import '../../routes/custom_appBar.dart';
import '../../routes/custom_drawer.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart';
import '../../widgets/custom_user_travel.dart';

class Template extends StatefulWidget {
  final Map<String, dynamic>? templateData;

  const Template({super.key, required this.templateData});

  static Template fromState(GoRouterState state) {
    return Template(templateData: state.extra as Map<String, dynamic>?);
  }

  @override
  TemplateState createState() => TemplateState();
}

class TemplateState extends State<Template> {
  final ApiService apiService = ApiService();
  final QuillController _controller = () {
    return QuillController.basic(
        config: QuillControllerConfig(
      clipboardConfig: QuillClipboardConfig(
        enableExternalRichPaste: true,
        onImagePaste: (imageBytes) async {
          if (kIsWeb) {
            // Dart IO is unsupported on the web.
            return null;
          }
          // Save the image somewhere and return the image URL that will be
          // stored in the Quill Delta JSON (the document).
          final newFileName =
              'image-file-${DateTime.now().toIso8601String()}.png';
          final newPath = path.join(
            io.Directory.systemTemp.path,
            newFileName,
          );
          final file = await io.File(
            newPath,
          ).writeAsBytes(imageBytes, flush: true);
          return file.path;
        },
      ),
    ));
  }();
  final FocusNode _editorFocusNode = FocusNode();
  final ScrollController _editorScrollController = ScrollController();
  // final QuillController _controller = QuillController.basic();
  Color layoutColor = Colors.redAccent;
  Color bodyColor = Colors.white;
  final Map<String, TextEditingController> controllers = {};
  List<String> dataHeader = ["subject"];

  Map<String, dynamic> get TemplateData {
    final data = {
      // "org_id": orgId;
      "template_name": controllers["templateName"]?.text,
      "subject": controllers["subject"]?.text,
      "body_html": controllers["bodyData"]?.text,
      "placeholder": [],
      // "created_by": userId
    };

    // Only add group_id if it's an edit operation
    // if (widget.templateData != null && widget.templateData!.containsKey('group_id')) {
    //   data["template_id"] = templateData;
    // }

    return data;
  }

  @override
  void initState() {
    super.initState();

    for (var field in dataHeader) {
      controllers[field] = TextEditingController();
    }

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _editorFocusNode.requestFocus(); // ✅ Ensure focus is requested
    });
    _controller.document = Document.fromJson(kQuillDefaultSample);
    // _controller.document = Document.fromJson(kQuillDefaultSample);
    // _controller.document = Document.fromJson();
    // _controller.document.toPlainText();
    // _controller.readOnly = false;
    updateData();

    loadInitialData();
  }

  @override
  // void dispose() {
  //   // controllers.dispose();
  //   // _editorScrollController.dispose();
  //   _editorFocusNode.dispose();
  //   super.dispose();
  // }

  void dispose() {
    _controller.dispose();
    _editorScrollController.dispose();
    _editorFocusNode.dispose();
    super.dispose();
  }

  void loadInitialData() async {
    String? layoutString = await getLayoutColor();
    String? bodyStringColor = await getBodyColor();

    setState(() {
      layoutColor = layoutString != null
          ? Color(int.parse(layoutString))
          : Colors.redAccent;

      bodyColor = bodyStringColor != null
          ? Color(int.parse(bodyStringColor))
          : Colors.white;
    });
  }

  Future<void> updateData() async {
    // Ensure apiselectedUser is not null before printing
    if (widget.templateData != null) {
      print("API Selected User Has Data - ${widget.templateData}");
      print(
          "API Selected User Has  - ${widget.templateData?["templateData"]?["subject"]}");
      setState(() {
        // ✅ Wrap in setState to update the UI
        controllers["subject"]?.text =
            widget.templateData?["templateData"]?["subject"] ?? "";

        // if (widget.group?["international_policy_id"] != null) {
        //   selectedInternational =
        //       widget.group!["international_policy_id"].toString();
        // }
      });
    } else {
      print("API Selected User Has Data - No data available yet");
    }
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(builder: (context, sizingInfo) {
      bool isDesktop = sizingInfo.deviceScreenType == DeviceScreenType.desktop;

      return Scaffold(
        backgroundColor: const Color(0xFFf5f5f5),
        appBar: CustomAppBar(isDesktop: isDesktop),
        drawer: CustomDrawer(isDesktop: false),
        body: Padding(
          padding: isDesktop
              ? EdgeInsets.symmetric(
                  horizontal: MediaQuery.of(context).size.width *
                      0.1, // 30% of screen width as horizontal padding
                  vertical: MediaQuery.of(context).size.height *
                      0, // 5% of screen height as vertical padding
                )
              : EdgeInsets.all(0),
          child: Row(
            children: [
              // if (isDesktop) CustomDrawer(isDesktop: true),
              Expanded(
                  child: buildUserTable(
                      isDesktop, context, bodyColor, layoutColor)),
            ],
          ),
        ),
      );
    });
  }

  Widget buildUserTable(
      bool isDesktop, context, Color? bodyColor, Color layoutColor) {
    return Container(
      margin: isDesktop ? const EdgeInsets.only(top: 10.0, bottom: 10.0) : null,
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: isDesktop ? Colors.white : Color(0xFFFCFCFC),
      ),
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Text("Editor"),
            SizedBox(
              height: 20,
            ),
            buildTempalteSubject(isDesktop),
            IconButton(
              icon: const Icon(Icons.output),
              tooltip: 'Print Delta JSON to log',
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                    content: Text(
                        'The JSON Delta has been printed to the console.')));
                debugPrint(jsonEncode(_controller.document.toDelta().toJson()));
              },
            ),
            SizedBox(
              height: 20,
            ),
            buildTempalteBody(isDesktop)
          ],
        ),
      ),
    );
  }

  Widget buildTempalteSubject(bool isDesktop) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "Subject",
          style: GoogleFonts.poppins(
              fontSize: 12, fontWeight: FontWeight.w400, color: Colors.black),
        ),
        SizedBox(height: 5),
        CustomTextFieldUserTravellerWrapper(
          isFocused: false,
          isDesktop: isDesktop,
          child: SizedBox(
            height: 40,
            child: TextField(
              style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              controller: controllers["subject"],
              onChanged: (value) {
                // _clearError("local_id_num");
              },
              decoration: InputDecoration(
                labelText: "enter the subject",
                labelStyle:
                    GoogleFonts.poppins(fontSize: 12, color: Colors.grey),
                floatingLabelBehavior: FloatingLabelBehavior.never,
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(vertical: 16),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildTempalteBody(bool isDesktop) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "Content",
          style: GoogleFonts.poppins(
            fontSize: 12,
            fontWeight: FontWeight.w400,
            color: Colors.black,
          ),
        ),

        const SizedBox(height: 10),

        // Expanded(
        //
        //   child: QuillEditor(
        //     focusNode: _editorFocusNode,
        //     scrollController: _editorScrollController,
        //     controller: _controller,
        //     config: QuillEditorConfig(
        //       placeholder: 'Start writing your notes...',
        //       padding: const EdgeInsets.all(16),
        //       embedBuilders: [
        //         ...FlutterQuillEmbeds.editorBuilders(
        //           imageEmbedConfig: QuillEditorImageEmbedConfig(
        //             imageProviderBuilder: (context, imageUrl) {
        //               // https://pub.dev/packages/flutter_quill_extensions#-image-assets
        //               if (imageUrl.startsWith('assets/')) {
        //                 return AssetImage(imageUrl);
        //               }
        //               return null;
        //             },
        //           ),
        //           videoEmbedConfig: QuillEditorVideoEmbedConfig(
        //             customVideoBuilder: (videoUrl, readOnly) {
        //               // To load YouTube videos https://github.com/singerdmx/flutter-quill/releases/tag/v10.8.0
        //               return null;
        //             },
        //           ),
        //         ),
        //         TimeStampEmbedBuilder(),
        //       ],
        //     ),
        //   ),
        // ),

        // ✅ Modern toolbar
        QuillSimpleToolbar(
          controller: _controller,
          config: QuillSimpleToolbarConfig(
            embedButtons: FlutterQuillEmbeds.toolbarButtons(),
            showClipboardPaste: true,
            customButtons: [
              QuillToolbarCustomButtonOptions(
                icon: const Icon(Icons.add_alarm_rounded),
                onPressed: () {
                  _controller.document.insert(
                    _controller.selection.extentOffset,
                    TimeStampEmbed(
                      DateTime.now().toString(),
                    ),
                  );
                  _controller.readOnly = true;
                  _controller.updateSelection(
                    TextSelection.collapsed(
                      offset: _controller.selection.extentOffset + 1,
                    ),
                    ChangeSource.local,
                  );
                },
              ),
            ],
            buttonOptions: QuillSimpleToolbarButtonOptions(
              base: QuillToolbarBaseButtonOptions(
                afterButtonPressed: () {
                  final isDesktop = {
                    TargetPlatform.linux,
                    TargetPlatform.windows,
                    TargetPlatform.macOS
                  }.contains(defaultTargetPlatform);
                  if (isDesktop) {
                    _editorFocusNode.requestFocus();
                  }
                },
              ),
              linkStyle: QuillToolbarLinkStyleButtonOptions(
                validateLink: (link) {
                  // Treats all links as valid. When launching the URL,
                  // `https://` is prefixed if the link is incomplete (e.g., `google.com` → `https://google.com`)
                  // however this happens only within the editor.
                  return true;
                },
              ),
            ),
          ),
        ),
        const SizedBox(height: 10),

        // // ✅ Modern editor
        Container(
          height: 200,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(8),
          ),
          child: QuillEditor(
            focusNode: _editorFocusNode,
            scrollController: _editorScrollController,
            controller: _controller,
            config: QuillEditorConfig(
              placeholder: 'Start writing your notes...',
              padding: const EdgeInsets.all(16),
              embedBuilders: [
                ...FlutterQuillEmbeds.editorBuilders(
                  imageEmbedConfig: QuillEditorImageEmbedConfig(
                    imageProviderBuilder: (context, imageUrl) {
                      // https://pub.dev/packages/flutter_quill_extensions#-image-assets
                      if (imageUrl.startsWith('assets/')) {
                        return AssetImage(imageUrl);
                      }
                      return null;
                    },
                  ),
                  videoEmbedConfig: QuillEditorVideoEmbedConfig(
                    customVideoBuilder: (videoUrl, readOnly) {
                      // To load YouTube videos https://github.com/singerdmx/flutter-quill/releases/tag/v10.8.0
                      return null;
                    },
                  ),
                ),
                TimeStampEmbedBuilder(),
              ],
            ),
          ),
        ),

        // child: QuillEditor.basic(
        //   focusNode: _editorFocusNode,
        //   scrollController: _editorScrollController,
        //   controller: _controller,
        //   // readOnly: true,
        //   config: QuillEditorConfig(
        //     requestKeyboardFocusOnCheckListChanged: false,
        //     // readOnlyMouseCursor: SystemMouseCursors.text,
        //     enableScribble: true,
        //     // readOnly: false,
        //     padding: const EdgeInsets.all(8),
        //     placeholder: 'Type something...',
        //     embedBuilders: [
        //       ...FlutterQuillEmbeds.editorBuilders(
        //         imageEmbedConfig: QuillEditorImageEmbedConfig(
        //           imageProviderBuilder: (context, imageUrl) {
        //             // https://pub.dev/packages/flutter_quill_extensions#-image-assets
        //             if (imageUrl.startsWith('assets/')) {
        //               return AssetImage(imageUrl);
        //             }
        //             return null;
        //           },
        //         ),
        //         videoEmbedConfig: QuillEditorVideoEmbedConfig(
        //           customVideoBuilder: (videoUrl, readOnly) {
        //             // To load YouTube videos https://github.com/singerdmx/flutter-quill/releases/tag/v10.8.0
        //             return null;
        //           },
        //         ),
        //       ),
        //       TimeStampEmbedBuilder(),
        //     ],
        //   ),
        // ),
      ],
    );
  }
}

class TimeStampEmbed extends Embeddable {
  const TimeStampEmbed(
    String value,
  ) : super(timeStampType, value);

  static const String timeStampType = 'timeStamp';

  static TimeStampEmbed fromDocument(Document document) =>
      TimeStampEmbed(jsonEncode(document.toDelta().toJson()));

  Document get document => Document.fromJson(jsonDecode(data));
}

class TimeStampEmbedBuilder extends EmbedBuilder {
  @override
  String get key => 'timeStamp';

  @override
  String toPlainText(Embed node) {
    return node.value.data;
  }

  @override
  Widget build(
    BuildContext context,
    EmbedContext embedContext,
  ) {
    return Row(
      children: [
        const Icon(Icons.access_time_rounded),
        Text(embedContext.node.value.data as String),
      ],
    );
  }
}
