import { useState, useEffect, useMemo } from 'react';
import BaseModal from '../BaseModal';

function ScheduleItemModal({ date, hour, plannableItems, onSchedule, onClose }) {
  const [selectedItemId, setSelectedItemId] = useState('');
  const [startTime, setStartTime] = useState('');
  const [endTime, setEndTime] = useState('');
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    // Set default times based on the clicked hour
    const startHour = hour.toString().padStart(2, '0');
    const endHour = (hour + 1).toString().padStart(2, '0');
    setStartTime(`${startHour}:00`);
    setEndTime(`${endHour}:00`);
  }, [hour]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (!selectedItemId) {
      setError('Please select an item to schedule');
      return;
    }

    if (!startTime || !endTime) {
      setError('Please select start and end times');
      return;
    }

    // Construct full datetime strings
    const dateString = date.toISOString().split('T')[0];
    const startDatetime = `${dateString} ${startTime}:00`;
    const endDatetime = `${dateString} ${endTime}:00`;

    // Validate end time is after start time
    if (endTime <= startTime) {
      setError('End time must be after start time');
      return;
    }

    try {
      setSubmitting(true);
      await onSchedule(selectedItemId, startDatetime, endDatetime);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to schedule item');
    } finally {
      setSubmitting(false);
    }
  };

  // Generate time options (every 30 minutes) - memoized to avoid recreation
  const timeOptions = useMemo(() => {
    const options = [];
    for (let h = 0; h < 24; h++) {
      for (let m = 0; m < 60; m += 30) {
        const timeStr = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
        options.push(timeStr);
      }
    }
    return options;
  }, []);

  return (
    <BaseModal onClose={onClose} title="Schedule Item">
      <form onSubmit={handleSubmit} className="space-y-4">
        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-2 rounded">
            {error}
          </div>
        )}

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Select Item
          </label>
          <select
            value={selectedItemId}
            onChange={(e) => setSelectedItemId(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          >
            <option value="">-- Choose an item --</option>
            {plannableItems.map(item => (
              <option key={item.id} value={item.id}>
                {item.name} {item.type ? `(${item.type})` : ''}
              </option>
            ))}
          </select>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Start Time
            </label>
            <select
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              {timeOptions.map(time => (
                <option key={time} value={time}>
                  {time}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              End Time
            </label>
            <select
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              {timeOptions.map(time => (
                <option key={time} value={time}>
                  {time}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div className="flex justify-end gap-2 pt-4">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-gray-700 bg-gray-100 rounded hover:bg-gray-200 transition-colors"
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="submit"
            className="px-4 py-2 text-white bg-blue-600 rounded hover:bg-blue-700 transition-colors disabled:bg-blue-300"
            disabled={submitting}
          >
            {submitting ? 'Scheduling...' : 'Schedule'}
          </button>
        </div>
      </form>
    </BaseModal>
  );
}

export default ScheduleItemModal;
