import React, { useState } from 'react';

function FutureTimeForm({ scheduledTime, setScheduledTime }) {
  const [selectedTime, setSelectedTime] = useState(new Date());
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleTimeChange = (e) => {
    setSelectedTime(e.target.value);
    setScheduledTime(new Date(e.target.value));
    setError('');
    setSuccess('');
  };

  const validateAndSubmit = (e) => {
    e.preventDefault();

    if (!selectedTime) {
      setError('Please select a date and time.');
      return;
    }

    const now = new Date();
    const inputDate = new Date(selectedTime);

    // Calculate the minimum allowed time (Now + 10 minutes)
    const minAllowedTime = new Date(now.getTime() + 10 * 60000);

    if (inputDate < minAllowedTime) {
      setError('The time must be at least 10 minutes in the future.');
      setSuccess('');
      setScheduledTime(null);
    } else {
      setError('');
      setSuccess('Time validated successfully!');
      setScheduledTime(inputDate);
    }
  };

  return (
    <div
      style={{ maxWidth: '400px', margin: '2rem auto', fontFamily: 'Arial' }}
    >
      <h2>Schedule Event</h2>
      <form onSubmit={validateAndSubmit}>
        <div style={{ marginBottom: '1rem' }}>
          <label
            htmlFor="future-time"
            style={{ display: 'block', marginBottom: '0.5rem' }}
          >
            Select Date and Time:
          </label>
          <input
            type="datetime-local"
            id="future-time"
            value={selectedTime}
            onChange={handleTimeChange}
            style={{
              padding: '8px',
              width: '100%',
              borderColor: error ? 'red' : '#ccc',
            }}
          />
        </div>

        {error && <p style={{ color: 'red', fontSize: '0.9rem' }}>{error}</p>}
        {success && (
          <p style={{ color: 'green', fontSize: '0.9rem' }}>{success}</p>
        )}

        <button
          type="submit"
          style={{
            padding: '10px 20px',
            backgroundColor: '#007BFF',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
          }}
        >
          Submit
        </button>
      </form>
    </div>
  );
}

export default FutureTimeForm;
