import React, { useEffect, useState } from 'react';
import { TextInput, TouchableOpacity } from 'react-native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import Colors from '../../constants/colors';
import CommonStyles from '../../constants/CommonStyles';

interface FormikDatePickerProps {
  field: { name: string; value?: any };
  setFieldValue: (field: string, value: any) => void;
  mode?: 'date' | 'time' | 'datetime';
  placeholder?: string;
  minDate?: Date;
  maxDate?: Date;
  startDate?: Date | 'false';
}

const FormikDatePicker: React.FC<FormikDatePickerProps> = ({
  field,
  setFieldValue,
  mode = 'date',
  placeholder = 'Select date',
  minDate,
  maxDate,
  startDate,
}) => {
  const [isPickerVisible, setPickerVisible] = useState(false);
  const [displayDate, setDisplayDate] = useState<string>('');

  useEffect(() => {
    // If field already has value, format it for display
    if (field.value) {
      const dateObj = new Date(field.value);
      setDisplayDate(formatDate(dateObj));
    }
  }, [field.value]);

  const formatDate = (date: Date) => {
    if (mode === 'time') {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
    return `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
  };

  const handleConfirm = (selectedDate: Date) => {
    setPickerVisible(false);
    setDisplayDate(formatDate(selectedDate));
    setFieldValue(field.name, selectedDate);
  };

  const handlePress = () => {
    if (startDate === 'false') {
      alert('Please Select Start Date');
    } else {
      setPickerVisible(true);
    }
  };

  return (
    <>
      <TouchableOpacity onPress={handlePress}>
        <TextInput
          editable={false}
          pointerEvents="none"
          style={[CommonStyles.textInput]}
          placeholder={placeholder}
          placeholderTextColor={Colors.colorPlaceholder}
          value={displayDate}
        />
      </TouchableOpacity>

      <DateTimePickerModal
        isVisible={isPickerVisible}
        mode={mode}
        textColor={Colors.textColor}
        maximumDate={maxDate}
        minimumDate={
        minDate
            ? minDate
            : startDate && startDate !== 'false'
            ? new Date(startDate)
            : undefined
        }
       onConfirm={handleConfirm}
        onCancel={() => setPickerVisible(false)}
      />
    </>
  );
};

export { FormikDatePicker };
