import { Formik } from "formik";
import React, { useEffect, useState, useRef, useCallback } from "react";
import { StyleSheet, Text, View, ScrollView, FlatList } 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";

import { RefreshControl } from "react-native";

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);

  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 [loadingClockOut, setLoadingClockOut] = useState(false);
  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!");
        setLoadingClockOut(false);
        setError({ message: t("timeticketclockoff.errors.nan") });
        return;
      }
      setError(null);
      // console.log("all have values:");
    } else {
      // console.log("missing values!");
        setLoadingClockOut(false);
      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) {
        setLoadingClockOut(false);
        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
    setLoadingClockOut(true);
    const result = await updateTimeticket(tempcallobj);

    //after call results are retuning add handling below for cases
    // console.log("updateTimeticket, result :", result);
    setLoadingClockOut(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();
  };

  const onRefresh = useCallback(() => {
    setLoading(true);
    // refetch();
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  }, []);

  return (
    <View style={styles.cardBackground}>
      <FlatList
        ListHeaderComponent={
          <Card style={localStyles.localCardStyle}>
            <Card.Content>
              <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
                      mode="outlined"
                      style={styles.buttonBasicOutlined}
                      onPress={handleSubmit}
                      title={t("timeticketclockoff.actions.clockoff")}
                      loading={loadingClockOut}
                    >
                      <Text style={{ fontSize: 12 }}>
                        {t("timeticketclockoff.actions.clockoff")}
                      </Text>
                    </Button>
                  </View>
                )}
              </Formik>
            </Card.Content>
          </Card>
        }
        data={null}
        renderItem={null}
        ListFooterComponent={
          <LaborAllocationsTable
            jobId={currentTmTicketJobId}
            costCenterDiff={costCenterDiff}
            selectedCostCenter={currentSCC}
            style={localStyles.localCardStyle}
            shouldRefresh={loading}
          />
        }
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={onRefresh} />
        }
      />
    </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,
  },
  localCardStyle: {
    margin: 4,
  },
});
