import { connect } from "react-redux";
import { selectCurrentEmployee } from "../../redux/employee/employee.selectors";
import { QUERY_ACTIVE_TIME_TICKETS } from "../../graphql/timetickets.queries";
import { ActivityIndicator } from "react-native-paper";
import ErrorDisplay from "../error-display/error-display.component";
import { View, Text, FlatList, RefreshControl } from "react-native";
import { useMutation, useQuery } from "@apollo/client";
import { createStructuredSelector } from "reselect";
import { useTranslation } from "react-i18next";
import ClockedinListItem from "../time-ticket-items/clockedin-list-item.component";
import { useEffect, useState } from "react";

// import { setTmTicketJobId } from "../../redux/app/app.actions";

const mapStateToProps = createStructuredSelector({
  //technician: selectTechnician,
  currentEmployee: selectCurrentEmployee,
  // updateJobs: selectUpdateJobs
});
// const mapDispatchToProps = (dispatch) => ({
//   setTmTicketJobId: (jobId) => dispatch(setTmTicketJobId(jobId)),
// });

export function EmployeeClockedInList({ currentEmployee, isRefresh }) {
  const [refreshKey, setRefreshKey] = useState(isRefresh);
  const [jobData, setJobData] = useState(data);
  //  console.info("EmployeeClockedInList, QUERY_ACTIVE_TIME_TICKETS called.",currentEmployee);

  // console.info(
  //   "EmployeeClockedInList, isRefresh :",
  //   isRefresh
  // );
  const { t } = useTranslation();

  useEffect(() => {
    // async function fetchData(){
    //     // const result = await getUsers();
    //     // setData(result);
    //     console.log("teste: ", result);
    // }
    // fetchData();
    if(isRefresh){
      refetch();
    }
    // console.log("useEffect: ", isRefresh);
    // setRefreshKey(isRefresh);
    
}, [isRefresh]);

  const { loading, error, data, refetch } = useQuery(
    QUERY_ACTIVE_TIME_TICKETS,
    {
      variables: {
        employeeId: currentEmployee?.technician?.id,
      },
      skip: !currentEmployee?.technician,
      onCompleted:setJobData,
      onRefresh:{onRefresh}
    }
  );
  if (loading) return <ActivityIndicator color="dodgerblue" size="large" />;
  if (error) return <ErrorDisplay errorMessage={error.message} />;

  const onRefresh = async () => {
    // console.info("EmployeeClockedInList, onRefresh.");
    return refetch();
  };

  return (
    <View style={{ flex: 1, flexGrow: 1 }}>
      {jobData ? (
        <View style={{ flex: 1 }}>
          <Text style={{ paddingLeft: 12, paddingTop: 14 }}>
          {t("employeeclockedinlist.labels.alreadyclockedon")}
          </Text>
          <FlatList
            data={jobData?.timetickets}
            refreshControl={
              <RefreshControl refreshing={loading} onRefresh={onRefresh} />
            }
            renderItem={(object) => (
              <ClockedinListItem
                ticket={object.item}
                // handleRefresh={onRefresh}
              />
            )}
            // setTmTicketJobId={setTmTicketJobId}
          />
        </View>
      ) : null}
    </View>
    //   <div>
    //     {data.timetickets.length > 0 ? (
    //       <div>
    //         <Typography.Title level={2}>
    //           {t("timetickets.labels.alreadyclockedon")}
    //         </Typography.Title>
    //         <List
    //           grid={{
    //             gutter: 32,
    //             xs: 1,
    //             sm: 2,
    //             md: 3,
    //             lg: 4,
    //             xl: 5,
    //             xxl: 6,
    //           }}
    //           dataSource={data.timetickets || []}
    //           renderItem={(ticket) => (
    //             <List.Item>
    //               <Card
    //                 title={
    //                   <Link to={`/tech/joblookup?selected=${ticket.job.id}`}>
    //                     {`${
    //                       ticket.job.ro_number || t("general.labels.na")
    //                     } ${OwnerNameDisplayFunction(ticket.job)}`}
    //                   </Link>
    //                 }
    //                 actions={[
    //                   <TechClockOffButton
    //                     jobId={ticket.jobid}
    //                     timeTicketId={ticket.id}
    //                     completedCallback={refetch}
    //                   />,
    //                 ]}
    //               >
    //                 <div>
    //                   {`
    //                 ${ticket.job.v_model_yr || ""} ${
    //                     ticket.job.v_make_desc || ""
    //                   } ${ticket.job.v_model_desc || ""}`}
    //                 </div>
    //                 <DataLabel label={t("timetickets.fields.clockon")}>
    //                   <DateTimeFormatter>{ticket.clockon}</DateTimeFormatter>
    //                 </DataLabel>
    //                 <DataLabel label={t("timetickets.fields.cost_center")}>
    //                   {ticket.cost_center === "timetickets.labels.shift"
    //                     ? t(ticket.cost_center)
    //                     : ticket.cost_center}
    //                 </DataLabel>
    //               </Card>
    //             </List.Item>
    //           )}
    //         ></List>
    //       </div>
    // ) : null}
    //   </div>
  );
}

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