import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medora/data/models/doctor.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 ConsultationsCenterScreen extends StatefulWidget {
  final Doctor doctor;

  const ConsultationsCenterScreen({
    super.key,
    required this.doctor,
  });

  @override
  State<ConsultationsCenterScreen> createState() =>
      _ConsultationsCenterScreenState();
}

class _ConsultationsCenterScreenState extends State<ConsultationsCenterScreen> {
  List<ConsultationCenter> _consultationCenters = [];
  bool _isLoading = true;
  String? _error;

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

  Future<void> _fetchDoctorConsultationCenters() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      if (widget.doctor.uid == null) {
        throw Exception('Doctor UID is missing');
      }

      final centers =
          await ConsultationCenterService.getDoctorConsultationCenters(
        widget.doctor.uid!,
      );

      if (mounted) {
        setState(() {
          _consultationCenters = centers;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _error = e.toString();
          _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 && center.floorBuilding!.isNotEmpty) {
      addressParts.add(center.floorBuilding!);
    }
    if (center.street != null && center.street!.isNotEmpty) {
      addressParts.add(center.street!);
    }
    if (center.city != null && center.city!.isNotEmpty) {
      addressParts.add(center.city!);
    }

    return addressParts.join(', ');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FF),
      appBar: _buildAppBar(),
      body: RefreshIndicator(
        onRefresh: _fetchDoctorConsultationCenters,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildDoctorInfo(),
                const SizedBox(height: 24),
                _buildConsultationLocations(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.black87),
        onPressed: () => Navigator.pop(context),
      ),
      title: Text(
        'Select Location',
        style: GoogleFonts.poppins(
          color: Colors.black87,
          fontWeight: FontWeight.w600,
          fontSize: 20,
        ),
      ),
      centerTitle: true,
    );
  }

  Widget _buildDoctorInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: Image.network(
              widget.doctor.profileImageUrl!,
              width: 80,
              height: 80,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  width: 80,
                  height: 80,
                  color: Colors.grey[300],
                  child: Icon(Icons.person, size: 40, color: Colors.grey[600]),
                );
              },
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.doctor.firstName ?? "",
                  style: GoogleFonts.poppins(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                Text(
                  widget.doctor.speciality!,
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                Text(
                  '${widget.doctor.yearsOfExperience} years experience',
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildConsultationLocations() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Select Location',
          style: GoogleFonts.poppins(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
        const SizedBox(height: 12),
        if (_isLoading)
          const Center(child: CircularProgressIndicator())
        else if (_error != null)
          Center(
            child: Column(
              children: [
                Text(
                  'Error loading centers',
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: Colors.red,
                  ),
                ),
                TextButton(
                  onPressed: _fetchDoctorConsultationCenters,
                  child: const Text('Retry'),
                ),
              ],
            ),
          )
        else if (_consultationCenters.isEmpty)
          Center(
            child: Text(
              'No consultation centers available',
              style: GoogleFonts.poppins(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          )
        else
          SizedBox(
            height: 120,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _consultationCenters.length,
              itemBuilder: (context, index) {
                final center = _consultationCenters[index];

                return GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(
                      context,
                      RouteNames.consultationTimeScreen,
                      arguments: {
                        'doctor': widget.doctor,
                        'selectedConsultation': center,
                      },
                    );
                  },
                  child: Container(
                    width: 200,
                    margin: const EdgeInsets.only(right: 16),
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.1),
                          blurRadius: 10,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _formatAddress(center),
                          style: GoogleFonts.poppins(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                            color: Colors.black87,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const Spacer(),
                        if (center.averageDurationMinutes != null)
                          Text(
                            'Average time: ${center.averageDurationMinutes} mins',
                            style: GoogleFonts.poppins(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                        if (center.consultationFee != null)
                          Text(
                            'Fee: ${center.consultationFee}',
                            style: GoogleFonts.poppins(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
      ],
    );
  }
}
