import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/response/CarsResponse.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/shimmer/my_avto_shimmer.dart';
import 'package:road24_mobile/view/widgets/car_details.dart';
import 'package:road24_mobile/view/widgets/items/cars_list_item.dart';
import 'add/add_new_car_or_edit_page.dart';
import 'my_car_page.dart';

mixin CarDetailsImp {
  void onChangedCarList(List<Results> fullList);
}

class CarDetailsPage extends StatefulWidget {
  final Results carDetails;
  final CarDetailsImp imp;

  const CarDetailsPage({required this.carDetails, required this.imp});

  static ValueNotifier<bool> refreshPage = ValueNotifier(false);
  @override
  _CarDetailsPageState createState() => _CarDetailsPageState();
}

class _CarDetailsPageState extends State<CarDetailsPage> {
  final CarsRepository carsRepository = CarsRepository();
  Results? carDetails;
  bool loading = false;

  @override
  void initState() {
    carDetails = widget.carDetails;

    MyCarPage.currentId = carDetails!.id;

    MyCarPage.currentCarNumber = carDetails!.number;

    MyCarPage.carPageNotifierDisposed = false;

    CarDetailsPage.refreshPage = ValueNotifier(false)
      ..addListener(() async {
        CarDetailsPage.refreshPage.value = false;
        if (mounted) setState(() => loading = true);

        await onRefresh();
        if (mounted) setState(() => loading = false);
      });
    super.initState();
  }

  @override
  void dispose() {
    CarDetailsPage.refreshPage.dispose();
    MyCarPage.carPageNotifierDisposed = true;
    super.dispose();
  }

  Future<void> onRefresh() async {
    print("details page onRefresh");
    try {
      final cars = await carsRepository.getCars();

      final response = CarsResponse.fromJson(cars);

      widget.imp.onChangedCarList(response.results);

      int index = -1;

      for (int i = 0; i < response.results.length; i++)
        if (response.results[i].id == carDetails!.id) index = i;

      print('Index index = $index');

      if (index == -1) {
        print("index is -1, go back");
        Navigator.pop(context);
      } else
        carDetails = response.results[index];
    } catch (e) {
      print("xato_car_details $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.appPrimaryColor,
      appBar: AppBar(
        backgroundColor: AppColors.appPrimaryColor,
        centerTitle: true,
        leading: FrequentWidgets.appBarBackButton(context),
        title: Text(
          S.of(context).car_about,
          style: AppStyle.textStyle().copyWith(
            color: Color(0xff282828),
            fontWeight: FontWeight.w700,
            fontSize: 22,
          ),
        ),
      ),
      body: loading || carDetails == null
          ? const MyAvtoShimmer()
          : RefreshIndicator(
              onRefresh: onRefresh,
              child: ListView(
                shrinkWrap: true,
                physics: const BouncingScrollPhysics(),
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 8.0, horizontal: 16),
                    child: CarsListItem(
                      carDetails: carDetails!,
                      onTapEdit: () async {
                        await Navigator.push(
                          context,
                          CupertinoPageRoute(
                            builder: (_) => AddNewCarOrEditPage(
                              carDetails: carDetails,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  CarDetails(
                    carDetails: carDetails!,
                    isFromMainPage: false,
                  ),
                ],
              ),
            ),
    );
  }
}
