import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:medora/data/models/doctor.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medora/data/models/consultation_booking.dart';
import 'package:medora/data/services/doctor_profile_service.dart';

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

  @override
  State<DoctorDashboardHomeScreen> createState() =>
      _DoctorDashboardHomeScreenState();
}

class _DoctorDashboardHomeScreenState extends State<DoctorDashboardHomeScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  Doctor? _doctorProfile;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    _animationController.forward();
    _fetchDoctorProfile();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
    _fetchDoctorProfile();
  }

  Future<void> _fetchDoctorProfile() async {
    final doctorProfile = await DoctorProfileService.getDoctorProfile();
    if (mounted) {
      setState(() {
        _doctorProfile = doctorProfile;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            _buildSearchBar(),
            Expanded(
              child: ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  _buildRealTimeCard(),
                  const SizedBox(height: 20),
                  _buildUpcomingBookings(),
                  const SizedBox(
                    height: 20,
                  ),
                  // _buildCompletedConsultations()
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.blue[400]!,
            Colors.blue[300]!,
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(30.0),
          bottomRight: Radius.circular(30.0),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(30),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: TextField(
              decoration: InputDecoration(
                hintText: 'Search Patients',
                hintStyle: GoogleFonts.poppins(
                  color: Colors.grey[400],
                ),
                prefixIcon: const Icon(Icons.search, color: Colors.blue),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(30),
                  borderSide: BorderSide.none,
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 20),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRealTimeCard() {
    return Container(
      padding: const EdgeInsets.all(15), // Reduced padding
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue[400]!, Colors.white],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Instant patient insights\nright at your fingertips',
            style: GoogleFonts.poppins(
              fontSize: 24, // Reduced font size
              fontWeight: FontWeight.bold,
              color: const Color.fromARGB(221, 67, 67, 67),
            ),
          ),
          const SizedBox(height: 8), // Reduced spacing
          // ElevatedButton(
          //   onPressed: () {
          //     // Navigator.push(
          //     //   context,
          //     //   MaterialPageRoute(
          //     //       builder: (context) => const SpecialtyScreen()),
          //     // );
          //   },
          //   // style: ElevatedButton.styleFrom(
          //   //   backgroundColor: Colors.white,
          //   //   foregroundColor: Colors.blue[700],
          //   //   padding: const EdgeInsets.symmetric(
          //   //       horizontal: 12, vertical: 5), // Reduced padding
          //   //   shape: RoundedRectangleBorder(
          //   //     borderRadius: BorderRadius.circular(30),
          //   //   ),
          //   //   elevation: 5,
          //   // ),
          //   // child: Text(
          //   //   'Start Consultation',
          //   //   style: GoogleFonts.poppins(
          //   //     fontWeight: FontWeight.bold,
          //   //     fontSize: 14, // Reduced font size
          //   //   ),
          //   // ),
          // ),
        ],
      ),
    );
  }

  Widget _buildUpcomingBookings() {
    return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection('bookings')
          .where('doctorId', isEqualTo: _doctorProfile?.uid!)
          .orderBy('appointmentDate', descending: true)
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return const Center(child: Text('Error loading bookings'));
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        final bookings = snapshot.data!.docs
            .map((doc) => Booking.fromMap(doc.data()))
            .toList();

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(
                'Upcoming Bookings',
                style: GoogleFonts.poppins(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey[800],
                ),
              ),
            ),
            const SizedBox(height: 12),
            if (bookings.isNotEmpty)
              SizedBox(
                height: 220, // Adjust height as needed
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  itemCount: bookings.length,
                  itemBuilder: (context, index) {
                    final booking = bookings[index];
                    return Padding(
                      padding: const EdgeInsets.only(right: 16),
                      child: _consultationCard(
                        booking.patientName,
                        '${DateFormat('EEE, MMM d, yyyy').format(booking.appointmentDate)}\n${booking.appointmentTime}',
                        booking.paymentStatus,
                      ),
                    );
                  },
                ),
              ),
            if (bookings.isEmpty)
              Center(
                child: Text(
                  'No upcoming bookings',
                  style: GoogleFonts.poppins(
                    fontSize: 16,
                    color: Colors.grey[600],
                  ),
                ),
              ),
          ],
        );
      },
    );
  }

  IconData _getStatusIcon(PaymentStatus status) {
    switch (status) {
      case PaymentStatus.completed:
        return Icons.check_circle;
      case PaymentStatus.pending:
        return Icons.access_time;
      case PaymentStatus.failed:
        return Icons.error;
      default:
        return Icons.info;
    }
  }

  Color _getStatusColor(PaymentStatus status) {
    switch (status) {
      case PaymentStatus.pending:
        return Colors.orange;
      case PaymentStatus.completed:
        return Colors.green;
      case PaymentStatus.failed:
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(PaymentStatus status) {
    switch (status) {
      case PaymentStatus.pending:
        return 'Payment Pending';
      case PaymentStatus.completed:
        return 'Confirmed';
      case PaymentStatus.failed:
        return 'Payment Failed';
      default:
        return 'Unknown';
    }
  }

  Widget _consultationCard(
    String name,
    String schedule,
    PaymentStatus paymentStatus,
  ) {
    return Container(
      width: 300,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.white, Colors.grey[50]!],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 64,
                height: 64,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Colors.blue[400]!, Colors.blue[600]!],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.blue[300]!.withOpacity(0.3),
                      blurRadius: 12,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.person,
                  size: 36,
                  color: Colors.white,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      name,
                      style: GoogleFonts.poppins(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.grey[800],
                      ),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: _getStatusColor(paymentStatus).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                          color:
                              _getStatusColor(paymentStatus).withOpacity(0.2),
                        ),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            _getStatusIcon(paymentStatus),
                            size: 14,
                            color: _getStatusColor(paymentStatus),
                          ),
                          const SizedBox(width: 4),
                          Text(
                            _getStatusText(paymentStatus),
                            style: GoogleFonts.poppins(
                              fontSize: 12,
                              color: _getStatusColor(paymentStatus),
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: Colors.blue[50],
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: Colors.blue[100]!,
              ),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.calendar_today,
                  size: 18,
                  color: Colors.blue[700],
                ),
                const SizedBox(width: 8),
                Text(
                  schedule,
                  style: GoogleFonts.poppins(
                    color: Colors.blue[700],
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
