import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:intl/intl.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/components/drawer_professional.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/models/event_model.dart';
import 'package:prosappco/src/models/scores_model.dart';
import 'package:prosappco/src/screens/cita.dart';

class MyServicesScreen extends StatefulWidget {
  MyServicesScreen({super.key});

  @override
  State<MyServicesScreen> createState() => _MyServicesScreenState();
}

class _MyServicesScreenState extends State<MyServicesScreen> {
  DateTime today = DateTime.now();
  final uid = AuthenticationRepository.instance.getCurrentUserUid();

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

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: PopAppbar(
            onPressed: () {
              Navigator.pop(context);
            },
            label: 'Mis servicios'),
        drawer: DrawerProfessional(),
        body: SingleChildScrollView(
          child: Column(
            children: [
              _eventList(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _eventList() {
    return StreamBuilder<List<Event>>(
      stream: FirebaseFirestore.instance
          .collection('services')
          .where('user_id', isEqualTo: uid)
          .where('status', whereIn: [
            'aprobado',
            'denegado',
            'iniciado',
            'terminado',
            'pendiente'
          ])
          .snapshots()
          .asyncMap((snapshot) async {
            try {
              List<Event> eventos = [];
              for (var element in snapshot.docs) {
                final event = Event.fromJson(element.data());
                event.scoresModel =
                    await ScoresModel.scoreTo(event.userId, false, false);
                event.id = element.id;
                eventos.add(event);
              }
              return eventos;
            } catch (e) {
              print('Error getByProId $e');
              return [];
            }
          }),
      builder: (BuildContext context, AsyncSnapshot<List<Event>> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        List<Event> eventos = [];

        try {
          eventos.addAll(snapshot.data!);
        } catch (e) {
          print("Error" + e.toString());
        }

        if (eventos.isEmpty) {
          return const Padding(
            padding: EdgeInsets.symmetric(vertical: 50),
            child: Center(child: Text('No tienes citas')),
          );
        }

        return Column(
          children: [
            ...eventos.map(
              (event) => ListTile(
                tileColor: event.status == 'denegado'
                    ? Colors.red[100]
                    : Colors.blue[100],
                onTap: () {
                  Navigator.push(
                    context,
                    CupertinoPageRoute(
                      builder: (BuildContext context) {
                        return CitaScreen(evento: event);
                      },
                    ),
                  );
                },
                leading: event.status == 'aprobado'
                    ? const Icon(
                        Icons.check,
                        color: Colors.blue,
                        size: 40,
                      )
                    : event.status == 'iniciado'
                        ? const Icon(
                            Icons.access_time,
                            color: Colors.blue,
                            size: 40,
                          )
                        : event.status == 'pendiente'
                            ? const Icon(
                                Icons.access_time_outlined,
                                color: Colors.blue,
                                size: 40,
                              )
                            : event.status == 'terminado'
                                ? const Icon(
                                    Icons.rocket_launch,
                                    color: Colors.blue,
                                    size: 40,
                                  )
                                : const Icon(
                                    Icons.close,
                                    color: Colors.red,
                                    size: 40,
                                  ),
                title: RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: '${event.title}, ',
                        style: const TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                      TextSpan(
                        text:
                            '${DateFormat('dd MMM', 'es').format(DateTime.parse(event.day))} - ${TimeOfDay.fromDateTime(DateTime.parse(event.range1Hour1)).format(context)}',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16,
                        ),
                      ),
                    ],
                  ),
                ),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        RatingBar.builder(
                          initialRating: event.scoresModel?.average ?? 0,
                          minRating: 1,
                          direction: Axis.horizontal,
                          allowHalfRating: true,
                          itemCount: 5,
                          itemSize: 25,
                          maxRating: 5,
                          itemPadding:
                              const EdgeInsets.symmetric(horizontal: 0),
                          itemBuilder: (context, _) => const Icon(
                            Icons.star,
                            color: Color(0xFF2BA4EC),
                          ),
                          onRatingUpdate: (rating) {},
                          ignoreGestures: true,
                        ),
                        const SizedBox(width: 5),
                        Text(
                            '(${event.scoresModel?.total.toString()}) ${event.scoresModel?.average.toStringAsFixed(1)}'),
                      ],
                    ),
                    Text(
                      '" ${event.description}"',
                      style: const TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ],
                ),
                trailing: const Icon(Icons.keyboard_arrow_right),
              ),
            ),
          ],
        );
      },
    );
  }
}
