import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/access_device_table.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_event.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_state.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/app_enum.dart';
import 'package:syncrow_web/utils/style.dart';

class AddDeviceDialog extends StatelessWidget {
  final List<String>? selectedDeviceIds;
  const AddDeviceDialog({super.key, this.selectedDeviceIds});
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return BlocProvider(
      create: (context) =>
          VisitorPasswordBloc()..add(FetchDevice()),
      child: BlocBuilder<VisitorPasswordBloc, VisitorPasswordState>(
        builder: (BuildContext context, VisitorPasswordState state) {
          final visitorBloc = BlocProvider.of<VisitorPasswordBloc>(context);
          if (state is TableLoaded) {
            for (var device in selectedDeviceIds!) {
              if (selectedDeviceIds!.contains(device)) {
                visitorBloc.add(SelectDeviceEvent(device));
              }
            }
          }

          return AlertDialog(
            backgroundColor: Colors.white,
            title: Text(
              'Add Accessible Device',
              style: Theme.of(context).textTheme.headlineLarge!.copyWith(
                  fontWeight: FontWeight.w400,
                  fontSize: 24,
                  color: Colors.black),
            ),
            content: SizedBox(
              height: MediaQuery.of(context).size.height / 1.7,
              width: MediaQuery.of(context).size.width / 2,
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Column(
                  children: <Widget>[
                    Container(
                        width: size.width,
                        padding: const EdgeInsets.all(15),
                        decoration: containerDecoration.copyWith(
                            color: ColorsManager.worningColor,
                            border: Border.all(color: Color(0xffFFD22F)),
                            boxShadow: []),
                        child: Row(
                          children: [
                            SizedBox(
                              child: SvgPicture.asset(
                                Assets.deviceNoteIcon,
                                height: 15,
                                width: 15,
                              ),
                            ),
                            const SizedBox(
                              width: 10,
                            ),
                            Text(
                              'Only online accessible devices can be added',
                              style: Theme.of(context)
                                  .textTheme
                                  .bodySmall!
                                  .copyWith(
                                      fontWeight: FontWeight.w400,
                                      fontSize: 12,
                                      color: ColorsManager.grayColor),
                            ),
                          ],
                        )),
                    const SizedBox(
                      height: 20,
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      textBaseline: TextBaseline.alphabetic,
                      children: [
                        Expanded(
                          flex: 4,
                          child: CustomWebTextField(
                            controller: visitorBloc.deviceNameController,
                            isRequired: false,
                            textFieldName: 'Device Name',
                            description: '',
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          flex: 4,
                          child: CustomWebTextField(
                            controller: visitorBloc.deviceIdController,
                            isRequired: false,
                            textFieldName: 'Device ID',
                            description: '',
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          flex: 4,
                          child: CustomWebTextField(
                            controller: visitorBloc.unitNameController,
                            isRequired: false,
                            textFieldName: 'Space Name',
                            description: '',
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          flex: 2,
                          child: Container(
                            child: SizedBox(
                              width: size.width * 0.06,
                              child: Center(
                                child: DefaultButton(
                                  onPressed: () {
                                    visitorBloc.filterDevices();
                                  },
                                  borderRadius: 9,
                                  child: const Text('Search'),
                                ),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          flex: 2,
                          child: Container(
                            width: size.width * 0.06,
                            child: DefaultButton(
                              backgroundColor: ColorsManager.whiteColors,
                              borderRadius: 9,
                              child: Text(
                                'Reset',
                                style: Theme.of(context)
                                    .textTheme
                                    .bodySmall!
                                    .copyWith(color: Colors.black),
                              ),
                              onPressed: () {
                                visitorBloc.deviceNameController.clear();
                                visitorBloc.deviceIdController.clear();
                                visitorBloc.unitNameController.clear();
                                visitorBloc.add(
                                    FetchDevice()); // Reset to original list
                              },
                            ),
                          ),
                        )
                      ],
                    ),
                    const SizedBox(height: 20),
                    Expanded(
                        flex: 3,
                        child: state is TableLoaded
                            ? AccessDeviceTable(
                                uuidIndex: 1,
                                withSelectAll: true,
                                initialSelectedIds: selectedDeviceIds,
                                cellDecoration: containerDecoration,
                                isEmpty: visitorBloc.data.isEmpty,
                                selectAll: (p0) {
                                  visitorBloc.selectedDeviceIds.clear();
                                  for (var item in state.data) {
                                    visitorBloc
                                        .add(SelectDeviceEvent(item.uuid));
                                  }
                                },
                                onRowSelected: (index, isSelected, row) {
                                  final deviceId = state.data[index].uuid;
                                  visitorBloc.add(SelectDeviceEvent(deviceId));
                                },
                                withCheckBox: true,
                                size: size * 0.5,
                                headers: const [
                                  'Device Name',
                                  'Device ID',
                                  'Access Type',
                                  'Space Name',
                                  'Status'
                                ],
                                data: state.data.map((item) {
                                  return [
                                    item.name.toString(),
                                    item.uuid.toString(),
                                    item.productType.toString(),
                                    item.spaceName.toString(),
                                    item.online.value.toString(),
                                  ];
                                }).toList(),
                              )
                            : const Center(child: CircularProgressIndicator()))
                  ],
                ),
              ),
            ),
            actionsAlignment: MainAxisAlignment.center,
            actions: <Widget>[
              Container(
                decoration: containerDecoration,
                width: size.width * 0.2,
                child: DefaultButton(
                  borderRadius: 8,
                  onPressed: () {
                    Navigator.of(context).pop(); // Close the dialog
                  },
                  backgroundColor: Colors.white,
                  child: Text(
                    'Cancel',
                    style: Theme.of(context).textTheme.bodyMedium!,
                  ),
                ),
              ),
              Container(
                decoration: containerDecoration,
                width: size.width * 0.2,
                child: DefaultButton(
                  onPressed: () {
                    visitorBloc.addDeviceToList(context);
                  },
                  borderRadius: 8,
                  child: Text('Ok'),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
