import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/device_managment/schedule_device/bloc/schedule_bloc.dart';
import 'package:syncrow_web/pages/device_managment/water_heater/helper/add_schedule_dialog_helper.dart';
import 'package:syncrow_web/pages/device_managment/water_heater/models/schedule_entry.dart';
import 'package:syncrow_web/pages/device_managment/water_heater/models/schedule_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/format_date_time.dart';

class ScheduleTableWidget extends StatelessWidget {
  final String deviceUuid;
  final String category;
  final String deviceType;

  const ScheduleTableWidget({
    super.key,
    required this.deviceUuid,
    this.category = 'switch_1',
    required this.deviceType,
  });

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => ScheduleBloc(
        deviceId: deviceUuid,
      )..add(ScheduleGetEvent(category: category)),
      child: _ScheduleTableView(deviceType),
    );
  }
}

class _ScheduleTableView extends StatelessWidget {
  final String deviceType;
  const _ScheduleTableView(this.deviceType);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Table(
          border: TableBorder.all(
            color: ColorsManager.graysColor,
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(20), topRight: Radius.circular(20)),
          ),
          children: [
            TableRow(
              decoration: const BoxDecoration(
                color: ColorsManager.boxColor,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20),
                  topRight: Radius.circular(20),
                ),
              ),
              children: [
                _buildTableHeader('Active'),
                _buildTableHeader('Days'),
                _buildTableHeader('Time'),
                _buildTableHeader('Function'),
                _buildTableHeader('Action'),
              ],
            ),
          ],
        ),
        BlocBuilder<ScheduleBloc, ScheduleState>(
          builder: (context, state) {
            if (state is ScheduleLoading) {
              return const SizedBox(
                  height: 200,
                  child: Center(child: CircularProgressIndicator()));
            }
            if (state is ScheduleLoaded && state.schedules.isEmpty) {
              return _buildEmptyState(context);
            }
            if (state is ScheduleLoaded) {
              return Container(
                  height: 200,
                  decoration: BoxDecoration(
                    border: Border.all(color: ColorsManager.graysColor),
                    borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(20),
                        bottomRight: Radius.circular(20)),
                  ),
                  child: _buildTableBody(state.schedules, context, deviceType));
            }
            if (state is ScheduleError) {
              return Center(child: Text(state.error));
            }
            return const SizedBox(height: 200);
          },
        ),
      ],
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Container(
      height: 200,
      decoration: BoxDecoration(
        border: Border.all(color: ColorsManager.graysColor),
        borderRadius: const BorderRadius.only(
            bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
      ),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SvgPicture.asset(Assets.emptyRecords, width: 40, height: 40),
            const SizedBox(height: 8),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'No schedules added yet',
                style: Theme.of(context).textTheme.bodySmall!.copyWith(
                      fontSize: 13,
                      color: ColorsManager.grayColor,
                    ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTableBody(
      List<ScheduleModel> schedules, BuildContext context, String deviceType) {
    return SizedBox(
      height: 200,
      child: SingleChildScrollView(
        child: Table(
          border: TableBorder.all(color: ColorsManager.graysColor),
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: [
            for (int i = 0; i < schedules.length; i++)
              _buildScheduleRow(schedules[i], i, context,
                  deviceType: deviceType),
          ],
        ),
      ),
    );
  }

  Widget _buildTableHeader(String label) {
    return TableCell(
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Text(
          label,
          style: const TextStyle(
            fontSize: 13,
            color: ColorsManager.grayColor,
          ),
        ),
      ),
    );
  }

  TableRow _buildScheduleRow(
      ScheduleModel schedule, int index, BuildContext context,
      {required String deviceType}) {
    return TableRow(
      children: [
        Center(
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              context.read<ScheduleBloc>().add(
                    ScheduleUpdateEntryEvent(
                      category: schedule.category,
                      scheduleId: schedule.scheduleId,
                      functionOn: schedule.function.value,
                      enable: !schedule.enable,
                    ),
                  );
            },
            child: Center(
              child: SizedBox(
                width: 24,
                height: 24,
                child: schedule.enable
                    ? const Icon(Icons.radio_button_checked,
                        color: ColorsManager.blueColor)
                    : const Icon(Icons.radio_button_unchecked,
                        color: ColorsManager.grayColor),
              ),
            ),
          ),
        ),
        Center(
            child: Text(_getSelectedDays(
                ScheduleModel.parseSelectedDays(schedule.days)))),
        Center(child: Text(formatIsoStringToTime(schedule.time, context))),
        if (deviceType == 'CUR_2')
          Center(
              child: Text(schedule.function.value == true ? 'open' : 'close'))
        else
          Center(child: Text(schedule.function.value ? 'On' : 'Off')),
        Center(
          child: Wrap(
            runAlignment: WrapAlignment.center,
            children: [
              TextButton(
                style: TextButton.styleFrom(padding: EdgeInsets.zero),
                onPressed: () {
                  ScheduleDialogHelper.showAddScheduleDialog(context,
                          schedule: ScheduleEntry.fromScheduleModel(schedule),
                          isEdit: true,
                          deviceType: deviceType)
                      .then((updatedSchedule) {
                    if (updatedSchedule != null) {
                      bool temp;
                      if (deviceType == 'CUR_2') {
                        updatedSchedule.function.value == 'open'
                            ? temp = true
                            : temp = false;
                      } else {
                        temp = updatedSchedule.function.value;
                      }
                      context.read<ScheduleBloc>().add(
                            ScheduleEditEvent(
                                deviceType: deviceType,
                                scheduleId: schedule.scheduleId,
                                category: schedule.category,
                                time: updatedSchedule.time,
                                functionOn: temp,
                                selectedDays: updatedSchedule.days),
                          );
                    }
                  });
                },
                child: Text(
                  'Edit',
                  style: Theme.of(context)
                      .textTheme
                      .bodySmall!
                      .copyWith(color: ColorsManager.blueColor),
                ),
              ),
              TextButton(
                style: TextButton.styleFrom(padding: EdgeInsets.zero),
                onPressed: () async {
                  final confirmed = await showDialog<bool>(
                    context: context,
                    builder: (BuildContext dialogContext) {
                      return AlertDialog(
                        title: const Text('Confirm Delete'),
                        content: const Text(
                            'Are you sure you want to delete this schedule?'),
                        actions: [
                          TextButton(
                            onPressed: () =>
                                Navigator.of(dialogContext).pop(false),
                            child: Text('Cancel'),
                          ),
                          TextButton(
                            onPressed: () =>
                                Navigator.of(dialogContext).pop(true),
                            child: const Text(
                              'Delete',
                              style: TextStyle(color: Colors.red),
                            ),
                          ),
                        ],
                      );
                    },
                  );

                  if (confirmed == true) {
                    context.read<ScheduleBloc>().add(
                          ScheduleDeleteEvent(schedule.scheduleId),
                        );
                  }
                },
                child: Text(
                  'Delete',
                  style: Theme.of(context)
                      .textTheme
                      .bodySmall!
                      .copyWith(color: ColorsManager.blueColor),
                ),
              )
            ],
          ),
        ),
      ],
    );
  }

  String _getSelectedDays(List<bool> selectedDays) {
    const days = ScheduleDialogHelper.allDays;
    return selectedDays
        .asMap()
        .entries
        .where((entry) => entry.value)
        .map((entry) => days[entry.key])
        .join(', ');
  }
}
