import React, { useState, useEffect } from "react";
import { StyleSheet, Text, View, Image, FlatList } from "react-native";
import {
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  VIDEO_TITLE_HN,
  VIDEO_TITLE,
  RC_BOOK,
  RC_BOOK_HN,
  ODOMETER,
  ODOMETER_HN,
  CNG_HN,
  PUC,
  PUC_Hn,
} from "../common/Constants";
import VideoPlayer from "react-native-video-player";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import WarningContent from "../common/WarningContent";
import { TextInput } from "../common/ThemedComponents";
import Carousel, { Pagination } from "react-native-snap-carousel";
import { PrimaryButton, DashedButton } from "../common/ThemedComponents";
import Database from "../../../../Components/common/Database";
import reactotron from "reactotron-react-native";
import Validation, { renderErrorMsge } from "../common/Validation";
import Orientation from "react-native-orientation";
import { CNG } from "react-native-digitcamera/lib/commonjs/common/Constants";
import debounce from 'lodash.debounce'
const DEBOUNCE_INTERVAL = 500

const camera = require("../common/Image/camera.png");

const VechicleSurveyInstruction = ({
  title,
  subTitle,
  points,
  image,
  DocumentName,
  odometerReading,
  onCaptureButton,
  recorder,
  camera,
  show_RC_back_Button,
  show_RC_front_Button,
  isOdometerVisible,
  disableButton,
  titleHn,
  activityId,
  deleteIcon,
  tick,

  onDashedRCFrontPress,
  onDashedRCBackPress,
  onDashedRCAddMorePress,

  OnFrontButtonPressed,
  OnBackButtonPressed,
  OnAddMorePressed,

  addMoreRCImages,
  OnSkipPressed,
}) => {
  const [logoutModelVisible, setLogoutModelVisible] = useState(false);
  const [odometerReadings, setOdometerReadings] = useState(0);

  const rcBookData = [
    {
      name: "RCB1",
      image: "https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB1_V2.jpg",
      info: "RC FRONT SAMPLE",
    },
    {
      name: "RCB2",
      image: "https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB2_V2.jpg",
      info: "RC BACK SAMPLE",
    },
  ];
  let realm = Database.getRealm();
  var RealmData = realm.objects("SelectedLang");
  useEffect(() => {
    Orientation.lockToLandscapeLeft();
  }, []);

  const _renderRcBookData = ({ item, index }) => {
    return (
      // Image View
      <View style={styles.imageView}>
        <View
          style={{
            flex: 1,
            justifyContent: "center",
            borderWidth: 1,
            borderColor: "#DDDDDD",
            borderRadius: 8,
          }}
        >
          {item.image == undefined ? null : (
            <Image
              source={{ uri: item.image }}
              style={{
                width: "100%",
                height: "100%",
                resizeMode: "contain",
                alignItems: "center",
              }}
            />
          )}
          <Text style={[styles.sampleText, { paddingBottom: 20 }]}>
            {translate(item.info)}
          </Text>
        </View>
      </View>
    );
  };
  const onButtonPress = () => {
    onCaptureButton();
  };

  const onDashedFrontClick = () => {
    onDashedRCFrontPress();
  };

  const onDashedBackClick = () => {
    onDashedRCBackPress();
  };

  const onDashedAddMoreClick = () => {
    onDashedRCAddMorePress();
  };

  const RCBFrontButtonClick = () => {
    OnFrontButtonPressed();
  };

  const RCBBackButtonClick = () => {
    OnBackButtonPressed();
  };

  const RCBAddMoreButtonclicked = () => {
    OnAddMorePressed();
  };

  const onSkipClicked = () => {
    OnSkipPressed();
  };

  const debouncedCall = debounce(() => {
    console.log("Debounced")
    onButtonPress()
  }, DEBOUNCE_INTERVAL, { 'trailing': true })

  const renderItem = ({ index, item }) => {
    return (
      <DashedButton
        // Title={this.props.route?.params?.photo?.split('/')[this.props.route?.params?.photo?.split('/').length - 1]}
        Title={activityId + "_" + "RCB.jpg"}
        RightImage={deleteIcon}
        leftImage={tick}
        onDeletePress={() => {
          onDashedAddMoreClick();
        }}
      />
    );
  };
  return (
    <View style={{ flex: 1 }}>
      {title == RC_BOOK || title == RC_BOOK_HN ? (
        <View style={{ flexDirection: "row" }}>
          {/* crausel Image View */}
          <View style={{ flex: 0.5, paddingBottom: 10 }}>
            <Carousel
              data={rcBookData}
              renderItem={_renderRcBookData}
              sliderWidth={SCREEN_WIDTH}
              itemWidth={SCREEN_WIDTH}
              autoplay={true}
              loop={true}
            />
          </View>
          <View style={{ flex: 0.05 }}></View>
          <View style={{ flex: 0.45 }}>
            {/* <ScrollView> */}

            {/* </ScrollView> */}
            <FlatList
              data={["A"]}
              renderItem={({ item, index }) => {
                return (
                  <View key={"" + index}>
                    {title == RC_BOOK || titleHn == RC_BOOK_HN ? (
                      <View style={{ marginLeft: 24, marginRight: 24 }}>
                        <Text style={styles.rcTitle}>
                          {translate("RC Book")}
                        </Text>
                        {/* RC front */}
                        <Text style={styles.rcTypeText}>
                          {translate("RC Front Page")}
                        </Text>
                        {!show_RC_front_Button ? (
                          <DashedButton
                            // Title={this.props.route?.params?.photo?.split('/')[this.props.route?.params?.photo?.split('/').length - 1]}
                            Title={activityId + "_" + "RCB1.jpg"}
                            RightImage={deleteIcon}
                            leftImage={tick}
                            onDeletePress={() => {
                              onDashedFrontClick();
                            }}
                          />
                        ) : (
                          <PrimaryButton
                            style={{
                              marginBottom: 24,
                              marginTop: 5,
                              backgroundColor: "white",
                              borderColor: "#00000",
                              borderWidth: 1,
                              borderRadius: 4,
                            }}
                            onPress={() => {
                              RCBFrontButtonClick();
                            }}
                            icon={({ color, size }) => {
                              return (
                                <Image
                                  source={camera}
                                  style={{ width: 30, height: 30 }}
                                />
                              );
                            }}
                          >
                            {translate("Capture Image")}
                          </PrimaryButton>
                        )}

                        {/* RC back */}
                        <Text style={styles.rcTypeText}>
                          {translate("RC Back Page")}
                        </Text>
                        {!show_RC_back_Button ? (
                          <DashedButton
                            // Title={this.props.route?.params?.photo?.split('/')[this.props.route?.params?.photo?.split('/').length - 1]}
                            Title={activityId + "_" + "RCB2.jpg"}
                            RightImage={deleteIcon}
                            leftImage={tick}
                            onDeletePress={() => {
                              onDashedBackClick();
                            }}
                          />
                        ) : (
                          <PrimaryButton
                            style={{
                              marginBottom: 24,
                              marginTop: 5,
                              backgroundColor: "white",
                              borderColor: "#00000",
                              borderWidth: 1,
                              borderRadius: 4,
                            }}
                            onPress={() => {
                              RCBBackButtonClick();
                            }}
                            icon={({ color, size }) => {
                              return (
                                <Image
                                  source={camera}
                                  style={{ width: 30, height: 30 }}
                                />
                              );
                            }}
                          >
                            {translate("Capture Image")}
                          </PrimaryButton>
                        )}

                        {/* RC back if any other */}
                        <Text style={styles.rcTypeText}>
                          {translate("Other RC Pages (if any)")}
                        </Text>
                        <FlatList
                          data={addMoreRCImages}
                          keyExtractor={(item, index) => index.toString()}
                          renderItem={renderItem}
                          maxToRenderPerBatch={100}
                          updateCellsBatchingPeriod={1000}
                        />
                        <PrimaryButton
                          style={{
                            marginTop: 5,
                            backgroundColor: "white",
                            borderColor: "#00000",
                            borderWidth: 1,
                            borderRadius: 4,
                          }}
                          onPress={() => {
                            RCBAddMoreButtonclicked();
                          }}
                        >
                          {translate("+  Add Photos")}
                        </PrimaryButton>

                        {/* Button */}
                        <PrimaryButton
                          style={{
                            marginBottom: 24,
                            marginTop: SCREEN_WIDTH / 8,
                          }}
                          onPress={() => {
                            debouncedCall()
                            // onButtonPress();
                          }}
                          icon={({ color, size }) => {
                            return title == VIDEO_TITLE ||
                              title == VIDEO_TITLE_HN ? (
                              <Image
                                source={recorder}
                                style={{ width: 30, height: 30 }}
                              />
                            ) : (
                              <Image
                                source={camera}
                                style={{ width: 30, height: 30 }}
                              />
                            );
                          }}
                          disabled={
                            title == RC_BOOK || titleHn == RC_BOOK_HN
                              ? !(!show_RC_back_Button && !show_RC_front_Button)
                              : isOdometerVisible
                                ? disableButton
                                  ? true
                                  : false
                                : false
                          }
                        >
                          {title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN
                            ? translate("Capture Video")
                            : title == RC_BOOK || titleHn == RC_BOOK_HN
                              ? translate("Proceed")
                              : translate("Capture Image")}
                        </PrimaryButton>
                      </View>
                    ) : null}
                  </View>
                );
              }}
              keyExtractor={(item) => item.id}
            ></FlatList>
          </View>
        </View>
      ) : (
        <View style={[styles.main, { paddingBottom: 20 }]}>
          {/* Image view */}
          <View style={{ flex: 0.5 }}>
            {image == undefined ? null : (
              <View style={styles.vechicleImageView}>
                {DocumentName != "VDO" ? (
                  <Image
                    source={{ uri: image }}
                    style={{
                      width: "100%",
                      height: SCREEN_HEIGHT / 2.4,
                      alignSelf: "center",
                      resizeMode: "contain",
                    }}
                  />
                ) : (
                  <VideoPlayer
                    video={{ uri: image }}
                    videoHeight={SCREEN_HEIGHT}
                    videoWidth={SCREEN_WIDTH - 48}
                    pauseOnPress={true}
                    autoplay={true}
                    disableSeek={false}
                    style={styles.productImageStyle}
                  ></VideoPlayer>
                )}
              </View>
            )}
            {/* Title View */}
            <View style={styles.titleView}>
              {title == VIDEO_TITLE || title == VIDEO_TITLE_HN ? (
                <Text
                  style={{
                    fontFamily: "Muli-SemiBold",
                    fontSize: 12,
                    color: "#999999",
                    marginBottom: 29,
                  }}
                >
                  {translate("SAMPLE VIDEO")}
                </Text>
              ) : null}
            </View>
          </View>
          {/* blank View */}
          <View style={{ flex: 0.05 }}></View>
          {/* Text View */}
          <View style={{ flex: 0.45 }}>
            {/* subTitle View */}
            <View style={styles.subTitleView}>
              <FlatList
                data={[title]}
                renderItem={({ item, index }) => {
                  return (
                    <Text key={"" + index} style={styles.titleStyle}>
                      {item}
                    </Text>
                  );
                }}
                keyExtractor={(item) => item.id}
              ></FlatList>
            </View>

            {/* points View */}
            <View style={styles.pointsView}>
              {/* <ScrollView> */}

              {/* </ScrollView> */}
              <FlatList
                data={["A"]}
                renderItem={({ item, index }) => {
                  return (
                    <View key={"" + index}>
                      <Text key={"" + index} style={styles.subTitleText}>
                        {subTitle}
                      </Text>
                      {/*  display only for odometer*/}
                      {title == ODOMETER || title == ODOMETER_HN ? (
                        <TextInput
                          returnKeyType="done"
                          keyboardType={"number-pad"}
                          style={{ marginTop: 20 }}
                          label={translate("Enter Odometer Reading (in Km)")}
                          value={"" + odometerReadings}
                          onChangeText={(value) => {
                            setOdometerReadings(value);
                            odometerReading(value);
                          }}
                          errorMsge={
                            Number(odometerReadings) < 1
                              ? renderErrorMsge({
                                  type: "input",
                                  text: "Odometer Reading",
                                })
                              : null
                          }
                        />
                      ) : null}
                      {points?.map((item, index) => {
                        return (
                          <Text key={"" + index} style={styles.pointsText}>
                            {"\u2022 "}
                            {RealmData[0]?.PreferredLanguage === undefined ||
                            RealmData[0]?.PreferredLanguage == "en"
                              ? item?.instructionData?.includes("Note:")
                                ? item?.instructionData
                                    ?.split("Note:")[0]
                                    ?.trim()
                                    .split("<br>")
                                    .join("")
                                : item?.instructionData?.split(".")?.join("")
                              : item?.instructionDataHn?.includes("नोट:")
                              ? item?.instructionDataHn
                                  ?.split("नोट:")[0]
                                  ?.trim()
                              : item?.instructionDataHn?.split(".")?.join("")}
                          </Text>
                        );
                      })}

                      {points?.map((item, index) => {
                        if (item?.instructionData?.includes("Note:")) {
                          return (
                            <WarningContent
                              key={"" + index}
                              style={{ marginTop: 16 }}
                              textContent={
                                "Note:" +
                                item?.instructionData
                                  ?.split("Note:")[1]
                                  ?.split(".")
                                  ?.join("")
                              }
                            ></WarningContent>
                          );
                        }
                      })}
                    </View>
                  );
                }}
                keyExtractor={(item) => item.id}
              ></FlatList>
            </View>
            {/* Buttons  */}
            <View style={{ flex: 0.3, justifyContent: "center" }}>
              {DocumentName == "CNG" || DocumentName == "PUC" ? (
                <View style={{ flexDirection: "row" }}>
                  <View style={{ flex: 0.5 }}>
                    <PrimaryButton
                      style={{ marginBottom: 24 }}
                      onPress={() => {
                        debouncedCall()

                        // onButtonPress();
                      }}
                      icon={({ color, size }) => {
                        return title == VIDEO_TITLE ||
                          title == VIDEO_TITLE_HN ? (
                          <Image
                            source={recorder}
                            style={{ width: 30, height: 30 }}
                          />
                        ) : (
                          <Image
                            source={camera}
                            style={{ width: 30, height: 30 }}
                          />
                        );
                      }}
                      disabled={
                        title == RC_BOOK || titleHn == RC_BOOK_HN
                          ? !(!show_RC_back_Button && !show_RC_front_Button)
                          : isOdometerVisible
                          ? disableButton
                            ? true
                            : false
                          : false
                      }
                    >
                      {title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN
                        ? translate("Capture Video")
                        : title == RC_BOOK || titleHn == RC_BOOK_HN
                        ? translate("Proceed")
                        : translate("Capture")}
                    </PrimaryButton>
                  </View>
                  <View style={{ flex: 0.5 }}>
                    <PrimaryButton
                      style={{ marginLeft: 8 }}
                      mode={"outlined"}
                      color={"#FFFFFF"}
                      onPress={() => {
                        onSkipClicked();
                      }}
                    >
                      {translate("Skip")}
                    </PrimaryButton>
                  </View>
                </View>
              ) : (
                <PrimaryButton
                  style={{ marginBottom: 24, marginRight: 24, marginLeft: 24 }}
                  onPress={() => {
                    debouncedCall()

                    // onButtonPress();
                  }}
                  icon={({ color, size }) => {
                    return title == VIDEO_TITLE || title == VIDEO_TITLE_HN ? (
                      <Image
                        source={recorder}
                        style={{ width: 30, height: 30 }}
                      />
                    ) : (
                      <Image
                        source={camera}
                        style={{ width: 30, height: 30 }}
                      />
                    );
                  }}
                  disabled={
                    title == RC_BOOK || titleHn == RC_BOOK_HN
                      ? !(!show_RC_back_Button && !show_RC_front_Button)
                      : isOdometerVisible
                      ? disableButton && DocumentName == "DBD"
                        ? true
                        : false
                      : false
                  }
                >
                  {title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN
                    ? translate("Capture Video")
                    : title == RC_BOOK || titleHn == RC_BOOK_HN
                    ? translate("Proceed")
                    : translate("Capture Image")}
                </PrimaryButton>
              )}
            </View>
          </View>
        </View>
      )}
    </View>
  );
};
const styles = StyleSheet.create({
  main: {
    backgroundColor: "#FFFFFF",
    flex: 1,
    marginRight: 24,
    marginLeft: 24,
    flexDirection: "row",
  },
  vechicleImageView: {
    width: "100%",
    height: "100%",
    justifyContent: "center",
    borderWidth: 1,
    borderColor: "#DDDDDD",
    borderRadius: 8,
  },
  titleStyle: {
    fontSize: 20,
    fontFamily: "Muli-Black",
  },
  pointsText: {
    fontSize: 16,
    fontFamily: "Muli-Regular",
    flex: 1,
    lineHeight: 32,
  },
  titleView: {
    marginTop: 48,
  },
  subTitleView: {
    marginTop: 16,
    flex: 0.2,
  },
  subTitleText: {
    fontFamily: "Muli-SemiBold",
    fontSize: 16,
    marginTop: 8,
  },
  pointsView: {
    marginTop: 18,
    flex: 0.5,
    marginBottom: 16,
  },
  productImageStyle: {
    height: "100%",
  },
  imageView: {
    flex: 1,
    marginLeft: 24,
    marginRight: 24,
  },
  sampleText: {
    fontFamily: "Muli-SemiBold",
    fontSize: 12,
    color: "#999999",
    alignItems: "center",
    marginTop: 3,
  },
  rcTitle: {
    fontFamily: "Muli-Black",
    fontSize: 20,
    marginBottom: 17,
  },
  rcTypeText: {
    fontFamily: "Muli-Bold",
    fontSize: 14,
  },
});
export default VechicleSurveyInstruction;
