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/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/scores_model.dart';
import 'package:prosappco/src/models/setting_model.dart';
import 'package:prosappco/src/models/user_model.dart';
import 'package:prosappco/src/screens/service.dart';

class ServiceAfterScreen extends StatefulWidget {
  var eventoId;
  ServiceAfterScreen({super.key, this.eventoId});

  @override
  State<ServiceAfterScreen> createState() => _ServiceAfterScreenState();
}

class _ServiceAfterScreenState extends State<ServiceAfterScreen> {
  Event? evento;
  UserModel? user;
  ScoresModel? scoresModel;
  SettingModel? settings;

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

    if (settings == null) {
      SettingModel.getSettings().then(
        (SettingModel value) => setState(() {
          settings = value;
        }),
      );
    }

    Event.getEventById(widget.eventoId).then((value) {
      setState(() {
        evento = value;
      });
      if (scoresModel == null) {
        ScoresModel.scoreTo(value.professionalId, true, false).then(
          (ScoresModel s) => setState(() {
            scoresModel = s;
          }),
        );
      }
      UserModel.getUser(value.professionalId).then((s) {
        setState(
          () => user = s,
        );
      });
    });
  }

  String formatCurrency(int number) {
    final formatter =
        NumberFormat.currency(locale: 'es_CO', decimalDigits: 0, symbol: '');
    return '\$${formatter.format(number)}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PopAppbar(
          onPressed: () {
            Navigator.pushReplacement(
              context,
              CupertinoPageRoute(
                builder: (BuildContext context) {
                  return const ServiceScreen();
                },
              ),
            );
          },
          label: 'Servicio'),
      body: Column(
        children: [
          ListTile(
            leading: ReferencePhoto(
              ref: user?.photo,
              size: 55,
              sizeCircle: 60,
            ),
            title: RichText(
              text: TextSpan(
                children: [
                  TextSpan(
                    text: '${user?.name}, ',
                    style: const TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontSize: 16,
                    ),
                  ),
                  TextSpan(
                    text: DateFormat('dd MMM', 'es').format(DateTime.parse(
                        evento?.day ?? '2023-01-01 00:00:00.000Z')),
                    style: const TextStyle(
                      color: Colors.grey,
                      fontSize: 16,
                    ),
                  ),
                  TextSpan(
                    text: evento?.range1Hour1 != null
                        ? TimeOfDay.fromDateTime(
                                DateTime.parse(evento!.range1Hour1))
                            .format(context)
                        : '',
                    style: const TextStyle(
                      color: Colors.grey,
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
            ),
            subtitle: Column(
              children: [
                Row(
                  children: [
                    RatingBar.builder(
                      initialRating: 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(
                        '(${scoresModel?.total.toString()})  ${scoresModel?.average.toStringAsFixed(1)}'),
                  ],
                ),
              ],
            ),
          ),
          Container(
            margin:
                const EdgeInsets.only(left: 40, right: 40, top: 20, bottom: 20),
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
            decoration: BoxDecoration(
              color: const Color(0xFFD6F4FF),
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.5),
                  spreadRadius: 1,
                  blurRadius: 5,
                  offset: const Offset(1, 3),
                ),
              ],
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.error_outline,
                  size: 27,
                  color: Colors.black54,
                ),
                const SizedBox(width: 15),
                evento?.ubicacion != 'sitio'
                    ? const Text(
                        'Servicio a su domicilio.',
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      )
                    : const Text(
                        'Servicio en sitio / consultorio',
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      ),
              ],
            ),
          ),
          settings?.tarifas == true && evento?.tarifa != 0
              ? Column(children: [
                  Text(
                    formatCurrency(evento?.tarifa ?? 0),
                    style: const TextStyle(
                        fontWeight: FontWeight.w600, fontSize: 25),
                  ),
                  const Text('Tarifa consulta'),
                  const SizedBox(height: 10)
                ])
              : const SizedBox(),
          ListTile(
            leading: const Icon(Icons.near_me),
            title: Text(
              '${evento?.address}',
              style: TextStyle(fontSize: 15, color: Colors.grey[600]),
            ),
          ),
          Text(
            '" ${evento?.description} "',
            style:
                TextStyle(color: Colors.grey[600], fontStyle: FontStyle.italic),
          ),
          const Center(
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 20),
                  child: Icon(
                    Icons.check_circle_outline_rounded,
                    color: Color(0xFF35A8ED),
                    size: 70,
                  ),
                ),
                Text(
                  'Servicio solicitado exitosamente',
                  style: TextStyle(
                      color: Color(0xFF35A8ED),
                      fontSize: 17,
                      fontWeight: FontWeight.w600),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
