import 'package:flutter/material.dart';
import 'package:medora/controllers/consultation_center_controller.dart';
import 'package:medora/data/models/consultation_center.dart';
import 'package:medora/data/services/consultation_center_service.dart';
import 'package:medora/route/route_names.dart';
import 'package:medora/screens/doctor_screen/doctor_consultation_schedule/consultation_time_slot_screen.dart';

class ConsultationDayScreen extends StatefulWidget {
  final ConsultationCenterController controller;

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

  @override
  State<ConsultationDayScreen> createState() => _ConsultationDayScreenState();
}

class _ConsultationDayScreenState extends State<ConsultationDayScreen> {
  final _formKey = GlobalKey<FormState>();
  final List<String> weekDays = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday',
  ];

  Future<void> _showTimeSlotDialog(String day) async {
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ConsultationTimeSlotScreen(
          controller: widget.controller,
          selectedDay: day,
        ),
      ),
    );
    // Force rebuild after returning from TimeSlotScreen
    if (mounted) {
      setState(() {});
    }
  }

  Future<void> _saveCenter() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    try {
      final List<ConsultationCenterController> controllers = [
        widget.controller
      ];
      bool success =
          await ConsultationCenterService.saveConsultationCenters(controllers);

      if (success) {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Doctor consultation saved successfully!'),
            backgroundColor: Colors.green,
          ),
        );
        Navigator.of(context)
            .pushReplacementNamed(RouteNames.scheduleConsultationScreen);
      } else {
        _showError('Failed to save consultation center. Please try again.');
      }
    } catch (e) {
      _showError('An error occurred while saving. Please try again.');
      print('Error saving consultation center: $e');
    }
  }

  void _showError(String message) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return 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: const Text(
          'Week Days',
          style: TextStyle(
            color: Colors.black87,
            fontSize: 20,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: _saveCenter,
            icon: const Icon(
              Icons.check,
            ),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(15),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.08),
                        spreadRadius: 5,
                        blurRadius: 15,
                        offset: const Offset(0, 3),
                      ),
                    ],
                  ),
                  padding:
                      const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
                  child: Column(
                    children: [
                      Expanded(
                        child: ListView.separated(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          itemCount: weekDays.length,
                          separatorBuilder: (context, index) =>
                              const SizedBox(height: 12),
                          itemBuilder: (context, index) {
                            final day = weekDays[index];
                            final schedule = widget
                                .controller.model.weeklySchedule
                                ?.firstWhere(
                              (schedule) => schedule.day == day,
                              orElse: () => AvailabilitySchedule(
                                day: day,
                                timeSlots: [],
                              ),
                            );

                            return // In the ListView.builder, update the Container decoration:

                                Container(
                              decoration: BoxDecoration(
                                color: schedule?.timeSlots?.isNotEmpty == true
                                    ? const Color(0xFF4FB6D8).withOpacity(
                                        0.1) // Light blue for days with slots
                                    : Colors.grey[
                                        100], // Original color for days without slots
                                borderRadius: BorderRadius.circular(30),
                              ),
                              child: ListTile(
                                contentPadding: const EdgeInsets.symmetric(
                                  horizontal: 24,
                                  vertical: 8,
                                ),
                                title: Text(
                                  day,
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                    color: schedule?.timeSlots?.isNotEmpty ==
                                            true
                                        ? const Color(
                                            0xFF4FB6D8) // Blue text for days with slots
                                        : Colors
                                            .black87, // Original color for days without slots
                                  ),
                                ),
                                // subtitle: schedule?.timeSlots?.isNotEmpty ==
                                //         true
                                //     ? Padding(
                                //         padding: const EdgeInsets.only(top: 4),
                                //         child: Column(
                                //           crossAxisAlignment:
                                //               CrossAxisAlignment.start,
                                //           children: schedule!.timeSlots!
                                //               .map(
                                //                 (slot) => Padding(
                                //                   padding:
                                //                       const EdgeInsets.only(
                                //                           top: 2),
                                //                   // child: Text(
                                //                   //   '${slot.startTime} - ${slot.endTime}',
                                //                   //   style: const TextStyle(
                                //                   //     fontSize: 13,
                                //                   //     color: Colors.black54,
                                //                   //   ),
                                //                   // ),
                                //                 ),
                                //               )
                                //               .toList(),
                                //         ),
                                //       )
                                //     : null,
                                trailing: Container(
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(50),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.grey.withOpacity(0.1),
                                        spreadRadius: 1,
                                        blurRadius: 3,
                                        offset: const Offset(0, 1),
                                      ),
                                    ],
                                  ),
                                  child: IconButton(
                                    icon: Icon(
                                      Icons.edit_outlined,
                                      size: 20,
                                      color: schedule?.timeSlots?.isNotEmpty ==
                                              true
                                          ? const Color(
                                              0xFF4FB6D8) // Blue icon for days with slots
                                          : Colors
                                              .black54, // Original color for days without slots
                                    ),
                                    onPressed: () => _showTimeSlotDialog(day),
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // const SizedBox(height: 24),
              // SizedBox(
              //   width: MediaQuery.of(context).size.width * 0.5,
              //   height: 50,
              //   child: ElevatedButton(
              //     onPressed: _saveCenter,
              //     style: ElevatedButton.styleFrom(
              //       backgroundColor: const Color(0xFF4FB6D8),
              //       elevation: 0,
              //       shape: RoundedRectangleBorder(
              //         borderRadius: BorderRadius.circular(25),
              //       ),
              //     ),
              //     child: const Text(
              //       'SAVE',
              //       style: TextStyle(
              //           fontSize: 16,
              //           fontWeight: FontWeight.w600,
              //           letterSpacing: 1,
              //           color: Colors.white),
              //     ),
              //   ),
              // ),
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
    );
  }
}
