import React, { useState, useCallback } from 'react';
import { 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 { StyledTouchableOpacity } from './StyledDatePicker';
import type { InternalDatePickerProps } from './types';

type DatePickerIOSProps = Omit<
  InternalDatePickerProps,
  '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,
  TextInputComponent,
  inputProps,
  groupStyleEnabled = false,
}: DatePickerIOSProps) => {
  const [open, setOpen] = useState(false);
  const { lang: defaultLocale } = useLocale();
  const { displayValue, format } = useFormatDate({
    displayFormat,
    locale,
    value,
  });

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

  const InputComponent = TextInputComponent || TextInput;

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

  return (
    <StyledTouchableOpacity
      onPress={onPress}
      disabled={disabled}
      themeGroupStyleEnabled={groupStyleEnabled}
      themeHasError={!!error}
      testID="date-picker-ios-touchable-opacity"
    >
      <View pointerEvents="none" testID="datePickerInputIOS">
        <InputComponent
          {...inputProps}
          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
              ? (props) =>
                  renderSelectedValue(
                    {
                      date: value,
                      formattedDateString: displayValue,
                    },
                    props
                  )
              : 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}
      />
    </StyledTouchableOpacity>
  );
};

export default DatePickerIOS;
