import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:garage/car/widget/insurance_row.dart';
import 'package:garage/user/model/user_provider.dart';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';

import '../model/car.dart';
import '../service/car_service.dart';
import 'info_car_page.dart';

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

  @override
  State<MyInsurancePage> createState() => _MyInsurancePageState();
}

class _MyInsurancePageState extends State<MyInsurancePage> {
  final CarService carService = GetIt.instance<CarService>();

  @override
  Widget build(BuildContext context) {
    final UserProvider userProvider = context.watch<UserProvider>();
    if (userProvider.currentUser == null) {
      print("Nikdy tady neni null");
      userProvider.updateUser();
      return CircularProgressIndicator();
    }
    final carIds = userProvider.currentUser!.cars;
    final List<Future<Car?>> futureCars = [];
    for (String recipeId in carIds) {
      futureCars.add(carService.getItemById(recipeId));
    }
    final futureList = Future.wait(futureCars);
    return Scaffold(
      body: Center(
          child: FutureBuilder<List<Car?>>(
        future: futureList,
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text("WRONG ${snapshot.error}"));
          }
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          List<Car?> cars = snapshot.data!;
          cars = cars
              .where((Car? car) => car != null && car.insurances.isNotEmpty)
              .toList();
          mergeSort(cars,
              compare: (car1, car2) => car1!
                  .getCurrentInsurance()!
                  .expirationDate
                  .compareTo(car2!.getCurrentInsurance()!.expirationDate));
          if (cars.isEmpty) {
            return Center(
                child: Column(
              children: [
                Image.asset("images/empty_drawing.png"),
                Text("Žádné vozidlo nemá pojištění."),
              ],
            ));
          }
          return ListView.separated(
              separatorBuilder: (_, __) => const Divider(),
              itemCount: cars.length,
              itemBuilder: (context, i) {
                return InkWell(
                    onTap: () {
                      Navigator.of(context)
                          .push(MaterialPageRoute(builder: (context) {
                        return InfoCarPage(
                          car: cars[i]!,
                          refresh: () {
                            setState(() {});
                          },
                        );
                      }));
                    },
                    child: InsuranceRow(
                      car: cars[i]!,
                      refresh: () => setState(() {}),
                    ));
              });
        },
      )),
    );
  }
}
