import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:service/constant/style.dart';
import 'package:service/controller/functions/launch.dart';
import 'package:service/views/widgets/my_scafold.dart';

import '../../../constant/colors.dart';
import '../../../constant/links.dart';
import '../../../views/widgets/my_textField.dart';
import '../../functions/encrypt_decrypt.dart';
import '../../functions/image.dart';
import '../main_controller.dart';

class AddCar extends StatelessWidget {
  const AddCar({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(MainController());

    return GetBuilder<MainController>(builder: (mainController) {
      return MyScaffold(
        title: 'Edit car details'.tr,
        isleading: true,
        body: [
          Expanded(
            child: ListView.builder(
                padding: const EdgeInsets.all(16.0),
                itemCount: mainController
                    .driverWithoutCar.length, // 10 fields + 1 save button
                itemBuilder: (context, index) {
                  var carData = mainController.driverWithoutCar[index];
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: InkWell(
                      onTap: () {
                        Get.to(AddCarForm(carData: carData));
                      },
                      child: Container(
                          decoration: AppStyle.boxDecoration1,
                          child: Text((carData['name_arabic']))),
                    ),
                  );
                }),
          ),
        ],
      );
    });
  }
}

class AddCarForm extends StatelessWidget {
  final Map carData;
  const AddCarForm({super.key, required this.carData});
  @override
  Widget build(BuildContext context) {
    Get.put(MainController());

    return GetBuilder<MainController>(builder: (mainController) {
      return MyScaffold(
          title: 'Add Car',
          action: Row(
            children: [
              IconButton(
                onPressed: () {
                  makePhoneCall(carData['phone']);
                },
                icon: const Icon(Icons.phone),
              ),
              IconButton(
                onPressed: () {
                  launchCommunication('whatsapp', carData['phone'], '');
                },
                icon: const Icon(
                  Icons.message,
                  color: AppColor.greenColor,
                ),
              ),
            ],
          ),
          isleading: true,
          body: [
            ListView(
              children: [
                Column(
                  children: [
                    GestureDetector(
                      onLongPress: () async {
                        await ImageController().choosImage(
                            AppLink.uploadEgypt, carData['id'], 'car_front');
                      },
                      child: Image.network(
                        '${AppLink.server}/card_image/car_front-${carData['id']}.jpg',
                        height: 200,
                        width: double.maxFinite,
                        fit: BoxFit.fill,
                        errorBuilder: (BuildContext context, Object exception,
                            StackTrace? stackTrace) {
                          // If the image fails to load, use the _copy version
                          return Image.network(
                            '${AppLink.server}/card_image/car_front-${carData['id']}_copy.jpg',
                            height: 200,
                            width: double.maxFinite,
                            fit: BoxFit.fill,
                          );
                        },
                      ),
                    ),
                    GestureDetector(
                      onLongPress: () async {
                        await ImageController().choosImage(
                            AppLink.uploadEgypt, carData['id'], 'car_back');
                      },
                      child: Image.network(
                        '${AppLink.server}/card_image/car_back-${carData['id']}.jpg',
                        height: 200,
                        width: double.maxFinite,
                        fit: BoxFit.fill,
                        errorBuilder: (BuildContext context, Object exception,
                            StackTrace? stackTrace) {
                          // If the image fails to load, use the _copy version
                          return Image.network(
                            '${AppLink.server}/card_image/car_back-${carData['id']}_copy.jpg',
                            height: 200,
                            width: double.maxFinite,
                            fit: BoxFit.fill,
                          );
                        },
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 9),
                Form(
                  key: mainController.formKey,
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          SizedBox(
                            width: Get.width * .6,
                            child: MyTextForm(
                              controller: mainController.carplateController,
                              label: 'car plate'.tr,
                              hint: 'car plate'.tr,
                              type: TextInputType.name,
                            ),
                          ),
                          IconButton(
                            onPressed: () async {
                              if (mainController.formKey.currentState!
                                  .validate()) {
                                await mainController
                                    .addRegistrationCarEgyptHandling(
                                  driverId: carData['id'].toString(),
                                  carPlate:
                                      mainController.carplateController.text,
                                  color: mainController.colorController.text,
                                  colorHex:
                                      mainController.colorHex.value.toString(),
                                  year: mainController.yearController.text,
                                  make: mainController.makeController.text,
                                  model: mainController.modelController.text,
                                  expirationDate: mainController
                                      .expirationDateController.text,
                                  owner: mainController.ownerController.text,
                                );
                              }
                            },
                            icon: const Icon(
                              Icons.upload_outlined,
                              color: AppColor.blueColor,
                            ),
                          ),
                        ],
                      ),
                      // Other fields

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: Get.width * .4,
                            child: MyTextForm(
                              controller: mainController.yearController,
                              label: 'Year'.tr,
                              hint: 'Year'.tr,
                              type: TextInputType.number,
                            ),
                          ),
                          SizedBox(
                            width: Get.width * .4,
                            child: DropdownButtonFormField<String>(
                              decoration: InputDecoration(
                                labelText: 'Color'.tr, // Localized label
                              ),
                              value: mainController.colorHex.value.isEmpty
                                  ? null
                                  : mainController.colorHex
                                      .value, // Use the hex value as the current value
                              items: [
                                {'red'.tr: '#FF0000'},
                                {'green'.tr: '#008000'},
                                {'blue'.tr: '#0000FF'},
                                {'black'.tr: '#000000'},
                                {'white'.tr: '#FFFFFF'},
                                {'yellow'.tr: '#FFFF00'},
                                {'purple'.tr: '#800080'},
                                {'orange'.tr: '#FFA500'},
                                {'pink'.tr: '#FFC0CB'},
                                {'brown'.tr: '#A52A2A'},
                                {'gray'.tr: '#808080'},
                                {'cyan'.tr: '#00FFFF'},
                                {'magenta'.tr: '#FF00FF'},
                                {'lime'.tr: '#00FF00'},
                                {'indigo'.tr: '#4B0082'},
                                {'violet'.tr: '#EE82EE'},
                                {'gold'.tr: '#FFD700'},
                                {'silver'.tr: '#C0C0C0'},
                                {'teal'.tr: '#008080'},
                                {'navy'.tr: '#000080'},
                              ].map((colorMap) {
                                String colorName = colorMap.keys.first;
                                String colorValue = colorMap.values.first;
                                return DropdownMenuItem<String>(
                                  value: colorValue,
                                  child: Text(colorName),
                                );
                              }).toList(),
                              onChanged: (value) {
                                if (value != null) {
                                  // Find the selected color name based on the hex value
                                  String selectedColorName = '';
                                  for (var colorMap in [
                                    {'red'.tr: '#FF0000'},
                                    {'green'.tr: '#008000'},
                                    {'blue'.tr: '#0000FF'},
                                    {'black'.tr: '#000000'},
                                    {'white'.tr: '#FFFFFF'},
                                    {'yellow'.tr: '#FFFF00'},
                                    {'purple'.tr: '#800080'},
                                    {'orange'.tr: '#FFA500'},
                                    {'pink'.tr: '#FFC0CB'},
                                    {'brown'.tr: '#A52A2A'},
                                    {'gray'.tr: '#808080'},
                                    {'cyan'.tr: '#00FFFF'},
                                    {'magenta'.tr: '#FF00FF'},
                                    {'lime'.tr: '#00FF00'},
                                    {'indigo'.tr: '#4B0082'},
                                    {'violet'.tr: '#EE82EE'},
                                    {'gold'.tr: '#FFD700'},
                                    {'silver'.tr: '#C0C0C0'},
                                    {'teal'.tr: '#008080'},
                                    {'navy'.tr: '#000080'},
                                  ]) {
                                    if (colorMap.values.first == value) {
                                      selectedColorName = colorMap.keys.first;
                                      break;
                                    }
                                  }

                                  mainController.colorController.text =
                                      selectedColorName;
                                  mainController.colorHex.value = value;
                                }
                              },
                            ),
                          ),
                        ],
                      ),

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: Get.width * .4,
                            child: MyTextForm(
                              controller: mainController.makeController,
                              label: 'Make'.tr,
                              hint: 'Make'.tr,
                              type: TextInputType.name,
                            ),
                          ),
                          SizedBox(
                            width: Get.width * .4,
                            child: MyTextForm(
                              controller: mainController.modelController,
                              label: 'Model'.tr,
                              hint: 'Model'.tr,
                              type: TextInputType.name,
                            ),
                          ),
                        ],
                      ),

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: Get.width * .4,
                            child: TextField(
                              controller:
                                  mainController.expirationDateController,
                              decoration: InputDecoration(
                                labelText: 'Expiration Date'.tr,
                                hintText: 'Expiration Date'.tr,
                              ),
                              readOnly:
                                  true, // Make the field read-only to prevent manual input
                              onTap: () async {
                                DateTime pickedDate =
                                    DateTime.now(); // Declare the variable here

                                await showCupertinoModalPopup<void>(
                                  context: context,
                                  builder: (context) => Container(
                                    height: 250,
                                    color: Colors.white,
                                    child: Column(
                                      children: [
                                        SizedBox(
                                          height: 150,
                                          child: CupertinoDatePicker(
                                            initialDateTime: pickedDate,
                                            minimumDate: DateTime(
                                                1955), // Set the starting date
                                            maximumDate: DateTime(
                                                2034), // Set the ending date
                                            mode: CupertinoDatePickerMode.date,
                                            onDateTimeChanged:
                                                (DateTime dateTime) {
                                              pickedDate = dateTime;
                                            },
                                          ),
                                        ),
                                        CupertinoButton(
                                          child: Text('Done'.tr),
                                          onPressed: () {
                                            String formattedDate =
                                                DateFormat('yyyy-MM-dd')
                                                    .format(pickedDate);
                                            mainController
                                                    .expirationDateController
                                                    .text =
                                                formattedDate.toString();
                                            Navigator.of(context).pop();
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                          SizedBox(
                            width: Get.width * .4,
                            child: MyTextForm(
                              controller: mainController.ownerController,
                              label: 'Owner'.tr,
                              hint: 'Owner'.tr,
                              type: TextInputType.name,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                )
              ],
            )
          ]);
    });
  }
}
