import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/common/buttons/search_reset_buttons.dart';
import 'package:syncrow_web/pages/common/custom_table.dart';
import 'package:syncrow_web/pages/common/date_time_widget.dart';
import 'package:syncrow_web/pages/common/filter/filter_widget.dart';
import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart';
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_state.dart';
import 'package:syncrow_web/pages/visitor_password/view/visitor_password_dialog.dart';
import 'package:syncrow_web/utils/constants/app_enum.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_bloc.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_event.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
import 'package:syncrow_web/utils/style.dart';

class AccessOverviewContent extends StatelessWidget
    with HelperResponsiveLayout {
  const AccessOverviewContent({super.key});

  @override
  Widget build(BuildContext context) {
    final isLargeScreen = isLargeScreenSize(context);
    final isSmallScreen = isSmallScreenSize(context);
    final isHalfMediumScreen = isHafMediumScreenSize(context);
    final padding =
        isLargeScreen ? const EdgeInsets.all(30) : const EdgeInsets.all(15);

    return BlocProvider(
        create: (BuildContext context) => AccessBloc()..add(FetchTableData()),
        child: BlocConsumer<AccessBloc, AccessState>(
            listener: (context, state) {},
            builder: (context, state) {
              final accessBloc = BlocProvider.of<AccessBloc>(context);
              final filteredData = accessBloc.filteredData;
              return state is AccessLoaded
                  ? const Center(child: CircularProgressIndicator())
                  : Container(
                      padding: padding,
                      height: MediaQuery.of(context).size.height,
                      width: MediaQuery.of(context).size.width,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          FilterWidget(
                            size: MediaQuery.of(context).size,
                            tabs: accessBloc.tabs,
                            selectedIndex: accessBloc.selectedIndex,
                            onTabChanged: (index) {
                              accessBloc.add(TabChangedEvent(index));
                            },
                          ),
                          const SizedBox(height: 20),
                          if (isSmallScreen || isHalfMediumScreen)
                            _buildSmallSearchFilters(context, accessBloc)
                          else
                            _buildNormalSearchWidgets(context, accessBloc),
                          const SizedBox(height: 20),
                          _buildVisitorAdminPasswords(context, accessBloc),
                          const SizedBox(height: 20),
                          Expanded(
                              child: DynamicTable(
                            tableName: 'AccessManagement',
                            uuidIndex: 1,
                            withSelectAll: true,
                            isEmpty: filteredData.isEmpty,
                            withCheckBox: false,
                            size: MediaQuery.of(context).size,
                            cellDecoration: containerDecoration,
                            headers: const [
                              'Name',
                              'Access Type',
                              'Access Start',
                              'Access End',
                              'Accessible Device',
                              'Authorizer',
                              'Authorization Date & Time',
                              'Access Status'
                            ],
                            data: filteredData.map((item) {
                              return [
                                item.passwordName,
                                item.passwordType.value,
                                accessBloc.timestampToDate(item.effectiveTime),
                                accessBloc.timestampToDate(item.invalidTime),
                                item.deviceName.toString(),
                                item.authorizerEmail.toString(),
                                accessBloc.timestampToDate(item.invalidTime),
                                item.passwordStatus.value,
                              ];
                            }).toList(),
                          )),
                        ],
                      ),
                    );
            }));
  }

  Wrap _buildVisitorAdminPasswords(
      BuildContext context, AccessBloc accessBloc) {
    return Wrap(
      spacing: 10,
      runSpacing: 10,
      children: [
        Container(
          width: 205,
          height: 42,
          decoration: containerDecoration,
          child: DefaultButton(
              onPressed: () {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return const VisitorPasswordDialog();
                  },
                ).then((v) {
                  if (v != null) {
                    accessBloc.add(FetchTableData());
                  }
                });
              },
              borderRadius: 8,
              child: Text(
                'Create Visitor Password ',
                style: context.textTheme.titleSmall!
                    .copyWith(color: Colors.white, fontSize: 12),
              )),
        ),
        // Container(
        //   width: 133,
        //   height: 42,
        //   decoration: containerDecoration,
        //   child: DefaultButton(
        //       borderRadius: 8,
        //       backgroundColor: ColorsManager.whiteColors,
        //       child: Text(
        //         'Admin Password',
        //         style: context.textTheme.titleSmall!
        //             .copyWith(color: Colors.black, fontSize: 12),
        //       )),
        // ),
      ],
    );
  }

  Row _buildNormalSearchWidgets(BuildContext context, AccessBloc accessBloc) {
    // TimeOfDay _selectedTime = TimeOfDay.now();

    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.end,
      textBaseline: TextBaseline.ideographic,
      children: [
        SizedBox(
          width: 250,
          child: CustomWebTextField(
            controller: accessBloc.passwordName,
            height: 43,
            isRequired: false,
            textFieldName: 'Name',
            description: '',
            onSubmitted: (value) {
              accessBloc.add(FilterDataEvent(
                  emailAuthorizer:
                      accessBloc.emailAuthorizer.text.toLowerCase(),
                  selectedTabIndex:
                      BlocProvider.of<AccessBloc>(context).selectedIndex,
                  passwordName: accessBloc.passwordName.text.toLowerCase(),
                  startTime: accessBloc.effectiveTimeTimeStamp,
                  endTime: accessBloc.expirationTimeTimeStamp));
            },
          ),
        ),
        const SizedBox(width: 15),
        SizedBox(
          width: 250,
          child: CustomWebTextField(
            controller: accessBloc.emailAuthorizer,
            height: 43,
            isRequired: false,
            textFieldName: 'Authorizer',
            description: '',
            onSubmitted: (value) {
              accessBloc.add(FilterDataEvent(
                  emailAuthorizer:
                      accessBloc.emailAuthorizer.text.toLowerCase(),
                  selectedTabIndex:
                      BlocProvider.of<AccessBloc>(context).selectedIndex,
                  passwordName: accessBloc.passwordName.text.toLowerCase(),
                  startTime: accessBloc.effectiveTimeTimeStamp,
                  endTime: accessBloc.expirationTimeTimeStamp));
            },
          ),
        ),
        const SizedBox(width: 15),
        SizedBox(
          child: DateTimeWebWidget(
            icon: Assets.calendarIcon,
            isRequired: false,
            title: 'Access Time',
            size: MediaQuery.of(context).size,
            endTime: () {
              accessBloc.add(SelectTime(context: context, isStart: false));
            },
            startTime: () {
              accessBloc.add(SelectTime(context: context, isStart: true));
            },
            firstString: BlocProvider.of<AccessBloc>(context).startTime,
            secondString: BlocProvider.of<AccessBloc>(context).endTime,
          ),
        ),
        const SizedBox(width: 15),
        SearchResetButtons(
          onSearch: () {
            accessBloc.add(FilterDataEvent(
                emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(),
                selectedTabIndex:
                    BlocProvider.of<AccessBloc>(context).selectedIndex,
                passwordName: accessBloc.passwordName.text.toLowerCase(),
                startTime: accessBloc.effectiveTimeTimeStamp,
                endTime: accessBloc.expirationTimeTimeStamp));
          },
          onReset: () {
            accessBloc.add(ResetSearch());
          },
        ),
      ],
    );
  }

  Widget _buildSmallSearchFilters(BuildContext context, AccessBloc accessBloc) {
    return Wrap(
      spacing: 20,
      runSpacing: 10,
      children: [
        SizedBox(
          width: 300,
          child: CustomWebTextField(
              controller: accessBloc.passwordName,
              isRequired: true,
              height: 40,
              textFieldName: 'Name',
              description: '',
              onSubmitted: (value) {
                accessBloc.add(FilterDataEvent(
                    emailAuthorizer:
                        accessBloc.emailAuthorizer.text.toLowerCase(),
                    selectedTabIndex:
                        BlocProvider.of<AccessBloc>(context).selectedIndex,
                    passwordName: accessBloc.passwordName.text.toLowerCase(),
                    startTime: accessBloc.effectiveTimeTimeStamp,
                    endTime: accessBloc.expirationTimeTimeStamp));
              }),
        ),
        DateTimeWebWidget(
          icon: Assets.calendarIcon,
          isRequired: false,
          title: 'Access Time',
          size: MediaQuery.of(context).size,
          endTime: () {
            accessBloc.add(SelectTime(context: context, isStart: false));
          },
          startTime: () {
            accessBloc.add(SelectTime(context: context, isStart: true));
          },
          firstString: BlocProvider.of<AccessBloc>(context).startTime,
          secondString: BlocProvider.of<AccessBloc>(context).endTime,
        ),
        SearchResetButtons(
          onSearch: () {
            accessBloc.add(FilterDataEvent(
                emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(),
                selectedTabIndex:
                    BlocProvider.of<AccessBloc>(context).selectedIndex,
                passwordName: accessBloc.passwordName.text.toLowerCase(),
                startTime: accessBloc.effectiveTimeTimeStamp,
                endTime: accessBloc.expirationTimeTimeStamp));
          },
          onReset: () {
            accessBloc.add(ResetSearch());
          },
        ),
      ],
    );
  }
}
