import { Formik } from "formik";
import React, { useState } 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 } from "react-native-paper";
import { CostCenterSelect } from "../Selects/select-cost-center";
import {
  selectCurrentEmployee,
  selectRates,
} from "../../redux/employee/employee.selectors";
import { selectBodyshop } 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 { selectCurrentTimeTicketJobId } from "../../redux/timetickets/timetickets.selectors";

//TODO add props needed for call
const mapStateToProps = createStructuredSelector({
  currentEmployee: selectCurrentEmployee,
  currentRatesNCostCenters: selectRates,
  currentBodyshop: selectBodyshop,
  currentTmTicketJobId: selectCurrentTmTicketJobId,
//   currentJobId: selectCurrentTimeTicketJobId
});
 const mapDispatchToProps = (dispatch) => ({
    timeTicketClockOutStart
 });

export function TimeTicketClockOff({
  currentEmployee,
  currentRatesNCostCenters,
  currentBodyshop,
  currentTmTicketJobId,
}) {
 // console.log("TimeTicketClockOff, currentEmployee :", currentEmployee);
  //console.log("TimeTicketClockOff, currentRatesNCostCenters :", currentRatesNCostCenters  );
  //  console.log("TimeTicketClockOff, currentBodyshop :", currentBodyshop);

console.log("TimeTicketClockOff, currentTmTicketJobId :", currentTmTicketJobId);
// console.log("TimeTicketClockOff, jobId :", jobId);
//   console.log("TimeTicketClockOff, timeTicketId :", timeTicketId);
  const { t } = useTranslation();

//   const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
//   const [date2, setDate2] = useState(new Date());
  const [loading, setLoading] = useState(false);

  const [currentSCC, setCurrentSCC] = useState(null);
  // const [currentSJob, setCurrentSJob] = useState(null);
  const [currentSJobId, setCurrentSJobId] = useState(currentTmTicketJobId ? currentTmTicketJobId : null);
//   const [updateTimeticket] = useMutation(UPDATE_TIME_TICKET);
  // const wrapperSetCurrentSJobState = useCallback(
  //   (val) => {
  //     setCurrentSJob(val);
  //   },
  //   [setCurrentSJob]
  // );

  //   const showDatePicker = () => {
  //     setDatePickerVisibility(true);
  //   };
  //   const hideDatePicker = () => {
  //     setDatePickerVisibility(false);
  //   };
  //   const handleConfirm = (date) => {
  //     setDate2(date);
  //     //console.war1n("A date has been picked: ", date);
  //     hideDatePicker();
  //   };
  const formSubmit = (values) => {
    console.log("values", values);
    //Dialog.alert({ content: <pre>{JSON.stringify(values, null, 2)}</pre> });
    //TODO update with start call for create time ticket
  };

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

//     setLoading(true);
//     const result = await updateTimeticket({
//       variables: {
//         timeticketId: timeTicketId,
//         timeticket: {
//           clockoff: (await axios.post("/utils/time")).data,
//           ...values,
//           rate: currentSCC?.rate,
//           // emps &&
//           // emps.rates.filter((r) => r.cost_center === values.cost_center)[0]
//           //   ?.rate,
//           flat_rate: currentEmployee && currentEmployee?.technician?.flat_rate,
//           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
//                   );
//                 }),
//         },
//       },
//     });

//     if (!!result.errors) {
//       console.log("Error handleFinish clock off");

//       //if (error) return <ErrorDisplay errorMessage={error.message} />;

//       //   notification["error"]({
//       //     message: t("timetickets.errors.clockingout", {
//       //       message: JSON.stringify(result.errors),
//       //     }),
//       //   });
//     } else {
//       console.log("success");
//       //   notification["success"]({
//       //     message: t("timetickets.successes.clockedout"),
//       //   });
//     }
//     setLoading(false);
//     if (completedCallback) completedCallback();
//   };

  return (
    <View style={localStyles.content}>
      <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
        <Formik
          initialValues={{
            costcenter: { currentSCC },
            productivehours: "",
            actualhours: "",
          }}
          onSubmit={formSubmit}
        >
          {({ handleChange, handleBlur, handleSubmit, values }) => (
            <View style={localStyles.topTimeTicketContainer}>
              {/* <JobIdSearchSelect
                currentValue={currentSJobId}
                onJobSelected={setCurrentSJobId}
                convertedOnly={!currentBodyshop.tt_allow_post_to_invoiced}
                notExported={!currentBodyshop.tt_allow_post_to_invoiced}
              /> */}
              <TextInput
                style={localStyles.inputStyle}
                mode="outlined"
                onChangeText={handleChange("actualhours")}
                onBlur={handleBlur("actualhours")}
                value={values.actualhours}
                label={"Actual Hours"}
              />
              <TextInput
                style={localStyles.inputStyle}
                mode="outlined"
                onChangeText={handleChange("productivehours")}
                onBlur={handleBlur("productivehours")}
                value={values.productivehours}
                label={"Productive Hours"}
              />
              <CostCenterSelect
                currentRatesNCostCenters={currentRatesNCostCenters}
                currentValue={currentSCC}
                onValueSelected={setCurrentSCC}
              />
              <Button
                style={localStyles.input}
                // onPress={handleSubmit}
                title="Submit"
              >
                <Text style={{ fontSize: 12 }}>Clock Off</Text>
              </Button>
            </View>
          )}
        </Formik>
      </ScrollView>
      <View style={{ flexGrow: 1 }}>
        <LaborAllocationsTable jobId={currentTmTicketJobId} />
      </View>
    </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,
  },
});
