// withHooks
// noPage

import esp from 'esoftplay/esp';
import React, { useEffect, useRef } from 'react';
import { TextInput, View } from 'react-native';

export interface EventCountdown_timestampProps {
  expiredTimestamp: number;
  expiredText?: string;
  style?: any;
  containerStyle?: any;
  onlyDay?: boolean;
  onExpired?: () => void;
  hideTimeUnit?: boolean;
  showDayUnit?: boolean;
}

const fixSingleNumber = (n: number) => (n < 10 ? "0" + n : n);

export default function CountdownTimestamp(props: EventCountdown_timestampProps) {
  const ref = useRef<TextInput>(null)
  let timmerRef = useRef<any>(undefined)

  useEffect(() => {
    countDown()
    return () => {
      clearTimeout(timmerRef.current)
      timmerRef.current = undefined
    }
  }, [])

  function countDown(): any {
    let expired = false
    function loop() {
      const labels = [esp.lang("market/countdown", "day"), esp.lang("market/countdown", "hour"), esp.lang("market/countdown", "minutes"), esp.lang("market/countdown", "second")]

      const expiredTimestamp = props.expiredTimestamp
      const now = Date.now();
      const diffMs = expiredTimestamp - now;

      if (diffMs <= 0) {
        expired = true;
        props.onExpired?.();
        ref.current?.setNativeProps({
          text: props.expiredText || esp.lang('market/countdown', 'expired'),
        });
        return;
      }

      const totalSeconds = Math.floor(diffMs / 1000);
      const days = Math.floor(totalSeconds / 86400);
      const hours = Math.floor((totalSeconds % 86400) / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      const parts = [
        days,
        fixSingleNumber(hours),
        fixSingleNumber(minutes),
        fixSingleNumber(seconds),
      ];

      if (parts[0] != 0 && props.onlyDay) {
        ref.current?.setNativeProps({
          text: parts[0] + esp.lang('market/countdown', 'days'),
        });
      } else if (parts[0] == 0) {
        const filteredParts = [...parts];
        while (filteredParts.length > 1 && (filteredParts[0] === 0 || filteredParts[0] === "00")) {
          filteredParts.splice(0, 1);
        }

        const filtered = filteredParts.map((d, i) =>
          `${d}${props?.hideTimeUnit ? '' : ' ' + labels[parts.length - filteredParts.length + i]}`
        );

        ref.current?.setNativeProps({ text: filtered.join(' : ') });
      } else if (props?.showDayUnit && props?.hideTimeUnit) {
        const data = parts.map(
          (d, i) => d + (i === 0 ? ' ' + labels[0] + ' ' : '')
        );

        const first = data[0];
        ref.current?.setNativeProps({
          text: first + ' ' + data.slice(1).join(' : '),
        });
      } else {
        const filtered = parts.map(
          (d, i) => `${d}${props?.hideTimeUnit ? '' : ' ' + labels[i]}`
        );
        ref.current?.setNativeProps({ text: filtered.join(' : ') });
      }

      if (!expired) timmerRef.current = setTimeout(loop, 1000);

    };
    loop()
  }

  return (
    <View style={props.containerStyle} >
      <TextInput ref={ref} editable={false} allowFontScaling={false} style={props.style} />
    </View>
  )
}