import React, { useCallback, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
} from "react-native";
import axios from "axios";
import { connect } from "react-redux";
import { employeeGetRatesStart } from "../../redux/employee/employee.actions";
import { createStructuredSelector } from "reselect";
import {
  selectCurrentEmployee,
  selectRates,
  selectGettingRates,
  selectSignInError,
} from "../../redux/employee/employee.selectors";
import { Button, Card } from "react-native-paper";

import { QUERY_ACTIVE_TIME_TICKETS } from "../../graphql/timetickets.queries";
//temp
import { useQuery } from "@apollo/client";
import ErrorDisplay from "../error-display/error-display.component";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { JobIdSearchSelect } from "../Selects/select-job-id";
import { CostCenterSelect } from "../Selects/select-cost-center";
import {
  selectCurrentTimeTicketJob,
  selectCurrentTimeTicketJobId,
} from "../../redux/timetickets/timetickets.selectors";
import moment from "moment";
import EmployeeClockedInList from "../time-ticket-lists/employee-clockedin-list.component";
import { useNavigation } from "@react-navigation/native";

import { INSERT_NEW_TIME_TICKET } from "../../graphql/timetickets.queries";
import { useMutation } from "@apollo/client";
import { logImEXEvent } from "../../firebase/firebase.analytics";

const mapStateToProps = createStructuredSelector({
  currentEmployee: selectCurrentEmployee,
  loaderGettingRates: selectGettingRates,
  signingError: selectSignInError,
  currentBodyshop: selectBodyshop,
  currentRatesNCostCenters: selectRates,
  currentSelectedTimeTicketJobId: selectCurrentTimeTicketJobId,
  currentSelectedTimeTicketJob: selectCurrentTimeTicketJob,
});

const mapDispatchToProps = (dispatch) => ({
  employeeGetRatesStart: (employeeId) =>
    dispatch(employeeGetRatesStart(employeeId)),
});

export function ScreenTimeTicketBrowser({
  loaderGettingRates,
  currentEmployee,
  employeeGetRatesStart,
  signingError,
  currentBodyshop,
  currentRatesNCostCenters,
  currentSelectedTimeTicketJob,
  currentSelectedTimeTicketJobId,
}) {
  const navigation = useNavigation();
  //const employeeId = currentEmployee.technician.id;
  const [currentSCC, setCurrentSCC] = useState(null);
  const [currentSJobId, setCurrentSJobId] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [refreshing, setRefreshing] = useState(false);
  const [insertTimeTicket] = useMutation(INSERT_NEW_TIME_TICKET, {
    refetchQueries: ["QUERY_ACTIVE_TIME_TICKETS"],
  });
  const [jobCount, setJobCount] = useState(0);

  //test area

  const handleFinish = async (values) => {
    console.log("handleFinish called in ScreenTimeTicketBrowser");
    setLoading(true);
    setError(null);
    //do stuff...

    const theTime = (await axios.post("/utils/time")).data;

    if (!!currentSCC?.value && !!currentSJobId?.value) {
      setError(null);
      console.log("have all values");
    } else {
      console.log("missing values!");
      setLoading(false);
      setError({ message: "Please make sure all fields have a value." });
      return;
    }

    if (currentSJobId)
      console.log("jobid or currentSJobId", currentSJobId?.value);

    const tempVariablesObj = {
      variables: {
        timeTicketInput: [
          {
            bodyshopid: currentBodyshop.id,
            employeeid: currentEmployee?.technician?.id,
            date: moment(theTime).format("YYYY-MM-DD"),
            clockon: moment(theTime),
            jobid: currentSJobId?.value,
            cost_center: currentSCC?.value,
            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
                    );
                  }),
          },
        ],
      },
    };
    console.info(
      "INSERT_NEW_TIME_TICKET, variables for clockin. : ",
      tempVariablesObj?.variables?.timeTicketInput[0]
    );

    const result = await insertTimeTicket(tempVariablesObj);
    console.log("insertTimeTicket, result :", result);

    setLoading(false);
    if (!!result.errors) {
      console.log("insertTimeTicket, result.error :", result.errors);
      setError(JSON.stringify(result.errors));
    } else {
      console.log("insertTimeTicket, result. :", result.data);
      //show success
      //clear fields

      setCurrentSJobId(null);
      setCurrentSCC(null);
    }
  };
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    setTimeout(() => {
      setRefreshing(false);
    }, 2000);
  }, []);

  return (
    <View style={localStyles.content}>
      <ScrollView
        style={{ flex: 1 }}
        contentContainerStyle={{ flexGrow: 1 }}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      >
        <Card>
          <JobIdSearchSelect
            currentValue={currentSJobId}
            onJobSelected={setCurrentSJobId}
            convertedOnly={!currentBodyshop.tt_allow_post_to_invoiced}
            notExported={!currentBodyshop.tt_allow_post_to_invoiced}
          />
          <CostCenterSelect
            currentValue={currentSCC}
            currentRatesNCostCenters={currentRatesNCostCenters}
            onValueSelected={setCurrentSCC}
          />
          {error && error?.message ? (
            <ErrorDisplay errorMessage={error.message} />
          ) : null}
          <Button mode="outlined" loading={loading} onPress={handleFinish}>
            <Text>Clock In</Text>
          </Button>
          
        </Card>
        {/* <View style={{ flexGrow: 1, flex: 1 }}>
          <EmployeeClockedInList
            technician={currentEmployee}
            isRefresh={refreshing}
            onRefresh={onRefresh}
          />
        </View> */}
      </ScrollView>
      <View style={{ flexGrow: 1, flex: 1 }}>
          <EmployeeClockedInList
            technician={currentEmployee}
            isRefresh={refreshing}
          />
        </View>
      {/* <ScrollView style={{flex:1}} contentContainerStyle={{ flexGrow: 1 }}  refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />} >

      <View style={{ flexGrow: 1, flex:1 }}>
        <EmployeeClockedInList technician={currentEmployee} handleRefresh={refreshing} onRefresh={onRefresh} />
      </View>
      </ScrollView> */}
    </View>
  );
}

const localStyles = StyleSheet.create({
  content: {
    display: "flex",
    flex: 2,
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ScreenTimeTicketBrowser);
