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


export interface EventCountdown_baseArgs {

}
export interface EventCountdown_baseProps {
  expired: string,
  timezone?: string,
  expiredText?: string,
  style?: any,
  containerStyle?: any,
  onlyDay?: boolean
  onExpired?: () => void
  hideTimeUnit?: boolean
  showDayUnit?: boolean
}

const fixSingleNumber = (number: number) => number < 10 ? '0' + number : number

function parseTimezone(tz: string): string {
  if (!tz) return '+00:00';
  const lower = tz.toLowerCase().trim();

  const match = lower.match(/gmt([+-]\d{1,2})(?::?(\d{1,2}))?(\.\d+)?/);
  if (!match) return '+00:00';

  const sign = match[1].startsWith('-') ? '-' : '+';
  let hours = Math.abs(parseInt(match[1], 10));
  let minutes = 0;

  if (match[2]) {
    minutes = parseInt(match[2], 10);
  } else if (match[3]) {
    minutes = Math.round(parseFloat(match[3]) * 60);
  }

  const hh = hours.toString().padStart(2, '0');
  const mm = minutes.toString().padStart(2, '0');
  return `${sign}${hh}:${mm}`;
}

export default function m(props: EventCountdown_baseProps): any {
  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")]

      // @ts-ignore
      const configGMT = esp.config("forcedGMT+") ? `GMT+${esp.config("forcedGMT+")}` : "GMT+7" // set default to GMT+7 Jakarta
      const tzOffset = parseTimezone(props?.timezone || configGMT);
      const serverDate = new Date(props.expired.replace(' ', 'T') + tzOffset);
      const now = new Date();

      const diffMs = serverDate.getTime() - now.getTime();

      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>
  )
}