import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_bloc.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_event.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_state.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/helper/garage_door_helper.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/extension/build_context_x.dart';
import 'package:syncrow_web/utils/format_date_time.dart';

class ScheduleGarageTableWidget extends StatelessWidget {
  final GarageDoorLoadedState state;

  const ScheduleGarageTableWidget({
    super.key,
    required this.state,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Table(
          border: TableBorder.all(
            color: ColorsManager.graysColor,
            borderRadius: const BorderRadius.vertical(top: 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<GarageDoorBloc, GarageDoorState>(
          builder: (context, state) {
            if (state is ScheduleGarageLoadingState) {
              return const SizedBox(
                  height: 200,
                  child: Center(child: CircularProgressIndicator()));
            }
            if (state is GarageDoorLoadedState &&
                state.status.schedules!.isEmpty) {
              return _buildEmptyState(context);
            } else if (state is GarageDoorLoadedState) {
              return Container(
                  height: 200,
                  decoration: BoxDecoration(
                    border: Border.all(color: ColorsManager.graysColor),
                    borderRadius: const BorderRadius.vertical(
                        bottom: Radius.circular(20)),
                  ),
                  child: _buildTableBody(state, context));
            }
            return const SizedBox(
              height: 200,
            );
          },
        ),
      ],
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Container(
      height: 200,
      decoration: BoxDecoration(
        border: Border.all(color: ColorsManager.graysColor),
        borderRadius: const BorderRadius.vertical(top: 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: context.textTheme.bodySmall!.copyWith(
                  fontSize: 13,
                  color: ColorsManager.grayColor,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTableBody(GarageDoorLoadedState state, BuildContext context) {
    return SizedBox(
      height: 200,
      child: SingleChildScrollView(
        child: Table(
          border: TableBorder.all(color: ColorsManager.graysColor),
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: [
            if (state.status.schedules != null)
              for (int i = 0; i < state.status.schedules!.length; i++)
                _buildScheduleRow(
                    state.status.schedules![i], i, context, state),
          ],
        ),
      ),
    );
  }

  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, GarageDoorLoadedState state) {
    return TableRow(
      children: [
        Center(
          child: GestureDetector(
            onTap: () {
              context.read<GarageDoorBloc>().add(UpdateGarageDoorScheduleEvent(
                    index: index,
                    enable: !schedule.enable,
                    scheduleId: schedule.scheduleId,
                    deviceId: state.status.uuid,
                    functionOn: schedule.function.value,
                  ));
            },
            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))),
        Center(child: Text(schedule.function.value ? 'On' : 'Off')),
        Center(
          child: Wrap(
            runAlignment: WrapAlignment.center,
            children: [
              TextButton(
                style: TextButton.styleFrom(padding: EdgeInsets.zero),
                onPressed: () {
                  GarageDoorDialogHelper.showAddGarageDoorScheduleDialog(
                      context,
                      schedule: schedule,
                      index: index,
                      isEdit: true);
                },
                child: Text(
                  'Edit',
                  style: context.textTheme.bodySmall!
                      .copyWith(color: ColorsManager.blueColor),
                ),
              ),
              TextButton(
                style: TextButton.styleFrom(padding: EdgeInsets.zero),
                onPressed: () {
                  context
                      .read<GarageDoorBloc>()
                      .add(DeleteGarageDoorScheduleEvent(
                        index: index,
                        scheduleId: schedule.scheduleId,
                        deviceId: state.status.uuid,
                      ));
                },
                child: Text(
                  'Delete',
                  style: context.textTheme.bodySmall!
                      .copyWith(color: ColorsManager.blueColor),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  String _getSelectedDays(List<bool> selectedDays) {
    final days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    List<String> selectedDaysStr = [];
    for (int i = 0; i < selectedDays.length; i++) {
      if (selectedDays[i]) {
        selectedDaysStr.add(days[i]);
      }
    }
    return selectedDaysStr.join(', ');
  }
}
