import React, { useState, useCallback } from 'react';
import { TouchableOpacity, View } from 'react-native';

import { useLocale } from '../LocaleProvider/hooks';
import TextInput from '../TextInput';
import IOSDatePickerDialog from './Dialog/IOSDialog';
import useCalculateDate from './hooks/useCalculateDate';
import useFormatDate from './hooks/useFormatDate';
import type { DatePickerProps } from './types';

type DatePickerIOSProps = Omit<
  DatePickerProps,
  'variant' | 'monthPickerConfirmLabel' | 'monthPickerCancelLabel'
> & {
  variant?: 'default' | 'month-year';
};
const DatePickerIOS = ({
  value,
  minDate,
  maxDate,
  label,
  placeholder,
  onChange,
  confirmLabel,
  displayFormat,
  disabled = false,
  required,
  error,
  helpText,
  style,
  testID,
  supportedOrientations = ['portrait'],
  variant = 'default',
  locale,
  renderSelectedValue,
}: DatePickerIOSProps) => {
  const [open, setOpen] = useState(false);
  const { lang: defaultLocale } = useLocale();
  const { displayValue, format } = useFormatDate({
    displayFormat,
    locale,
    value,
  });

  useCalculateDate({ minDate, maxDate, onChange, value });

  const onPress = useCallback(() => {
    setOpen(true);
  }, []);

  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled}
      testID="date-picker-ios-touchable-opacity"
    >
      <View pointerEvents="none" testID="datePickerInputIOS">
        <TextInput
          label={label}
          value={displayValue}
          suffix="calendar-dates-outlined"
          placeholder={placeholder || format}
          disabled={disabled}
          error={error}
          required={required}
          helpText={helpText}
          testID={testID}
          style={style}
          renderInputValue={
            renderSelectedValue !== undefined && !!value
              ? (inputProps) =>
                  renderSelectedValue(
                    {
                      date: value,
                      formattedDateString: displayValue,
                    },
                    inputProps
                  )
              : undefined
          }
        />
      </View>
      <IOSDatePickerDialog
        value={value}
        onChange={onChange}
        open={open}
        onClose={() => setOpen(false)}
        confirmLabel={confirmLabel}
        locale={locale || defaultLocale}
        supportedOrientations={supportedOrientations}
        variant={variant}
        label={label}
        minDate={minDate}
        maxDate={maxDate}
      />
    </TouchableOpacity>
  );
};

export default DatePickerIOS;
