import { useQuery } from "@apollo/client";
import { Picker } from "native-base";
import React from "react";
import { Text, View } from "react-native";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_ALL_ACTIVE_JOBS } from "../../graphql/jobs.queries";
import { setCameraJob, setCameraJobId } from "../../redux/app/app.actions";
import { selectCurrentCameraJobId } from "../../redux/app/app.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import ErrorDisplay from "../error-display/error-display.component";
import LoadingDisplay from "../loading-display/loading-display.component";
import { useTranslation } from "react-i18next";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  cameraJobId: selectCurrentCameraJobId,
});

const mapDispatchToProps = (dispatch) => ({
  setCameraJobId: (id) => dispatch(setCameraJobId(id)),
  setCameraJob: (job) => dispatch(setCameraJob(job)),
});

export function CameraSelectJob({
  bodyshop,
  cameraJobId,
  setCameraJobId,
  setCameraJob,
}) {
  const { loading, error, data } = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    variables: {
      statuses: bodyshop.md_ro_statuses.active_statuses || ["Open", "Open*"],
    },
    skip: !bodyshop,
  });
  const { t } = useTranslation();
  if (loading) return <LoadingDisplay />;
  if (error) return <ErrorDisplay errorMessage={error.message} />;

  console.log("Picker Render");
  return (
    <View
      style={{
        fontSize: 20,
        fontWeight: "bold",
      }}
    >
      {!cameraJobId && <Text>{t("mediabrowser.labels.selectjob")}</Text>}
      <Picker
        selectedValue={cameraJobId}
        onValueChange={(value, idx) => {
          setCameraJobId(value);
          setCameraJob(data.jobs[idx]);
        }}
      >
        {data.jobs.map((j) => {
          return (
            <Picker.Item
              label={`${j.ro_number ? `${j.ro_number} - ` : ``}${
                j.ownr_fn || ""
              } ${j.ownr_ln || ""} ${j.ownr_co_nm || ""} - ${
                j.v_model_yr || ""
              } ${j.v_make_desc || ""} ${j.v_model_desc || ""}`}
              value={j.id}
              key={j.id}
            />
          );
        })}
      </Picker>
    </View>
  );
}

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