import { useCallback, useContext, useState } from "react";
import { Dimensions, Text, TouchableOpacity, View } from "react-native";
import { AppContext, AppStyles, ModalContainer } from "../../../../../utils";
import { FlatList } from "react-native";
import {
  MyBottomSheetModal,
  MyPickerModalListItem,
} from "../../../../../Components/Modal";
import { useTranslation } from "react-i18next";
import { useFocusEffect } from "@react-navigation/native";
import { RenderHeaderRight } from "..";

const dataHours = [
  { number: "00" },
  { number: "01" },
  { number: "02" },
  { number: "03" },
  { number: "04" },
  { number: "05" },
  { number: "06" },
  { number: "07" },
  { number: "08" },
  { number: "09" },
  { number: "10" },
  { number: "11" },
  { number: "12" },
  { number: "13" },
  { number: "14" },
  { number: "15" },
  { number: "16" },
  { number: "17" },
  { number: "18" },
  { number: "19" },
  { number: "20" },
  { number: "21" },
  { number: "22" },
  { number: "23" },
];

const dataMinutesAndSeconds = [
  { number: "00" },
  { number: "01" },
  { number: "02" },
  { number: "03" },
  { number: "04" },
  { number: "05" },
  { number: "06" },
  { number: "07" },
  { number: "08" },
  { number: "09" },
  { number: "10" },
  { number: "15" },
  { number: "20" },
  { number: "25" },
  { number: "30" },
  { number: "35" },
  { number: "40" },
  { number: "45" },
  { number: "50" },
  { number: "55" },
];

const windowHeight = Dimensions.get("window").height;

const modalHeight = windowHeight * 0.6; // 60 % of device screen

export default function WaitEditActionModalContent({ navigation, route }) {
  const appContext = useContext(AppContext);
  const { t } = useTranslation();

  const { action } = route.params;

  const [selectedHours, setSelectedHours] = useState(
    action.modeAdjustments.hours
  );
  const [selectedMinutes, setSelectedMinutes] = useState(
    action.modeAdjustments.minutes
  );
  const [selectedSeconds, setSelectedSeconds] = useState(
    action.modeAdjustments.seconds
  );

  const NumberSelection = ({
    headerTitle,
    data,
    numberDescription,
    selectedNumber,
    setSelectedNumber,
    action,
    timeUnit,
  }) => {
    return (
      <View style={{ alignItems: "center", width: 70 }}>
        <MyNumberModal
          headerTitle={headerTitle}
          numberDescription={numberDescription}
          data={data}
          selectedNumber={selectedNumber}
          setSelectedNumber={setSelectedNumber}
          action={action}
          timeUnit={timeUnit}
        />
      </View>
    );
  };

  const NumberDivider = () => {
    return (
      <Text
        style={[
          { color: appContext.appTheme.textSecondary },
          AppStyles.typography20,
        ]}
      >
        :
      </Text>
    );
  };

  useFocusEffect(
    useCallback(() => {
      navigation.setOptions({
        headerRight: () => (
          <RenderHeaderRight
            action={action}
            appContext={appContext}
            navigation={navigation}
            t={t}
          />
        ),
      });
    }, [])
  );

  return (
    <ModalContainer>
      <View
        style={{
          flexDirection: "row",
          justifyContent: "center",
          alignItems: "center",
          marginTop: 50,
          gap: 20,
        }}
      >
        <NumberSelection
          numberDescription={
            selectedHours === 1
              ? t(
                  "screens.device.scenes.editActions.modalWaitEditAction.hours.singular"
                )
              : t(
                  "screens.device.scenes.editActions.modalWaitEditAction.hours.plural"
                )
          }
          headerTitle={t(
            "screens.device.scenes.editActions.modalWaitEditAction.hours.bottomModalHeaderTitle"
          )}
          data={dataHours}
          selectedNumber={selectedHours}
          setSelectedNumber={setSelectedHours}
          action={action}
          timeUnit={"hours"}
        />

        <NumberDivider />

        <NumberSelection
          numberDescription={
            selectedMinutes === 1
              ? t(
                  "screens.device.scenes.editActions.modalWaitEditAction.minutes.singular"
                )
              : t(
                  "screens.device.scenes.editActions.modalWaitEditAction.minutes.plural"
                )
          }
          headerTitle={t(
            "screens.device.scenes.editActions.modalWaitEditAction.minutes.bottomModalHeaderTitle"
          )}
          data={dataMinutesAndSeconds}
          selectedNumber={selectedMinutes}
          setSelectedNumber={setSelectedMinutes}
          action={action}
          timeUnit={"minutes"}
        />

        <NumberDivider />

        <NumberSelection
          numberDescription={
            selectedSeconds === 1
              ? t(
                  "screens.device.scenes.editActions.modalWaitEditAction.seconds.singular"
                )
              : t(
                  "screens.device.scenes.editActions.modalWaitEditAction.seconds.plural"
                )
          }
          headerTitle={t(
            "screens.device.scenes.editActions.modalWaitEditAction.seconds.bottomModalHeaderTitle"
          )}
          data={dataMinutesAndSeconds}
          selectedNumber={selectedSeconds}
          setSelectedNumber={setSelectedSeconds}
          action={action}
          timeUnit={"seconds"}
        />
      </View>

      <View style={{ marginTop: 20, justifyContent: "center" }}>
        <Text style={{ color: appContext.appTheme.text, textAlign: "center" }}>
          {t(
            "screens.device.scenes.editActions.modalWaitEditAction.waitDescription"
          )}
        </Text>
      </View>
    </ModalContainer>
  );
}

export function MyNumberModal({
  headerTitle,
  numberDescription,
  data,
  selectedNumber,
  setSelectedNumber,
  action,
  timeUnit,
}) {
  const appContext = useContext(AppContext);

  const [isNumberModalOpen, setIsNumberModalOpen] = useState(false);

  return (
    <>
      <TouchableOpacity
        onPress={() => setIsNumberModalOpen(true)}
        style={{ alignItems: "center" }}
      >
        <Text
          style={[{ color: appContext.appTheme.text }, AppStyles.typography20]}
        >
          {data.find((d) => parseInt(d.number, 10) === selectedNumber).number}
        </Text>

        <Text
          style={[
            { color: appContext.appTheme.textSecondary },
            AppStyles.typography14,
          ]}
        >
          {numberDescription}
        </Text>
      </TouchableOpacity>

      <MyBottomSheetModal
        isOpen={isNumberModalOpen}
        closeModal={() => setIsNumberModalOpen(false)}
        headerTitle={headerTitle}
        modalHeight={modalHeight}
      >
        <FlatList
          data={data}
          keyExtractor={(item) => item.number}
          renderItem={({ item }) => (
            <MyPickerModalListItem
              pressableBackgroundColor={
                appContext.appTheme.card.backgroundColor
              }
              itemName={item.number}
              onPress={() => {
                setSelectedNumber(parseInt(item.number, 10));

                appContext.setDeviceSceneActions((arr) => {
                  const newArr = [...arr];

                  const actionIndex = newArr.findIndex(
                    (a) => a.actionId === action.actionId
                  );

                  if (actionIndex !== -1) {
                    newArr[actionIndex].modeAdjustments[timeUnit] = parseInt(
                      item.number,
                      10
                    );
                  }

                  return newArr;
                });
              }}
              itemSelected={selectedNumber === parseInt(item.number, 10)}
            />
          )}
        />
      </MyBottomSheetModal>
    </>
  );
}
