import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:rogapp/model/destination.dart';
import 'package:rogapp/pages/destination/destination_controller.dart';
import 'package:rogapp/pages/index/index_controller.dart';
import 'package:rogapp/services/external_service.dart';
import 'package:rogapp/utils/const.dart';

String getTagText(bool isRecept, String? tags) {
  if (tags == null || tags.isEmpty) {
    return "";
  }
  List<String> tts = tags.split(" ");
  List<String> ttt = tags.split("　");
  if (isRecept) {
    if (ttt.length > tts.length && ttt.length > 1) {
      return ttt[1];
    }
  }
  if (!isRecept) {
    if (ttt.length > tts.length && ttt.length > 1) {
      return ttt[0];
    }
  }
  if (!isRecept) {
    return tts[0];
  }
  return "";
}

Image getDisplayImage(Destination destination) {
  String serverUrl = ConstValues.currentServer();

  Image img = Image.asset("assets/images/empty_image.png");
  if (destination.phone == null) {
    return img;
  }

  if (destination.photos!.contains('http')) {
    return Image(
      image: NetworkImage(
        destination.phone!,
      ),
      errorBuilder:
          (BuildContext context, Object exception, StackTrace? stackTrace) {
        return Image.asset("assets/images/empty_image.png");
      },
    );
  } else {
    return Image(
      image: NetworkImage(
        '$serverUrl/media/compressed/${destination.photos}',
      ),
      errorBuilder:
          (BuildContext context, Object exception, StackTrace? stackTrace) {
        return Image.asset("assets/images/empty_image.png");
      },
    );
  }
}

ImageProvider getFinishImage() {
  DestinationController destinationController =
      Get.find<DestinationController>();
  if (destinationController.photos.isNotEmpty) {
    return FileImage(destinationController.photos[0]);
  } else {
    return const AssetImage('assets/images/empty_image.png');
  }
}

ImageProvider getReceiptImage() {
  DestinationController destinationController =
      Get.find<DestinationController>();
  if (destinationController.photos.isNotEmpty) {
    return FileImage(destinationController.photos[0]);
  } else {
    return const AssetImage('assets/images/money.png');
  }
}

class CameraPage extends StatelessWidget {
  bool? manulaCheckin = false;
  bool? buyPointPhoto = false;
  Destination destination;
  Destination? dbDest;
  String? initImage;
  CameraPage(
      {Key? key,
      required this.destination,
      this.dbDest,
      this.manulaCheckin,
      this.buyPointPhoto,
      this.initImage})
      : super(key: key);
  DestinationController destinationController =
      Get.find<DestinationController>();
  IndexController indexController = Get.find<IndexController>();

  var settingGoal = false.obs;

  Timer? timer;

  Widget getAction(BuildContext context) {
    //print("----cccheckin is ---  ${dbDest?.checkedin} ----");
    if (manulaCheckin == true) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          ElevatedButton(
              onPressed: () {
                destinationController.openCamera(context, destination);
              },
              child: const Text("撮影")),
          Obx(() => destinationController.photos.isNotEmpty
              ? ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                  onPressed: () async {
                    await destinationController.makeCheckin(destination, true,
                        destinationController.photos[0].path);
                    Get.back();
                    destinationController.rogainingCounted.value = true;
                    destinationController.skipGps = false;
                    destinationController.isPhotoShoot.value = false;
                    Get.snackbar("チェックインしました。",
                        "${destination.sub_loc_id} : ${destination.name}");
                  },
                  child: const Text("チェックイン"))
              : Container())
        ],
      );
    }

    if (destinationController.isAtGoal.value &&
        destinationController.isInRog.value) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          ElevatedButton(
              onPressed: () {
                if (settingGoal.value == false) {
                  destinationController.openCamera(context, destination);
                }
              },
              child: Text("take_photo of the clock".tr)),
          Obx(() => destinationController.photos.isNotEmpty
              ? settingGoal.value == false
                  ? ElevatedButton(
                      style:
                          ElevatedButton.styleFrom(backgroundColor: Colors.red),
                      onPressed: () async {
                        // print(
                        //     "----- user isss ${indexController.currentUser[0]} -----");

                        settingGoal.value = true;
                        try {
                          int userId =
                              indexController.currentUser[0]["user"]["id"];
                          //print("--- Pressed -----");
                          String team = indexController.currentUser[0]["user"]
                              ['team_name'];
                          //print("--- _team : ${_team}-----");
                          String eventCode = indexController.currentUser[0]
                              ["user"]["event_code"];
                          //print("--- _event_code : ${_event_code}-----");
                          String token =
                              indexController.currentUser[0]["token"];
                          //print("--- _token : ${_token}-----");
                          DateTime now = DateTime.now();
                          String formattedDate =
                              DateFormat('yyyy-MM-dd HH:mm:ss').format(now);

                          await ExternalService()
                              .makeGoal(
                                  userId,
                                  token,
                                  team,
                                  destinationController.photos[0].path,
                                  formattedDate,
                                  eventCode)
                              .then((value) {
                            // print(
                            //     "---called ext api ${value['status']} ------");
                            if (value['status'] == 'OK') {
                              Get.back();
                              destinationController.skipGps = false;
                              Get.snackbar("目標が保存されました", "目標が正常に追加されました");
                              destinationController.resetRogaining();
                            } else {
                              //print("---- status ${value['status']} ---- ");
                              Get.snackbar("目標が追加されていません", "please_try_again");
                            }
                          });
                        } on Exception catch (_) {
                          settingGoal.value = false;
                        } finally {
                          settingGoal.value = false;
                        }
                      },
                      child: Text("finish_goal".tr))
                  : const Center(
                      child: CircularProgressIndicator(),
                    )
              : Container())
        ],
      );
    } else if (destinationController.isInRog.value &&
        dbDest?.checkedin != null &&
        dbDest?.checkedin == true) {
      //make buypoint image
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Obx(() => ElevatedButton(
              onPressed: () {
                destinationController.openCamera(context, destination);
              },
              child: destinationController.photos.isNotEmpty
                  ? const Text("再撮影")
                  : const Text("撮影"))),
          Obx(() => destinationController.photos.isNotEmpty
              ? ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                  onPressed: () async {
                    // print(
                    //     "##### current destination ${indexController.currentDestinationFeature[0].sub_loc_id} #######");
                    await destinationController.makeBuyPoint(
                        destination, destinationController.photos[0].path);
                    Get.back();
                    destinationController.rogainingCounted.value = true;
                    destinationController.skipGps = false;
                    destinationController.isPhotoShoot.value = false;
                    Get.snackbar("お買い物加点を行いました。",
                        "${destination.sub_loc_id} : ${destination.name}");
                  },
                  child: const Text("レシートの写真を撮る"))
              : Container())
        ],
      );
    } else {
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Obx(() => ElevatedButton(
              onPressed: () {
                destinationController.openCamera(context, destination);
              },
              child: destinationController.photos.isNotEmpty
                  ? const Text("再撮影")
                  : const Text("撮影"))),
          Obx(() => destinationController.photos.isNotEmpty
              ? ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                  onPressed: () async {
                    // print(
                    //     "##### current destination ${indexController.currentDestinationFeature[0].sub_loc_id} #######");
                    await destinationController.makeCheckin(
                        indexController.currentDestinationFeature[0],
                        true,
                        destinationController.photos[0].path);
                    Get.back();
                    destinationController.rogainingCounted.value = true;
                    destinationController.skipGps = false;
                    destinationController.isPhotoShoot.value = false;
                    Get.snackbar(
                        "チェックインしました",
                        indexController.currentDestinationFeature[0].name ??
                            "");
                  },
                  child: const Text("チェックイン"))
              : Container())
        ],
      );
    }
  }

  // void finishRog(){
  //   destinationController.addToRogaining(destinationController.current_lat, destinationController.current_lon, destination_id)
  // }

  @override
  Widget build(BuildContext context) {
    //print("---- photos ${destination.photos} ----");
    if (buyPointPhoto == true) {
      //print("--- buy point camera ${destination.toString()}");
      return BuyPointCamera(destination: destination);
    } else if (destinationController.isInRog.value) {
      //print("-----tags camera page----- ${destination.tags}");
      //print("--- in normal camera ${destination.toString()}");
      return Scaffold(
        appBar: destinationController.isInRog.value &&
                destinationController.rogainingCounted.value == true
            ? AppBar(
                automaticallyImplyLeading: false,
                title: destination.cp == -1
                    ? Text("finishing_rogaining".tr)
                    : Text("${destination.sub_loc_id} : ${destination.name}"),
                leading: IconButton(
                  icon: Text("cancel".tr),
                  onPressed: () {
                    Navigator.of(context).pop();
                    destinationController.skip_10s = true;
                    timer =
                        Timer.periodic(const Duration(seconds: 10), (Timer t) {
                      destinationController.skip_10s = false;
                    });
                  },
                ),
                centerTitle: true,
              )
            : AppBar(
                automaticallyImplyLeading: false,
                title: Text("${destination.sub_loc_id} : ${destination.name}"),
              ),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                  child: Obx(
                    () => Container(
                      width: MediaQuery.of(context).size.width,
                      height: 370,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: destinationController.photos.isEmpty
                                  ? getDisplayImage(destination).image
                                  : getFinishImage(),
                              fit: BoxFit.cover)),
                    ),
                  ),
                ),
              ),
              Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Text(getTagText(
                    false,
                    destination.tags,
                  ))
                  // child: Obx(() => destinationController.photos.isEmpty == true
                  //     ? const Text("撮影してチェックインしてください。")
                  //     : const Text("チェックインをタップしてください。")),
                  ),
              getAction(context),
            ],
          ),
        ),
      );
    } else {
      return StartRogaining();
    }
  }
}

class StartRogaining extends StatelessWidget {
  StartRogaining({Key? key}) : super(key: key);

  DestinationController destinationController =
      Get.find<DestinationController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          "Not started yet".tr,
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("You have not started rogaining yet.".tr,
                style: const TextStyle(fontSize: 24)),
            const SizedBox(
              height: 40.0,
            ),
            ElevatedButton(
              onPressed: () {
                Get.back();
                destinationController.skipGps = false;
              },
              child: const Text("Back"),
            ),
          ],
        ),
      ),
    );
  }
}

// class NotAtGoal extends StatelessWidget {
//   NotAtGoal({Key? key}) : super(key: key);

//   DestinationController destinationController =
//       Get.find<DestinationController>();

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text(
//           "Not reached the goal yet".tr,
//         ),
//       ),
//       body: Container(
//         child: Center(
//           child: Column(
//             mainAxisAlignment: MainAxisAlignment.center,
//             children: [
//               Text("You have not reached the goal yet.".tr,
//                   style: const TextStyle(fontSize: 24)),
//               const SizedBox(
//                 height: 40.0,
//               ),
//               ElevatedButton(
//                 onPressed: () {
//                   Get.back();
//                   destinationController.skip_gps = false;
//                 },
//                 child: const Text("Back"),
//               ),
//             ],
//           ),
//         ),
//       ),
//     );
//   }
// }

class BuyPointCamera extends StatelessWidget {
  BuyPointCamera({Key? key, required this.destination}) : super(key: key);

  Destination destination;

  DestinationController destinationController =
      Get.find<DestinationController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          "${destination.sub_loc_id} : ${destination.name}",
        ),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Center(
              child: Obx(
                () => Container(
                  width: MediaQuery.of(context).size.width,
                  height: 370,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: getReceiptImage(), fit: BoxFit.cover)),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(getTagText(true, destination.tags)),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            mainAxisSize: MainAxisSize.min,
            children: [
              Obx(() => Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ElevatedButton(
                          onPressed: () {
                            destinationController.openCamera(
                                context, destination);
                          },
                          child: destinationController.photos.isNotEmpty
                              ? const Text("再撮影")
                              : const Text("撮影")),
                      const SizedBox(
                        width: 10,
                      ),
                      ElevatedButton(
                          onPressed: () async {
                            await destinationController
                                .cancelBuyPoint(destination);
                            Get.back();
                            destinationController.rogainingCounted.value = true;
                            destinationController.skipGps = false;
                            destinationController.isPhotoShoot.value = false;
                          },
                          child: const Text("買い物なし"))
                    ],
                  )),
              Obx(() => destinationController.photos.isNotEmpty
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // ElevatedButton(
                        //     style: ElevatedButton.styleFrom(
                        //         backgroundColor: Colors.red),
                        //     onPressed: () async {},
                        //     child: const Text("買物なし")),
                        // const SizedBox(
                        //   width: 10,
                        // ),
                        ElevatedButton(
                            style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.red),
                            onPressed: () async {
                              await destinationController.makeBuyPoint(
                                  destination,
                                  destinationController.photos[0].path);
                              Get.back();
                              destinationController.rogainingCounted.value =
                                  true;
                              destinationController.skipGps = false;
                              destinationController.isPhotoShoot.value = false;
                              Get.snackbar("お買い物加点を行いました",
                                  "${destination.sub_loc_id} : ${destination.name}");
                            },
                            child: const Text("完了"))
                      ],
                    )
                  : Container())
            ],
          ),
        ],
      ),
    );
  }
}
