import 'package:siro_driver/views/widgets/elevated_btn.dart';
import 'package:siro_driver/views/widgets/my_scafold.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../constant/colors.dart';
import '../../../constant/links.dart';
import '../../../constant/style.dart';
import '../../../controller/functions/encrypt_decrypt.dart';
import '../../../controller/functions/gemeni.dart';
import '../../auth/captin/driver_car_controller.dart';

class CarsInsertingPage extends StatelessWidget {
  CarsInsertingPage({super.key});
  final driverCarController = Get.put(DriverCarController());
  @override
  Widget build(BuildContext context) {
    Get.put(AI());
    return MyScafolld(
        title: "Add new car".tr,
        body: [
          Container(
            color: AppColor.accentColor.withOpacity(.2),
            child: Padding(
              padding: const EdgeInsets.all(22),
              child: ListView(
                // crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  syriaCarLicenceFront(),
                  syriaCarLicenceBack(),
                  const SizedBox(height: 10),
                  Text('Please make sure to read the license carefully.'.tr),
                  Text(
                      'If your car license has the new design, upload the front side with two images.'
                          .tr),
                  const SizedBox(height: 10),
                  MyElevatedButton(
                      title: 'Please upload this license.'.tr,
                      onPressed: () {
                        final aiFront =
                            Get.find<AI>().responseIdCardDriverEgyptFront;
                        final aiBack =
                            Get.find<AI>().responseIdCardDriverEgyptBack;
                        driverCarController.addCarsForDrivers(
                          aiBack['chassis'].toString(),
                          aiBack['car_plate'].toString(),
                          aiBack['make'].toString(),
                          aiBack['model'].toString(),
                          aiBack['year'].toString(),
                          aiFront['LicenseExpirationDate'].toString(),
                          aiBack['color'].toString(),
                          aiBack['color_hex'].toString(),
                          aiFront['address'].toString(),
                          aiFront['owner'].toString(),
                          aiBack['inspection_date'].toString(),
                          aiBack['engine'].toString(),
                          aiBack['fuel'].toString(),
                        );
                      })
                ],
              ),
            ),
          )
        ],
        isleading: true);
  }
}

GetBuilder<AI> syriaCarLicenceFront() {
  return GetBuilder<AI>(
    builder: (ai) {
      if (ai.responseIdCardDriverEgyptFront.isNotEmpty) {
        // No need to access ai.responseIdCardDriverEgyptBack anymore
        final licenseExpiryDate = DateTime.parse(
            ai.responseIdCardDriverEgyptFront['LicenseExpirationDate']);

        // Check if license has expired
        final today = DateTime.now();
        final isLicenseExpired = licenseExpiryDate.isBefore(today);

        return Card(
          elevation: 4.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.0),
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text('Vehicle Details Front'.tr,
                        style: AppStyle.headTitle2),
                    IconButton(
                      onPressed: () async {
                        ai.allMethodForAI((ai.prompts[3]['prompt'].toString()),
                            AppLink.uploadEgypt, 'car_front');
                      },
                      icon: const Icon(Icons.refresh),
                    ),
                  ],
                ),
                const SizedBox(height: 8.0),
                const Divider(color: AppColor.accentColor),
                const SizedBox(height: 8.0),
                // Removed Make, Model, etc. as they are not available

                Text(
                  '${'Plate Number'.tr}: ${ai.responseIdCardDriverEgyptFront['car_plate']}',
                ),
                const SizedBox(height: 8.0),
                Text(
                  '${'Owner Name'.tr}: ${ai.responseIdCardDriverEgyptFront['owner']}',
                ),
                const SizedBox(height: 8.0),
                Text(
                  '${'Address'.tr}: ${ai.responseIdCardDriverEgyptFront['address']}',
                ),
                const SizedBox(height: 8.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '${'License Expiry Date'.tr}: ${licenseExpiryDate.toString().substring(0, 10)}',
                      style: TextStyle(
                        color: isLicenseExpired ? Colors.red : Colors.green,
                      ),
                    ),
                    // Removed Fuel as it's not available
                  ],
                ),
                // Removed Inspection Date as it's not available
              ],
            ),
          ),
        );
      }
      return Card(
        child: InkWell(
          onTap: () async {
            ai.allMethodForAINewCar((ai.prompts[3]['prompt'].toString()),
                AppLink.uploadEgypt1, 'car_front', 'carId'); //todo
          },
          child: Column(
            children: [
              Image.asset(
                'assets/images/3.png',
                height: Get.height * .25,
                width: double.maxFinite,
                fit: BoxFit.fitHeight,
              ),
              Text(
                'Capture an Image of Your car license front '.tr,
                style: AppStyle.title,
              ),
            ],
          ),
        ),
      );
    },
  );
}

GetBuilder<AI> syriaCarLicenceBack() {
  return GetBuilder<AI>(
    builder: (ai) {
      if (ai.responseIdCardDriverEgyptBack.isNotEmpty) {
        // Get the tax expiry date from the response
        final taxExpiryDate =
            ai.responseIdCardDriverEgyptBack['tax_expiry'].toString();
        // final displacement = ai.responseIdCardDriverEgyptBack['displacement'];
        // if (int.parse(displacement) < 1000) {}
        // Get the inspection date from the response
        final inspectionDate =
            ai.responseIdCardDriverEgyptBack['inspection_date'].toString();
        final year = int.parse(inspectionDate.toString().split('-')[0]);

// Set inspectionDateTime to December 31st of the given year
        final inspectionDateTime = DateTime(year, 12, 31);
        String carBackLicenseExpired =
            inspectionDateTime.toString().split(' ')[0];
// Get the current date
        final today = DateTime.now();

// Try parsing the tax expiry date. If it fails, set it to null.
        final taxExpiryDateTime = DateTime.tryParse(taxExpiryDate ?? '');
        final isExpired =
            taxExpiryDateTime != null && taxExpiryDateTime.isBefore(today);
// Check if the inspection date is before today
        bool isInspectionExpired = inspectionDateTime.isBefore(today);

        return Card(
          elevation: 4.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.0),
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('Vehicle Details Back'.tr, style: AppStyle.headTitle2),
                    IconButton(
                      onPressed: () async {
                        ai.allMethodForAI((ai.prompts[4]['prompt'].toString()),
                            AppLink.uploadEgypt, 'car_back');
                      },
                      icon: const Icon(Icons.refresh),
                    ),
                  ],
                ),
                const SizedBox(height: 8.0),
                const Divider(color: AppColor.accentColor),
                const SizedBox(height: 8.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                        '${'Make'.tr}: ${ai.responseIdCardDriverEgyptBack['make']}'),
                    Text(
                        '${'Model'.tr}: ${ai.responseIdCardDriverEgyptBack['model']}'),
                  ],
                ),
                const SizedBox(height: 8.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                        '${'Year'.tr}: ${ai.responseIdCardDriverEgyptBack['year']}'),
                    Text(
                        '${'Chassis'.tr}: ${ai.responseIdCardDriverEgyptBack['chassis']}'),
                  ],
                ),
                const SizedBox(height: 8.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                        '${'Color'.tr}: ${ai.responseIdCardDriverEgyptBack['color']}'),
                    Text(
                        '${'Displacement'.tr}: ${ai.responseIdCardDriverEgyptBack['displacement']} cc'),
                  ],
                ),
                const SizedBox(height: 8.0),
                Text(
                    '${'Fuel'.tr}: ${ai.responseIdCardDriverEgyptBack['fuel']}'),
                const SizedBox(height: 8.0),
                if (taxExpiryDateTime != null)
                  Text(
                    '${'Tax Expiry Date'.tr}: $taxExpiryDate',
                    style: TextStyle(
                      color: isExpired ? Colors.red : Colors.green,
                    ),
                  ),
                const SizedBox(height: 8.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '${'Inspection Date'.tr}: $carBackLicenseExpired',
                      style: TextStyle(
                        color: isInspectionExpired ? Colors.red : Colors.green,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      }
      return Card(
        child: InkWell(
          onTap: () async {
            ai.allMethodForAI((ai.prompts[4]['prompt'].toString()),
                AppLink.uploadEgypt, 'car_back');
          },
          child: Column(
            children: [
              Image.asset(
                'assets/images/4.png',
                height: Get.height * .25,
                width: double.maxFinite,
                fit: BoxFit.fitHeight,
              ),
              Text(
                'Capture an Image of Your car license back'.tr,
                style: AppStyle.title,
              ),
            ],
          ),
        ),
      );
    },
  );
}
