import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:syncrow_web/pages/space_tree/view/space_tree_view.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class LinkSpaceModelSpacesDialog extends StatefulWidget {
  final SpaceTemplateModel spaceModel;

  const LinkSpaceModelSpacesDialog({super.key, required this.spaceModel});

  @override
  State<LinkSpaceModelSpacesDialog> createState() =>
      _LinkSpaceModelSpacesDialogState();
}

class _LinkSpaceModelSpacesDialogState
    extends State<LinkSpaceModelSpacesDialog> {
  @override
  void initState() {
    context.read<LinkSpaceToModelBloc>().add(LinkSpaceModelSelectedIdsEvent());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      contentPadding: EdgeInsets.zero,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      backgroundColor: Colors.white,
      content: SizedBox(
        width: MediaQuery.of(context).size.width * 0.4,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDialogContent(),
            _buildActionButtons(),
          ],
        ),
      ),
    );
  }

  Widget _buildDialogContent() {
    widget.spaceModel.createdAt.toString();
    String formattedDate =
        DateFormat('yyyy-MM-dd').format(widget.spaceModel.createdAt!);
    String formattedTime =
        DateFormat('HH:mm:ss').format(widget.spaceModel.createdAt!);

    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(15.0),
        child: SizedBox(
          width: MediaQuery.of(context).size.width * 0.4,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Center(
                        child: Text(
                          "Link Space Model to Spaces",
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.blueAccent,
                          ),
                        ),
                      ),
                      const Divider(),
                      const SizedBox(height: 16),
                      _buildDetailRow(
                          "Space model name:", widget.spaceModel.modelName),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 4),
                        child: Row(
                          children: [
                            const Expanded(
                              child: Text(
                                "Creation date and time:",
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                "$formattedDate  $formattedTime",
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black),
                              ),
                            ),
                          ],
                        ),
                      ),
                      // _buildDetailRow("Creation date and time:",
                      //     widget.spaceModel.createdAt.toString()),
                      _buildDetailRow("Created by:", "Admin"),
                      const SizedBox(height: 12),
                      const Text(
                        "Link to:",
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const Text(
                        "Please select all the spaces where you would like to link the Routine.",
                        style: TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                      const SizedBox(height: 8),
                      Expanded(
                        child: SizedBox(
                          child: Column(
                            children: [
                              Expanded(
                                  flex: 7,
                                  child: Container(
                                      color: ColorsManager.whiteColors,
                                      child: SpaceTreeView(
                                          isSide: true,
                                          onSelect: () {
                                            context
                                                .read<LinkSpaceToModelBloc>()
                                                .add(
                                                    LinkSpaceModelSelectedIdsEvent());
                                          })))
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 50,
            decoration: const BoxDecoration(
              border: Border(
                right: BorderSide(
                  color: ColorsManager.grayColor,
                  width: 0.5,
                ),
                top: BorderSide(
                  color: ColorsManager.grayColor,
                  width: 1,
                ),
              ),
            ),
            child: _buildButton("Cancel", Colors.grey, () {
              Navigator.of(context).pop();
            }),
          ),
        ),
        Expanded(
          child: Container(
            height: 50,
            decoration: const BoxDecoration(
              border: Border(
                left: BorderSide(
                  color: ColorsManager.grayColor,
                  width: 0.5,
                ),
                top: BorderSide(
                  color: ColorsManager.grayColor,
                  width: 1.0,
                ),
              ),
            ),
            child: _buildButton(
              "Confirm",
              ColorsManager.onSecondaryColor,
              () {
                final spaceModelBloc = context.read<LinkSpaceToModelBloc>();
                if (!spaceModelBloc.hasSelectedSpaces) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                        content: Text("Please select at least one space")),
                  );
                  return;
                } else {
                  spaceModelBloc.add(ValidateSpaceModelEvent(context: context));
                }
              },
            ),
          ),
        ),
      ],
    );
  }
}

Widget _buildDetailRow(String label, String value) {
  return Padding(
    padding: const EdgeInsets.symmetric(vertical: 4),
    child: Row(
      children: [
        Expanded(
          child: Text(
            label,
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(
                fontWeight: FontWeight.bold, color: Colors.black),
          ),
        ),
      ],
    ),
  );
}

Widget _buildButton(String text, Color color, VoidCallback onPressed) {
  return InkWell(
    onTap: onPressed,
    child: Center(
      child: Text(
        text,
        style:
            TextStyle(color: color, fontWeight: FontWeight.w400, fontSize: 14),
      ),
    ),
  );
}
