import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/device_managment/water_heater/models/schedule_entry.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';

class ScheduleDialogHelper {
  static const List<String> allDays = [
    'Sun',
    'Mon',
    'Tue',
    'Wed',
    'Thu',
    'Fri',
    'Sat'
  ];

  static Future<ScheduleEntry?> showAddScheduleDialog(
    BuildContext context, {
    ScheduleEntry? schedule,
    bool isEdit = false,
    String? code,
    required String deviceType,
  }) {
    bool temp;
    if (deviceType == 'CUR_2') {
      temp = schedule!.function.value == 'open' ? true : false;
    } else {
      temp = schedule!.function.value;
    }
    final initialTime = schedule != null
        ? _convertStringToTimeOfDay(schedule.time)
        : TimeOfDay.now();
    final initialDays = schedule != null
        ? _convertDaysStringToBooleans(schedule.days)
        : List.filled(7, false);
    bool? functionOn = temp;
    TimeOfDay selectedTime = initialTime;
    List<bool> selectedDays = List.of(initialDays);

    return showDialog<ScheduleEntry>(
      context: context,
      builder: (ctx) {
        return StatefulBuilder(
          builder: (ctx, setState) {
            return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const SizedBox(),
                      Text(
                        isEdit ? 'Edit Schedule' : 'Add Schedule',
                        style: Theme.of(context).textTheme.titleLarge!.copyWith(
                              color: Colors.blue,
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                      const SizedBox(),
                    ],
                  ),
                  const SizedBox(height: 24),
                  SizedBox(
                    width: 150,
                    height: 40,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey[200],
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                      ),
                      onPressed: () async {
                        TimeOfDay? time = await showTimePicker(
                          context: ctx,
                          initialTime: selectedTime,
                        );
                        if (time != null) {
                          setState(() => selectedTime = time);
                        }
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            selectedTime.format(context),
                            style: Theme.of(context)
                                .textTheme
                                .bodySmall!
                                .copyWith(color: Colors.grey),
                          ),
                          const Icon(Icons.access_time,
                              color: Colors.grey, size: 18),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  _buildDayCheckboxes(ctx, selectedDays, (i, v) {
                    setState(() => selectedDays[i] = v);
                  }),
                  const SizedBox(height: 16),
                  _buildFunctionSwitch(deviceType, ctx, functionOn!, (v) {
                    setState(() => functionOn = v);
                  }),
                ],
              ),
              actions: [
                SizedBox(
                  width: 100,
                  child: OutlinedButton(
                    onPressed: () {
                      Navigator.pop(ctx, null);
                    },
                    child: const Text('Cancel'),
                  ),
                ),
                SizedBox(
                    width: 100,
                    child: ElevatedButton(
                      onPressed: () {
                        dynamic temp;
                        if (deviceType == 'CUR_2') {
                          temp = functionOn! ? 'open' : 'close';
                        } else {
                          temp = functionOn;
                        }
                        final entry = ScheduleEntry(
                          category: schedule?.category ?? 'switch_1',
                          time: _formatTimeOfDayToISO(selectedTime),
                          function: Status(
                            code: code ?? 'switch_1',
                            value: temp,
                          ),
                          days: _convertSelectedDaysToStrings(selectedDays),
                          scheduleId: schedule.scheduleId,
                        );
                        Navigator.pop(ctx, entry);
                      },
                      child: const Text('Save'),
                    )),
              ],
            );
          },
        );
      },
    );
  }

  static TimeOfDay _convertStringToTimeOfDay(String iso) {
    final dt = DateTime.tryParse(iso);
    if (dt != null) return TimeOfDay(hour: dt.hour, minute: dt.minute);
    return const TimeOfDay(hour: 9, minute: 0);
  }

  static List<bool> _convertDaysStringToBooleans(List<String> selectedDays) {
    final daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    return daysOfWeek
        .map((d) =>
            selectedDays.map((e) => e.toLowerCase()).contains(d.toLowerCase()))
        .toList();
  }

  static String _formatTimeOfDayToISO(TimeOfDay t) {
    final now = DateTime.now();
    final dt = DateTime(now.year, now.month, now.day, t.hour, t.minute);
    return dt.toIso8601String();
  }

  static List<String> _convertSelectedDaysToStrings(List<bool> selectedDays) {
    const allDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    List<String> result = [];
    for (int i = 0; i < selectedDays.length; i++) {
      if (selectedDays[i]) result.add(allDays[i]);
    }
    return result;
  }

  static Widget _buildDayCheckboxes(BuildContext ctx, List<bool> selectedDays,
      Function(int, bool) onChanged) {
    final dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: List.generate(
        7,
        (index) => Row(
          children: [
            Checkbox(
              value: selectedDays[index],
              onChanged: (val) => onChanged(index, val!),
            ),
            Text(dayLabels[index]),
          ],
        ),
      ),
    );
  }

  static Widget _buildFunctionSwitch(
      String categor, BuildContext ctx, bool isOn, Function(bool) onChanged) {
    return Row(
      children: [
        Text(
          'Function:',
          style:
              Theme.of(ctx).textTheme.bodySmall!.copyWith(color: Colors.grey),
        ),
        const SizedBox(width: 10),
        Radio<bool>(
          value: true,
          groupValue: isOn,
          onChanged: (val) => onChanged(true),
        ),
        Text(categor == 'CUR_2' ? 'open' : 'On'),
        const SizedBox(width: 10),
        Radio<bool>(
          value: false,
          groupValue: isOn,
          onChanged: (val) => onChanged(false),
        ),
        Text(categor == 'CUR_2' ? 'close' : 'Off'),
      ],
    );
  }
}
