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

class CameraPage extends StatelessWidget {
  CameraPage({Key? key}) : super(key: key);
  DestinationController destinationController = Get.find<DestinationController>();
  IndexController indexController = Get.find<IndexController>();

  ImageProvider getFinishImage(){
    if(destinationController.photos.isNotEmpty){
      return FileImage(destinationController.photos[0]);
    }
    else{
      return AssetImage('assets/images/empty_image.png');
    }
  }

  Widget getAction(BuildContext context){
    if(destinationController.is_at_goal.value && destinationController.is_in_rog.value){
      return Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              ElevatedButton(
                onPressed: (){
                  destinationController.openCamera(context);
                }, 
                child: Text("take_photo of the clock".tr)
              ),
              Obx(() => 
              destinationController.photos.isNotEmpty ?
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Colors.red
                ),
                onPressed: (){
                  int user_id = indexController.currentUser[0]["user"]["id"];
                  //print("--- Pressed -----");
                  String _team = indexController.currentUser[0]["user"]['team_name'];
                  //print("--- _team : ${_team}-----");
                  String _event_code = 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);
                  
                  ExternalService().makeGoal(user_id, _token, _team, destinationController.photos[0].path, formattedDate, _event_code).then((value){
                    print("---called ext api ${value['status']} ------");
                    if(value['status'] == 'OK'){
                      Get.back();
                      destinationController.skip_gps = false;
                      Get.snackbar("目標が保存されました", "目標が正常に追加されました");
                      destinationController.resetRogaining();
                    }
                    else{
                      print("---- status ${value['status']} ---- ");
                      Get.snackbar("目標が追加されていません", "please_try_again");
                    }
                  });
                }, 
                child: Text("finish_goal".tr)
              ):
              Container()
              )
            ],
          );
    }
    else{
      return Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              ElevatedButton(
                onPressed: (){
                  destinationController.openCamera(context);
                }, 
                child: Text("再撮影")
              ),
              Obx(() => 
              destinationController.photos.isNotEmpty ?
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Colors.red
                ),
                onPressed: (){

                  destinationController.makeCheckin(indexController.currentDestinationFeature[0], true, destinationController.photos[0].path);
                  Get.back();
                  destinationController.rogaining_counted.value = true;
                  destinationController.skip_gps = false;
                  destinationController.is_photo_shoot.value = false;
                  Get.snackbar("チェックインした", "正常にチェックインしました");
                  
                  // ExternalService().makeGoal(user_id, _token, _team, destinationController.photos[0].path, formattedDate, _event_code).then((value){
                  //   print("---called ext api ${value['status']} ------");
                  //   if(value['status'] == 'OK'){
                  //     Get.back();
                  //     destinationController.skip_gps = false;
                  //     Get.snackbar("Checked in", "Checked in successfuly");
                  //   }
                  //   else{
                  //     print("---- status ${value['status']} ---- ");
                  //     Get.snackbar("Checkin not added", "please_try_again");
                  //   }
                  // });
                }, 
                child: Text("チェックイン")
              ):
              Container()
              )
            ],
          );
    }
  }

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

  @override
  Widget build(BuildContext context) {
    if(destinationController.is_in_rog.value){
      return Scaffold(
      appBar: 
      destinationController.is_in_rog.value && destinationController.rogaining_counted.value == true ?
      AppBar(
        title: Text("finishing_rogaining".tr)
        ,
      )
      :
      AppBar(
        title: Text("チェックポイント"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Padding(
            padding: EdgeInsets.all(8.0),
            child: Center(
              child: Obx(() => 
                Container(
                width: MediaQuery.of(context).size.width,
                height: 370,
                decoration:  BoxDecoration(
                  image:
                    DecorationImage(
                    image: getFinishImage(),
                    fit: BoxFit.cover
                  )
                ),
              ),
              ),
            ),
          ),
          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(
        title: Text("Not started yet".tr,),
      ),
      body: Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("You have not started rogaining yet.".tr, style: TextStyle(fontSize: 24)),
            SizedBox(height: 40.0,),
            ElevatedButton(
              onPressed: (){
                Get.back();
                destinationController.skip_gps = false;
              },
              child: 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: TextStyle(fontSize: 24)),
            SizedBox(height: 40.0,),
            ElevatedButton(
              onPressed: (){
                Get.back();
                destinationController.skip_gps = false;
              },
              child: Text("Back"),
            ),
          ],
        ),
      ),
    ),
    );
  }
}