import 'package:flutter/material.dart';
import 'package:medora/controllers/consultation_center_controller.dart';
import 'package:medora/data/models/consultation_center.dart';

class ConsultationTimeSlotScreen extends StatefulWidget {
  final ConsultationCenterController controller;
  final String selectedDay;

  const ConsultationTimeSlotScreen({
    super.key,
    required this.controller,
    required this.selectedDay,
  });

  @override
  State<ConsultationTimeSlotScreen> createState() =>
      _ConsultationTimeSlotScreenState();
}

class _ConsultationTimeSlotScreenState
    extends State<ConsultationTimeSlotScreen> {
  late AvailabilitySchedule currentSchedule;

  @override
  void initState() {
    super.initState();
    _initializeSchedule();
  }

  void _initializeSchedule() {
    // Ensure weeklySchedule is not null and initialize it if needed
    widget.controller.model.weeklySchedule ??= [];

    // Find the schedule for the selected day, or create a new one
    currentSchedule = widget.controller.model.weeklySchedule!.firstWhere(
      (schedule) => schedule.day == widget.selectedDay,
      orElse: () {
        final newSchedule = AvailabilitySchedule(
          day: widget.selectedDay,
          timeSlots: [],
        );
        widget.controller.model.weeklySchedule!.add(newSchedule);
        return newSchedule;
      },
    );
    currentSchedule.timeSlots ??= [];
    print(
        'Initial schedule for ${widget.selectedDay}: ${currentSchedule.timeSlots}');
  }

  String formatTime(TimeOfDay time) {
    final hour = time.hourOfPeriod == 0 ? 12 : time.hourOfPeriod;
    final minute = time.minute.toString().padLeft(2, '0');
    final period = time.period == DayPeriod.am ? 'AM' : 'PM';
    return '$hour:$minute $period';
  }

  void _validateTimeSlot(TimeOfDay startTime, TimeOfDay endTime) {
    int startMins = startTime.hour * 60 + startTime.minute;
    int endMins = endTime.hour * 60 + endTime.minute;
    int duration = endMins - startMins;
    int minimumDuration =
        int.parse(widget.controller.model.averageDurationMinutes ?? '0');
    if (duration < minimumDuration) {
      throw 'Time slot must be atleast $minimumDuration minutes long';
    }
  }

  void _validateOverlap(TimeOfDay startTime, TimeOfDay endTime,
      [TimeSlot? excludeSlot]) {
    int newStartMins = startTime.hour * 60 + startTime.minute;
    int newEndMins = endTime.hour * 60 + endTime.minute;
    for (var slot in currentSchedule.timeSlots ?? []) {
      if (excludeSlot != null &&
          slot.startTime == excludeSlot.startTime &&
          slot.endTime == excludeSlot.endTime) {
        continue;
      }
      var existingStart = slot.startTime!.split(' ');
      var existingEnd = slot.endTime!.split(' ');
      var startHourMin = existingStart[0].split(':');
      var endHourMin = existingEnd[0].split(':');
      int startHour = int.parse(startHourMin[0]);
      if (existingStart[1] == 'PM' && startHour != 12) startHour += 12;
      if (existingStart[1] == 'AM' && startHour == 12) startHour = 0;
      int endHour = int.parse(endHourMin[0]);
      if (existingEnd[1] == 'PM' && endHour != 12) endHour += 12;
      if (existingEnd[1] == 'AM' && endHour == 12) endHour = 0;
      int existingStartMins = startHour * 60 + int.parse(startHourMin[1]);
      int existingEndMins = endHour * 60 + int.parse(endHourMin[1]);
      if ((newStartMins >= existingStartMins &&
              newStartMins < existingEndMins) ||
          (newEndMins > existingStartMins && newEndMins <= existingEndMins) ||
          (newStartMins <= existingStartMins &&
              newEndMins >= existingEndMins)) {
        throw 'This time slot overlaps with an existing slot';
        // throw 'This time slot overlaps with existing slot ${slot.startTime} - ${slot.endTime}';
      }
    }
  }

  void _addTimeSlot() {
    TimeOfDay? startTime;
    TimeOfDay? endTime;
    showModalBottomSheet(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setModalState) => Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Expanded(
                    child: _buildTimeField(
                      context: context,
                      label: 'Start Time',
                      time: startTime,
                      onSelect: (time) => setModalState(() => startTime = time),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _buildTimeField(
                      context: context,
                      label: 'End Time',
                      time: endTime,
                      onSelect: (time) => setModalState(() => endTime = time),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  if (startTime != null && endTime != null) {
                    try {
                      _validateTimeSlot(startTime!, endTime!);
                      _validateOverlap(startTime!, endTime!);
                      final slot = TimeSlot(
                        startTime: formatTime(startTime!),
                        endTime: formatTime(endTime!),
                      );
                      widget.controller.addTimeSlot(widget.selectedDay, slot);
                      Navigator.pop(context);
                      setState(() {
                        currentSchedule =
                            widget.controller.model.weeklySchedule!.firstWhere(
                          (schedule) => schedule.day == widget.selectedDay,
                          orElse: () => AvailabilitySchedule(
                            day: widget.selectedDay,
                            timeSlots: [],
                          ),
                        );
                      });
                    } catch (e) {
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text(e.toString()),
                          backgroundColor: Colors.red,
                        ),
                      );
                    }
                  }
                },
                child: const Text('Add Time Slot'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTimeField({
    required BuildContext context,
    required String label,
    required TimeOfDay? time,
    required Function(TimeOfDay) onSelect,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label),
        const SizedBox(height: 8),
        InkWell(
          onTap: () async {
            final selected = await showTimePicker(
              context: context,
              initialTime: time ?? TimeOfDay.now(),
            );
            if (selected != null) onSelect(selected);
          },
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey.shade300),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  time != null ? formatTime(time) : 'Select',
                ),
                const Icon(Icons.access_time),
              ],
            ),
          ),
        ),
      ],
    );
  }

  void _editTimeSlot(TimeSlot currentSlot) async {
    try {
      final currentStart = currentSlot.startTime!.split(' ');
      currentSlot.endTime!.split(' ');

      final startTime = TimeOfDay(
        hour: int.parse(currentStart[0].split(':')[0]),
        minute: int.parse(currentStart[0].split(':')[1]),
      );

      TimeOfDay? newStartTime = await showTimePicker(
        context: context,
        initialTime: startTime,
      );

      if (newStartTime != null) {
        TimeOfDay? newEndTime = await showTimePicker(
          context: context,
          initialTime: newStartTime,
        );

        if (newEndTime != null && mounted) {
          _validateTimeSlot(newStartTime, newEndTime);
          _validateOverlap(newStartTime, newEndTime, currentSlot);
          setState(() {
            widget.controller.removeTimeSlot(widget.selectedDay, currentSlot);

            final newSlot = TimeSlot(
              startTime: formatTime(newStartTime),
              endTime: formatTime(newEndTime),
            );
            widget.controller.addTimeSlot(widget.selectedDay, newSlot);

            currentSchedule =
                widget.controller.model.weeklySchedule!.firstWhere(
              (schedule) => schedule.day == widget.selectedDay,
              orElse: () => AvailabilitySchedule(
                day: widget.selectedDay,
                timeSlots: [],
              ),
            );
          });
        }
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(e.toString()),
        backgroundColor: Colors.red,
      ));
    }
  }

  void _deleteTimeSlot(TimeSlot slot) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Time Slot'),
        content: const Text('Are you sure you want to delete this time slot?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                widget.controller.removeTimeSlot(widget.selectedDay, slot);
                // Update local schedule
                currentSchedule =
                    widget.controller.model.weeklySchedule!.firstWhere(
                  (schedule) => schedule.day == widget.selectedDay,
                  orElse: () => AvailabilitySchedule(
                    day: widget.selectedDay,
                    timeSlots: [],
                  ),
                );
              });
              Navigator.pop(context);

              // Debug print
              print('Deleted time slot: $slot');
              print('Updated schedule: ${currentSchedule.timeSlots}');
            },
            child: const Text(
              'Delete',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          backgroundColor: Colors.grey[50],
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.white,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios, size: 20),
              color: Colors.black54,
              onPressed: () => Navigator.pop(context),
            ),
            title: Text(
              '${widget.selectedDay} Schedule',
              style: const TextStyle(
                color: Colors.black87,
                fontSize: 20,
                fontWeight: FontWeight.w600,
              ),
            ),
            centerTitle: true,
            actions: [
              IconButton(
                onPressed: () {
                  Navigator.of(context)
                      .pop(true); // Pop with true to indicate changes
                },
                icon: const Icon(
                  Icons.check,
                  color: Color(0xFF4FB6D8),
                ),
              ),
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Text(
                    'Time Slots',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    height: MediaQuery.of(context).size.height * 0.2,
                    margin: const EdgeInsets.only(bottom: 250),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(25),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.08),
                          spreadRadius: 5,
                          blurRadius: 15,
                          offset: const Offset(0, 3),
                        ),
                      ],
                    ),
                    padding: const EdgeInsets.all(16),
                    child: (currentSchedule.timeSlots == null ||
                            currentSchedule.timeSlots!.isEmpty)
                        ? Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.access_time,
                                  size: 48,
                                  color: Colors.grey[400],
                                ),
                                const SizedBox(height: 16),
                                Text(
                                  'No time slots added yet',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.grey[600],
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  'Tap + to add your first time slot',
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.grey[400],
                                  ),
                                ),
                              ],
                            ),
                          )
                        : ListView.separated(
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            itemCount: currentSchedule.timeSlots!.length,
                            separatorBuilder: (context, index) =>
                                const Divider(height: 1),
                            itemBuilder: (context, index) {
                              final slot = currentSchedule.timeSlots![index];
                              return Container(
                                padding:
                                    const EdgeInsets.symmetric(vertical: 8),
                                child: ListTile(
                                  leading: Container(
                                    padding: const EdgeInsets.all(8),
                                    decoration: BoxDecoration(
                                      color: Colors.blue.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child: const Icon(
                                      Icons.access_time,
                                      color: Colors.blue,
                                      size: 24,
                                    ),
                                  ),
                                  title: Text(
                                    '${slot.startTime} - ${slot.endTime}',
                                    style: const TextStyle(
                                      fontSize: 13.5,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  trailing: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      IconButton(
                                        icon: const Icon(
                                          Icons.edit_outlined,
                                          size: 26,
                                          color: Colors.blue,
                                        ),
                                        onPressed: () => _editTimeSlot(slot),
                                      ),
                                      IconButton(
                                        icon: const Icon(
                                          Icons.delete_outline,
                                          size: 26,
                                          color: Colors.red,
                                        ),
                                        onPressed: () => _deleteTimeSlot(slot),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                  ),
                ),
              ],
            ),
          ),
        ),
        Positioned(
          bottom: 280,
          right: 29,
          child: FloatingActionButton(
            onPressed: _addTimeSlot,
            backgroundColor: const Color(0xFF4FB6D8),
            elevation: 2,
            child: const Icon(
              Icons.add,
              size: 28,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }
}
