import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medora/common/custom_style.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';

class ScheduleConsultationScreen extends StatefulWidget {
  const ScheduleConsultationScreen({super.key});

  @override
  ScheduleConsultationScreenState createState() =>
      ScheduleConsultationScreenState();
}

class ScheduleConsultationScreenState
    extends State<ScheduleConsultationScreen> {
  List<ConsultationCenter> _consultationCenters = [];
  bool _isLoading = true;
  bool _isOnlineConsultationSelected = false;

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

  Future<void> _fetchConsultationCenters() async {
    try {
      final User? user = FirebaseAuth.instance.currentUser;
      final String uid = user!.uid;
      final consultationCenters =
          await ConsultationCenterService.getDoctorConsultationCenters(uid);
      setState(() {
        _consultationCenters = consultationCenters;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to load consultation centers: $e')),
      );
    }
  }

  String _formatAddress(ConsultationCenter center) {
    List<String> addressParts = [];
    if (center.floorBuilding != null) addressParts.add(center.floorBuilding!);
    if (center.city != null) addressParts.add(center.city!);
    return addressParts.join(', ');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => Navigator.pushReplacementNamed(
              context, RouteNames.doctorDashbordScreen),
        ),
        title: Text(
          'Consultation Centers',
          style: GoogleFonts.poppins(
            fontWeight: FontWeight.w600,
          ),
        ),
        elevation: CustomStyles.defaultAppBarElevation,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(CustomStyles.pagePadding),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Online Consultation Button
            Card(
              elevation: 4,
              shadowColor:
                  Theme.of(context).colorScheme.primary.withOpacity(0.2),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(
                  color: Theme.of(context).colorScheme.outline.withOpacity(0.1),
                ),
              ),
              child: ListTile(
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
                leading: Container(
                  width: 36,
                  height: 40,
                  decoration: BoxDecoration(
                    color:
                        Theme.of(context).colorScheme.primary.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Icon(
                    Icons.video_call_rounded,
                    color: Colors.blue,
                    size: 24,
                  ),
                ),
                title: Text(
                  'Online Consultation',
                  style: GoogleFonts.poppins(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
                ),
                trailing: SizedBox(
                  width: 80, // Increased width to accommodate contents
                  child: Row(
                    mainAxisSize:
                        MainAxisSize.min, // Added this to prevent overflow
                    children: [
                      SizedBox(
                        width: 24,
                        height: 24,
                        child: Checkbox(
                          value: _isOnlineConsultationSelected,
                          onChanged: (bool? value) {
                            setState(() {
                              _isOnlineConsultationSelected = value ?? false;
                            });
                          },
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(4),
                          ),
                          materialTapTargetSize:
                              MaterialTapTargetSize.shrinkWrap,
                          checkColor: Colors.blue,
                          activeColor: Colors.white,
                        ),
                      ),
                      const SizedBox(width: 8),
                      IconButton(
                        padding:
                            EdgeInsets.zero, // Added to reduce button padding
                        constraints:
                            const BoxConstraints(), // Removed constraints
                        icon: Icon(
                          Icons.calendar_month_rounded,
                          color: _isOnlineConsultationSelected
                              ? Colors.blue
                              : Theme.of(context)
                                  .colorScheme
                                  .onSurface
                                  .withOpacity(0.4),
                        ),
                        iconSize: 20,
                        onPressed: () {
                          // Navigator.pushNamed(
                          //   context,
                          //   RouteNames.ConsultationDayScreen,
                          // );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 24),

            // Consultation Centers Section
            Text(
              'Consultation Centers',
              style: GoogleFonts.poppins(
                fontSize: 20,
                fontWeight: FontWeight.w600,
                color: Theme.of(context).colorScheme.onSurface,
              ),
            ),

            const SizedBox(height: 16),

            // Consultation Centers List
            _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _consultationCenters.isEmpty
                    ? Center(
                        child: Text(
                          'No consultation centers available',
                          style: GoogleFonts.poppins(),
                        ),
                      )
                    : ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: _consultationCenters.length,
                        itemBuilder: (context, index) {
                          final center = _consultationCenters[index];
                          return Padding(
                            padding: const EdgeInsets.only(bottom: 12.0),
                            child: Card(
                              elevation: 4,
                              shadowColor: Theme.of(context)
                                  .colorScheme
                                  .primary
                                  .withOpacity(0.15),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                                side: BorderSide(
                                  color: Theme.of(context)
                                      .colorScheme
                                      .outline
                                      .withOpacity(0.1),
                                ),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.all(12),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Expanded(
                                          child: Text(
                                            _formatAddress(center),
                                            style: GoogleFonts.poppins(
                                              fontSize: 15,
                                              fontWeight: FontWeight.w600,
                                              color: Theme.of(context)
                                                  .colorScheme
                                                  .onSurface,
                                            ),
                                          ),
                                        ),
                                        Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            IconButton(
                                              constraints: const BoxConstraints(
                                                minWidth: 32,
                                                minHeight: 32,
                                              ),
                                              padding: EdgeInsets.zero,
                                              icon: const Icon(
                                                Icons.edit_rounded,
                                                color: Colors.blue,
                                                size: 18,
                                              ),
                                              onPressed: () {
                                                // Navigator.pushNamed(
                                                //   context,
                                                //   RouteNames
                                                //       .businessCenterScreen,
                                                // );
                                              },
                                            ),
                                            IconButton(
                                              constraints: const BoxConstraints(
                                                minWidth: 32,
                                                minHeight: 32,
                                              ),
                                              padding: EdgeInsets.zero,
                                              icon: const Icon(
                                                Icons.calendar_month_rounded,
                                                color: Colors.blue,
                                                size: 18,
                                              ),
                                              onPressed: () {
                                                // Pass the existing center data to maintain state
                                                // final consultationController =
                                                //     ConsultationCenterController(
                                                //         center);

                                                // Navigator.pushNamed(
                                                //   context,
                                                //   RouteNames
                                                //       .consultationDayScreen,
                                                //   arguments:
                                                //       consultationController,
                                                // );
                                              },
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                    const SizedBox(height: 8),
                                    IntrinsicHeight(
                                      child: Row(
                                        children: [
                                          Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Icon(
                                                Icons.payments_outlined,
                                                size: 16,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .onSurface
                                                    .withOpacity(0.6),
                                              ),
                                              const SizedBox(width: 4),
                                              Text(
                                                'Fee: ${center.consultationFee ?? "N/A"}',
                                                style: GoogleFonts.poppins(
                                                  fontSize: 13,
                                                  color: Theme.of(context)
                                                      .colorScheme
                                                      .onSurface
                                                      .withOpacity(0.6),
                                                ),
                                              ),
                                            ],
                                          ),
                                          Padding(
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 8),
                                            child: VerticalDivider(
                                              color: Theme.of(context)
                                                  .colorScheme
                                                  .onSurface
                                                  .withOpacity(0.2),
                                              thickness: 1,
                                            ),
                                          ),
                                          Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Icon(
                                                Icons.timer_outlined,
                                                size: 16,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .onSurface
                                                    .withOpacity(0.6),
                                              ),
                                              const SizedBox(width: 4),
                                              Text(
                                                '${center.averageDurationMinutes ?? "N/A"} mins',
                                                style: GoogleFonts.poppins(
                                                  fontSize: 13,
                                                  color: Theme.of(context)
                                                      .colorScheme
                                                      .onSurface
                                                      .withOpacity(0.6),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          Navigator.pushNamed(
            context,
            RouteNames.businessCenterScreen,
          );
        },
        hoverColor: Colors.blue,
        backgroundColor: Colors.white,
        icon: const Icon(
          Icons.add,
          color: Colors.blue,
        ),
        label: Text(
          'Add Center',
          style: GoogleFonts.poppins(
              fontWeight: FontWeight.w500, color: Colors.blue),
        ),
      ),
    );
  }
}
