import { Formik } from "formik";
import React, { useEffect, useState, useRef } from "react";
import { StyleSheet, Text, View, ScrollView } from "react-native";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { Button, TextInput, Card, Headline, Subheading } from "react-native-paper";
import  CostCenterSelect  from "../Selects/select-cost-center";
import {
  selectCurrentEmployee,
  selectRates,
} from "../../redux/employee/employee.selectors";
import { selectBodyshop,selectRestrictClaimableHoursFlag } from "../../redux/user/user.selectors";
import LaborAllocationsTable from "../labor-allocations-table/labor-allocations-table.component";
import { UPDATE_TIME_TICKET } from "../../graphql/timetickets.queries";
import { useMutation } from "@apollo/client";
import { selectCurrentTmTicketJobId } from "../../redux/app/app.selectors";
import ErrorDisplay from "../error-display/error-display.component";
import { timeTicketClockOutStart } from "../../redux/timetickets/timetickets.actions";
import { logImEXEvent } from "../../firebase/firebase.analytics";
import axios from "axios";
import { useNavigation } from "@react-navigation/native";
import styles from "../styles";
import StyleRepeater from "../style-repeater/style-repeater";
// import { selectCurrentTimeTicketJobId } from "../../redux/timetickets/timetickets.selectors";

import { QUERY_ACTIVE_TIME_TICKETS } from "../../graphql/timetickets.queries";
const mapStateToProps = createStructuredSelector({
  currentEmployee: selectCurrentEmployee,
  currentRatesNCostCenters: selectRates,
  currentBodyshop: selectBodyshop,
  currentTmTicketJobId: selectCurrentTmTicketJobId,
  currentRestrictClaimableHoursFlag: selectRestrictClaimableHoursFlag
});
const mapDispatchToProps = (dispatch) => ({
  timeTicketClockOutStart,
});

export function TimeTicketClockOff({
  currentEmployee,
  currentRatesNCostCenters,
  currentBodyshop,
  currentTmTicketJobId,
  currentRestrictClaimableHoursFlag,
  route,
}) {

  const costCenterDiff = useRef(0);
  // console.log("TimeTicketClockOff, costCenterDiff :", costCenterDiff);


  const setCostCenterDiff = (value) => {
    countRef.current = val;
    console.log(`Button clicked ${countRef.current} times`);
  };

  const navigation = useNavigation();
  const { timeTicketId } = route.params;
  // console.log("TimeTicketClockOff, timeTicketId :", timeTicketId);
  //  console.log( "TimeTicketClockOff, handleOnDone :", handleOnDone );

  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [currentSCC, setCurrentSCC] = useState(null);

  const [updateTimeticket] = useMutation(UPDATE_TIME_TICKET,
    {refetchQueries: ["QUERY_ACTIVE_TIME_TICKETS"]});

  const handleFinish = async (values) => {
    logImEXEvent("TimeTicketClockOff_handleFinish");

    if (
      !!values.actualhours &&
      !!values.productivehours &&
      !!currentSCC?.value
    ) {
      if (isNaN(values.actualhours)|isNaN(values.productivehours)) {
        // console.log("actual hours is NAN!");
        setLoading(false);
        setError({ message: t("timeticketclockoff.errors.nan") });
        return;
      }
      setError(null);
      // console.log("all have values:");
    } else {
      // console.log("missing values!");
      setError({ message: t("timeticketclockoff.errors.missingvalues")  });
      return;
    }
    // console.log("TimeTicketClockOff, currentRestrictClaimableHoursFlag :", currentRestrictClaimableHoursFlag);
    if(!!currentRestrictClaimableHoursFlag){
      //  console.log("TimeTicketClockOff, currentRestrictClaimableHoursFlag I am here:", currentRestrictClaimableHoursFlag);
      if (values.productivehours > costCenterDiff.current){
        setError({ message: t("timeticketclockoff.errors.hoursenteredmorethanavailable")  });
        return;
      }    
    }

    const tempcallobj = {
      variables: {
        timeticketId: timeTicketId,
        timeticket: {
          actualhrs: values?.actualhours,
          ciecacode:
            currentBodyshop?.cdk_dealerid || currentBodyshop?.pbs_serialnumber
              ? currentSCC?.value
              : Object.keys(
                  currentBodyshop.md_responsibility_centers.defaults.costs
                ).find((key) => {
                  return (
                    currentBodyshop.md_responsibility_centers.defaults.costs[
                      key
                    ] === currentSCC?.value
                  );
                }),
          clockoff: (await axios.post("/utils/time")).data,
          cost_center: currentSCC?.value,
          flat_rate:
            currentEmployee &&
            currentEmployee.technician &&
            currentEmployee.technician?.flat_rate,
          productivehrs: values?.productivehours,
          rate:
            currentRatesNCostCenters &&
            currentSCC?.value &&
            currentRatesNCostCenters.filter(
              (r) => r.cost_center === currentSCC?.value
            )[0]?.rate,
        },
      },
    };
    // console.log("TimeTicketClockOff, tempcallobj :", tempcallobj);

    //after obj is good add below to make call
    setLoading(true);
    const result = await updateTimeticket(tempcallobj);

    //after call results are retuning add handling below for cases
    // console.log("updateTimeticket, result :", result);
    setLoading(false);
    if (!!result.errors) {
      console.log("updateTimeticket, result.error :", result.errors);
      setError(JSON.stringify(result.errors));
    } else {
      console.log("updateTimeticket, result :", result.data);
      navigation.goBack();
    }
    //if (completedCallback) completedCallback();
  };
  return (
    <View style={styles.cardBackground}> 
    {/* style={localStyles.content}> */}
      <StyleRepeater childStyle={{ margin: 4 }}>
      <Card>
        <Formik
          initialValues={{
            costcenter: { currentSCC },
            productivehours: "",
            actualhours: "",
          }}
          onSubmit={handleFinish}
        >
          {({ handleChange, handleBlur, handleSubmit, values }) => (
            <View style={localStyles.topTimeTicketContainer}>
              <TextInput
                style={localStyles.inputStyle}
                mode="outlined"
                onChangeText={handleChange("actualhours")}
                onBlur={handleBlur("actualhours")}
                value={values.actualhours}
                label={t("timeticketclockoff.labels.actualhoursplaceholder")}
                keyboardType="numeric"
              />
              <TextInput
                style={localStyles.inputStyle}
                mode="outlined"
                onChangeText={handleChange("productivehours")}
                onBlur={handleBlur("productivehours")}
                value={values.productivehours}
                label={t("timeticketclockoff.labels.productivehoursplaceholder")}
                keyboardType="numeric"
              />
              <CostCenterSelect
                currentRatesNCostCenters={currentRatesNCostCenters}
                currentValue={currentSCC}
                onValueSelected={setCurrentSCC}
              />
              {error ? <ErrorDisplay errorMessage={error.message} /> : null}
              <Button
                style={localStyles.input}
                onPress={handleSubmit}
                title={t("timeticketclockoff.actions.clockoff")}
              >
                <Text style={{ fontSize: 12 }}>{t("timeticketclockoff.actions.clockoff")}</Text>
              </Button>
            </View>
          )}
        </Formik>
        </Card>
      <LaborAllocationsTable jobId={currentTmTicketJobId} costCenterDiff={costCenterDiff} selectedCostCenter={currentSCC}/>
      </StyleRepeater>
    </View>
  );
}

export default connect(mapStateToProps, null)(TimeTicketClockOff);

const localStyles = StyleSheet.create({
  content: {
    display: "flex",
    flex: 1,
  },
  topContainer: {},
  bottomContainer: {},
  input: {},
  dateButton: {
    marginVertical: 4,
    marginHorizontal: 16,
    height: 48,
    justifyContent: "center",
    alignContent: "center",
    borderColor: "blue",
    borderWidth: 0.8,
    flex: 1,
  },
  textForButton: {
    flex: 1,
    justifyContent: "center",
    alignContent: "center",
  },
  inputStyle: {
    marginVertical: 4,
    marginHorizontal: 16,
    height: 48,
    fontSize: 16,
  },
});
