import React, { useCallback, useState, useRef } from "react";
import moment from "moment";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  FlatList,
} from "react-native";
import {
  ActivityIndicator,
  Button,
  Card,
  Headline,
  Subheading,
} from "react-native-paper";
import styles from "../styles";

import axios from "axios";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";

import { employeeGetRatesStart } from "../../redux/employee/employee.actions";
import {
  selectCurrentEmployee,
  selectRates,
  selectGettingRates,
  selectSignInError,
  selectEmployeeFullName,
} from "../../redux/employee/employee.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";

import CostCenterSelect from "../Selects/select-cost-center";
import ErrorDisplay from "../error-display/error-display.component";
import {
  selectCurrentTimeTicketJob,
  selectCurrentTimeTicketJobId,
} from "../../redux/timetickets/timetickets.selectors";
import { INSERT_NEW_TIME_TICKET } from "../../graphql/timetickets.queries";
import { useMutation, useQuery } from "@apollo/client";
import { QUERY_ACTIVE_TIME_TICKETS } from "../../graphql/timetickets.queries";

// import EmployeeClockedInList from "../time-ticket-lists/employee-clockedin-list.component";
import { useTranslation } from "react-i18next";
import ClockedinListItem from "../time-ticket-items/clockedin-list-item.component";
import SignOutButton from "../Buttons/employee-sign-out-button.component";
import AddTimeTicketButton from "../Buttons/create-time-ticket-button.component";

import KeyboardAvoidingComponent from "../keyboards/KeyboardAvoidingComponent";
import JobSearchAndSelectModal from "../Modals/JobSearchAndSelectModal";
import { useNavigation } from "@react-navigation/native";

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

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

export function ScreenTimeTicketBrowser({
  loaderGettingRates,
  currentEmployee,
  employeeGetRatesStart,
  signingError,
  currentBodyshop,
  currentRatesNCostCenters,
  currentSelectedTimeTicketJob,
  currentSelectedTimeTicketJobId,
  currentEmployeeFullName,
}) {
  const { t } = useTranslation();
  const [currentSCC, setCurrentSCC] = useState(null);
  const [loadingClockIn, setLoadingClockIn] = 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 navigation = useNavigation();
  const [curSelClockIntoJob, setCurSelClockIntoJob] = useState(null);

  const handleFinish = async (values) => {
    setLoadingClockIn(true);
    setError(null);

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

    if (!!currentSCC?.value && !!curSelClockIntoJob?.id) {
      setError(null);
      // console.log("have all values");
    } else {
      // console.log("missing values!");
      setLoadingClockIn(false);
      setError({ message: t("timeticketbrowser.errors.missingvalues") });
      return;
    }

    const tempVariablesObj = {
      variables: {
        timeTicketInput: [
          {
            bodyshopid: currentBodyshop.id,
            employeeid: currentEmployee?.technician?.id,
            date: moment(theTime).format("YYYY-MM-DD"),
            clockon: moment(theTime),
            jobid: curSelClockIntoJob?.id,
            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
                    );
                  }),
          },
        ],
      },
    };
    const result = await insertTimeTicket(tempVariablesObj);
    setLoadingClockIn(false);
    if (!!result.errors) {
      setError(JSON.stringify(result.errors));
    } else {
      setCurSelClockIntoJob(null);
      setCurrentSCC(null);
    }
  };

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    refetch();
    setTimeout(() => {
      setRefreshing(false);
    }, 500);
  }, []);

  const [itemState, setItemState] = useState({
    title: t("employeeclockedinlist.labels.alreadyclockedon"),
    data: null,
    content: null,
  });

  const { loadingATT, errorATT, dataATT, refetch } = useQuery(
    QUERY_ACTIVE_TIME_TICKETS,
    {
      variables: {
        employeeId: currentEmployee?.technician?.id,
      },
      skip: !currentEmployee?.technician,
      onCompleted: (dataATT) => {
        if (!!dataATT && dataATT?.timetickets) {
          setItemState((itemState) => ({
            ...itemState,
            data: dataATT?.timetickets,
          }));
        }
      },
      onRefresh: { onRefresh },
    }
  );

  if (loadingATT) {
    setItemState((itemState) => ({
      ...itemState,
      content: <ActivityIndicator color="dodgerblue" size="large" />,
    }));
    return;
  }
  if (errorATT) {
    setItemState((itemState) => ({
      ...itemState,
      content: <ErrorDisplay errorMessage={errorATT.message} />,
    }));
    return;
  }

  return (
    <View style={styles.cardBackground}>
      <KeyboardAvoidingComponent>
        <FlatList
          ListHeaderComponent={
            <Card style={localStyles.localCardStyle}>
              <Card.Title
                title={t("timeticketbrowser.labels.loggedinemployee")}
                right={(props) => <SignOutButton style={{margin:8}}/>}
              />
              <Card.Content>
                {currentEmployeeFullName && (
                  <Subheading>{currentEmployeeFullName}</Subheading>
                )}
              </Card.Content>
            </Card>
          }
          data={!!itemState ? [itemState] : null}
          renderItem={({ item }) => (
            <MyItem style={localStyles.localCardStyle} itemState={item} />
          )}
          ListFooterComponent={
            <Card style={localStyles.localCardStyle}>
              <Card.Title
                title={t("timeticketbrowser.labels.clockintojob")}
                right={(props) => (
                  <View style={{ flexDirection: "row" }}>
                    <Button
                      mode="text"
                      compact={true}
                      onPress={() => {
                        navigation.navigate("CreateTimeTicket");
                      }}
                      icon="plus"
                      style={{ margin: 8 }}
                    >
                      <Text >
                        {t("timeticketbrowser.actions.ticket")}
                      </Text>
                    </Button>
                    {/* <Button
                      mode="outlined"
                      compact={true}
                      loading={loadingClockIn}
                      onPress={handleFinish}
                      style={{ margin: 4 }}
                    >
                      <Text>Clock In</Text>
                    </Button> */}
                  </View>
                )}
              />
              <Card.Content>
                <JobSearchAndSelectModal
                  currentValue={curSelClockIntoJob}
                  onSetCurrentValue={setCurSelClockIntoJob}
                  notExported={!currentBodyshop.tt_allow_post_to_invoiced}
                  notInvoiced={!currentBodyshop.tt_allow_post_to_invoiced}
                  convertedOnly={!currentBodyshop.tt_allow_post_to_invoiced}
                />
                <CostCenterSelect
                  currentValue={currentSCC}
                  currentRatesNCostCenters={currentRatesNCostCenters}
                  onValueSelected={setCurrentSCC}
                />
                {error && error?.message ? (
                  <ErrorDisplay errorMessage={error.message} />
                ) : null}
              </Card.Content>
              <Card.Actions
                style={{
                  justifyContent: "center",
                }}
              >
                <Button
                  mode="outlined"
                  style={styles.buttonBasicOutlined}
                  loading={loadingClockIn}
                  onPress={handleFinish}
                >
                  <Text>{t("timeticketbrowser.actions.clockin")}</Text>
                </Button>
              </Card.Actions>
            </Card>
          }
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
          }
          ListEmptyComponent={
            <View style={styles.containerNoData}>
              <Text>{t("timeticketbrowser.labels.nodata")}</Text>
            </View>
          }
        />
      </KeyboardAvoidingComponent>
    </View>
  );
}

const MyItem = ({ itemState, style }) => {
  const { t } = useTranslation();
  const items = itemState?.data;
  return (
    <Card key={itemState.title} style={style}>
      <Card.Title title={itemState.title} />
      <Card.Content>
        {!!items ? (
          items.map((item) => <ClockedinListItem key={item.id} ticket={item} />)
        ) : !!itemState?.content ? (
          itemState.content
        ) : (
          <Text>{t("timeticketbrowser.labels.nodata")}</Text>
        )}
      </Card.Content>
    </Card>
  );
};

const localStyles = StyleSheet.create({
  content: {
    display: "flex",
    flex: 2,
  },
  localCardStyle: {
    margin: 4,
  },
  containerNoData: {
    flex: 1,
    padding: 10,
    alignItems: "center",
    justifyContent: "center",
  },
});

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