import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:intl/intl.dart';
import 'package:prosappco/src/components/photo_view.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/models/event_model.dart';
import 'package:prosappco/src/models/user_model.dart';

class ScoreScreen extends StatefulWidget {
  final Event evento;
  final bool pro;
  const ScoreScreen({super.key, required this.evento, required this.pro});

  @override
  State<ScoreScreen> createState() => ScoreScreenState();
}

class ScoreScreenState extends State<ScoreScreen> {
  TextEditingController commentController = TextEditingController();
  Reference? ref_photo;
  String nombre = '';
  double _rating = 1.0;

  @override
  Widget build(BuildContext context) {
    if (nombre == '') {
      if (uid != widget.evento.userId) {
        UserModel.getUser(widget.evento.userId).then((value) {
          UserModel.getUser(uid.toString()).then((me) {
            setState(() {
              nombre = value.name;
              ref_photo = value.photo;
            });
          });
        });
      } else {
        UserModel.getUser(widget.evento.professionalId).then((value) {
          setState(() {
            nombre = value.name;
            ref_photo = value.photo;
          });
        });
      }
    }

    return Scaffold(
      appBar: PopAppbar(
          onPressed: () {
            Navigator.pop(context);
          },
          label: 'Puntuación'),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: ListTile(
              leading: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 5),
                child: ReferencePhoto(
                  ref: ref_photo,
                  size: 50,
                  sizeCircle: 50,
                  sizeIcon: 35,
                ),
              ),
              title: Text(
                nombre,
                style: const TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.w600,
                    fontSize: 16),
              ),
              subtitle: Text(
                  '${DateFormat('dd MMM', 'es').format(DateTime.parse(widget.evento.day))} ${TimeOfDay.fromDateTime(DateTime.parse(widget.evento.range1Hour1)).format(context)}'),
            ),
          ),
          RatingBar.builder(
            initialRating: _rating,
            minRating: 1,
            direction: Axis.horizontal,
            allowHalfRating: true,
            itemCount: 5,
            itemSize: 40,
            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,
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 40),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    'Comentario',
                    style: TextStyle(fontSize: 18),
                  ),
                  TextFormField(
                    maxLines: null,
                    maxLength: 250,
                    keyboardType: TextInputType.multiline,
                    controller: commentController,
                  ),
                ],
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 30),
            child: Column(
              children: [
                ElevatedButton(
                  onPressed: () {
                    if (widget.pro) {
                      FirebaseFirestore.instance
                          .collection("services")
                          .doc(widget.evento.id)
                          .update({'professional_scored': true}).then((value) {
                        FirebaseFirestore.instance.collection("scores").add({
                          "comment": commentController.text,
                          "from_user": widget.evento.professionalId,
                          "is_from_professional": false,
                          "score": _rating,
                          "to_user": widget.evento.userId,
                        }).then((value) {
                          Navigator.pop(context);
                        });
                      });
                    } else {
                      FirebaseFirestore.instance
                          .collection("services")
                          .doc(widget.evento.id)
                          .update({'user_scored': true}).then((value) {
                        FirebaseFirestore.instance.collection("scores").add({
                          "comment": commentController.text,
                          "from_user": widget.evento.userId,
                          "is_from_professional": true,
                          "score": _rating,
                          "to_user": widget.evento.professionalId,
                        }).then((value) {
                          Navigator.pop(context);
                        });
                      });
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF2BA4EC),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(50),
                    ),
                    elevation: 0,
                    minimumSize: const Size(230, 60),
                  ),
                  child: const Text(
                    'Enviar',
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
