
import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/providers/score_provider.dart';
import 'package:prosapp_web_app/providers/services_provider.dart';
import 'package:prosapp_web_app/providers/sidemenu_provider.dart';
import 'package:prosapp_web_app/router/router.dart';
import 'package:prosapp_web_app/services/navigation_service.dart';
import 'package:prosapp_web_app/ui/cards/white_card.dart';
import 'package:provider/provider.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';

class RatingView extends StatefulWidget {
  final String type;
  final String serviceId;
  final String professionalId;

  const RatingView({
    super.key,
    required this.type,
    required this.serviceId,
    required this.professionalId,
  });

  @override
  State<RatingView> createState() => _RatingViewState();
}

class _RatingViewState extends State<RatingView> {
  double _rating = 1.0;
  TextEditingController commentController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    final servicesProvider =
        Provider.of<ServicesProvider>(context, listen: false);
    final scoreProvider = Provider.of<ScoreProvider>(context);

    if (widget.type == 'user') {
      servicesProvider.getServiceForUser(widget.serviceId);
    }

    if (widget.type == 'professional') {
      servicesProvider.getServiceForProfessional(widget.serviceId);
    }

    return Consumer<ServicesProvider>(
        builder: (context, servicesProvider, child) {
      if (servicesProvider.isLoading) {
        return const Center(child: CircularProgressIndicator());
      }

      final service = servicesProvider.service!.service;
      final user = servicesProvider.service!.user;

      if (widget.type == 'user' && service.professionalScored == true) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          navigateTo(Flurorouter.dashboardRoute);
        });
      }

      if (widget.type == 'professional' && service.userScored == true) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          navigateTo(Flurorouter.dashboardRoute);
        });
      }

      final image = (user.picture == '' || user.picture == null)
          ? const Image(image: AssetImage('no-image.jpg'))
          : FadeInImage.assetNetwork(
              placeholder: 'loader.gif',
              fit: BoxFit.cover,
              image: user.picture!,
            );

      return ListView(
        children: [
          Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 900),
              child: WhiteCard(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: 100,
                              height: 100,
                              child: ClipOval(child: image),
                            ),
                            const SizedBox(height: 16.0),
                            Text(
                              user.name.toUpperCase(),
                              style: const TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(height: 20),
                            const Text(
                              'Califica el servicio',
                              style: TextStyle(
                                  fontSize: 18, fontWeight: FontWeight.w600),
                            ),
                            const SizedBox(height: 10),
                            RatingBar.builder(
                              initialRating: _rating,
                              minRating: 1,
                              direction: Axis.horizontal,
                              allowHalfRating: true,
                              itemCount: 5,
                              itemSize: 35,
                              glow: false,
                              maxRating: 5,
                              itemPadding:
                                  const EdgeInsets.symmetric(horizontal: 5),
                              itemBuilder: (context, _) => const Icon(
                                Icons.star,
                                color: Color(0xFF2BA4EC),
                              ),
                              onRatingUpdate: (rating) {
                                setState(() {
                                  _rating = rating;
                                });
                              },
                              ignoreGestures: false,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 8),
                              child: Text(
                                customMessage(_rating),
                                style: const TextStyle(
                                  fontSize: 17,
                                  color: Color(0xFF2BA4EC),
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 80, vertical: 40),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    'Comentario',
                                    style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w600),
                                  ),
                                  TextFormField(
                                    decoration: const InputDecoration(
                                      labelStyle: TextStyle(
                                        color: Colors.grey,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                    maxLines: null,
                                    maxLength: 500,
                                    keyboardType: TextInputType.multiline,
                                    controller: commentController,
                                  ),
                                ],
                              ),
                            ),
                            ConstrainedBox(
                              constraints: const BoxConstraints(maxWidth: 180),
                              child: ElevatedButton(
                                onPressed: () async {
                                  if (widget.type == 'user') {
                                    final newComment = CommentEntity(
                                      content: commentController.text,
                                      score: _rating,
                                      isFromUser: true,
                                      serviceId: widget.serviceId,
                                      createdAt: DateTime.now().toIso8601String(),
                                      authorId: service.userId,
                                      destinationId: service.professionalId,
                                    );

                                    await scoreProvider.addComment(
                                      newComment,
                                    );

                                    servicesProvider.changeProfessionalScored(
                                        widget.serviceId);
                                  }

                                  if (widget.type == 'professional') {
                                    final newComment = CommentEntity(
                                      content: commentController.text,
                                      score: _rating,
                                      isFromUser: false,
                                      serviceId: widget.serviceId,
                                      createdAt: DateTime.now().toIso8601String(),
                                      authorId: service.professionalId,
                                      destinationId: service.userId,
                                    );

                                    await scoreProvider.addComment(
                                      newComment,
                                    );

                                    servicesProvider
                                        .changeUserScored(widget.serviceId);
                                  }

                                  navigateTo(Flurorouter.dashboardRoute);
                                },
                                style: ButtonStyle(
                                  backgroundColor: WidgetStateProperty.all(
                                    Colors.blue.shade400,
                                  ),
                                  shape: WidgetStateProperty.all(
                                      const RoundedRectangleBorder(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(5)),
                                  )),
                                  shadowColor: WidgetStateProperty.all(
                                      Colors.transparent),
                                ),
                                child: const Text(
                                  'Enviar calificación',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      );
    });
  }

  void navigateTo(String routeName) {
    NavigationService.replaceTo(routeName);
    SideMenuProvider.closeMenu();
  }

  String customMessage(double rating) {
    if (rating > 4.0) {
      return '¡Excelente! 👏🌟';
    }

    if (rating < 2.0) {
      return '¡Malo! 😔❌';
    }

    if (rating <= 4.0 && rating >= 3.0) {
      return '¡Bueno! 👍😊';
    }

    if (rating < 3.0 && rating >= 2.0) {
      return '¡Regular! 😐🔄';
    }

    return '';
  }
}
