import DateTimePicker from '@react-native-community/datetimepicker';
import React, { useEffect, useState, useCallback } from 'react';
import { TouchableOpacity, View } from 'react-native';
import formatTime from 'date-fns/fp/format';

import BottomSheet from '../BottomSheet';
import TextInput from '../TextInput';
import Button from '../Button';
import { StyledPickerWrapper } from './StyledTimePicker';
import type { TimePickerProps } from './types';
import { useTheme } from '../../theme';

const TimePickerIOS = ({
  value,
  label,
  placeholder,
  onChange,
  confirmLabel,
  displayFormat = 'hh:mm aa',
  disabled = false,
  required,
  error,
  helpText,
  style,
  testID,
  showSuffix = true,
  supportedOrientations = ['portrait'],
}: TimePickerProps) => {
  const [selectingDate, setSelectingDate] = useState<Date>(value || new Date());
  const [open, setOpen] = useState(false);

  const is12Hour = displayFormat.includes('hh');
  const displayValue = value ? formatTime(displayFormat, value) : '';
  const theme = useTheme();

  // Determine locale based on time format preference
  // For 12-hour format: use en-US locale to ensure 12-hour display regardless of device settings
  // For 24-hour format: use en-GB for consistent 24-hour display
  const pickerLocale = is12Hour ? 'en-US' : 'en-GB';

  useEffect(() => {
    setSelectingDate(value || new Date());
  }, [value]);

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

  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled}
      testID="time-picker-ios-touchable-opacity"
    >
      <View pointerEvents="none" testID="timePickerInputIOS">
        <TextInput
          label={label}
          value={displayValue}
          suffix={showSuffix ? 'clock-3' : undefined}
          placeholder={placeholder || displayFormat}
          disabled={disabled}
          error={error}
          required={required}
          helpText={helpText}
          testID={testID}
          style={style}
        />
      </View>
      <BottomSheet
        open={open}
        onRequestClose={() => setOpen(false)}
        header={label}
        footer={
          <Button
            variant="text"
            text={confirmLabel}
            onPress={() => {
              if (selectingDate) {
                onChange(selectingDate);
              }
              setOpen(false);
            }}
          />
        }
        supportedOrientations={supportedOrientations}
      >
        <StyledPickerWrapper>
          <DateTimePicker
            testID="timePickerIOS"
            value={selectingDate}
            mode="time"
            locale={pickerLocale}
            onChange={(_: any, date: Date | undefined) => {
              if (date) {
                setSelectingDate(date);
              }
            }}
            display="spinner"
            style={{ flex: 1 }}
            textColor={theme.colors.onDefaultGlobalSurface}
          />
        </StyledPickerWrapper>
      </BottomSheet>
    </TouchableOpacity>
  );
};

export default TimePickerIOS;
