import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { EventDraft, persistEvent } from '../../lib/api/endpoints';
import LoadingSpinner from '../../components/ui/LoadingSpinner';
import './EditEvent.css';

interface EditEventParams {
  id: string;
}

const EditEvent: React.FC = () => {
  const params = useParams<{ id: string }>();
  const id = params.id;
  const navigate = useNavigate();
  
  const [eventDraft, setEventDraft] = useState<EventDraft | null>(null);
  const [loading, setLoading] = useState(true);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [startDate, setStartDate] = useState('');
  const [startTime, setStartTime] = useState('');
  const [endDate, setEndDate] = useState('');
  const [endTime, setEndTime] = useState('');
  const [allDay, setAllDay] = useState(false);

  useEffect(() => {
    // Try to load draft data from sessionStorage
    const draftData = sessionStorage.getItem('editingEventDraft');
    
    if (draftData) {
      try {
        const draft = JSON.parse(draftData) as EventDraft;
        setEventDraft(draft);
        
        // Set form values
        setTitle(draft.title);
        setDescription(draft.description || '');
        
        if (draft.start) {
          const startDateTime = new Date(draft.start);
          setStartDate(formatDateForInput(startDateTime));
          setStartTime(formatTimeForInput(startDateTime));
        }
        
        if (draft.end) {
          const endDateTime = new Date(draft.end);
          setEndDate(formatDateForInput(endDateTime));
          setEndTime(formatTimeForInput(endDateTime));
        }
        
        setAllDay(draft.allDay);
      } catch (error) {
        console.error('Error parsing draft data:', error);
      }
    } else {
      console.error('No event draft data found in session storage');
      // Redirect back to home if no draft data is found
      setTimeout(() => navigate('/'), 500);
    }
    
    setLoading(false);
  }, [id, navigate]);

  const formatDateForInput = (date: Date): string => {
    return date.toISOString().split('T')[0];
  };

  const formatTimeForInput = (date: Date): string => {
    return date.toTimeString().slice(0, 5);
  };

  const formatForServer = (date: string, time: string): string => {
    return `${date}T${time}:00`;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!title) {
      alert('Bitte geben Sie einen Titel ein');
      return;
    }
    
    try {
      setLoading(true);
      
      const eventData = {
        draft: {
          id: id || '',
          title,
          description,
          start: startDate ? formatForServer(startDate, startTime || '00:00') : new Date().toISOString(),
          end: endDate ? formatForServer(endDate, endTime || '00:00') : new Date().toISOString(),
          allDay
        }
      };
      
      const savedEvent = await persistEvent(eventData);
      console.log('Event created:', savedEvent);
      
      // Clear the draft from sessionStorage
      sessionStorage.removeItem('editingEventDraft');
      
      // Redirect back to home page after successful save
      navigate('/');
    } catch (error) {
      console.error('Error saving event:', error);
      setLoading(false);
      alert('Fehler beim Speichern des Termins');
    }
  };

  const handleCancel = () => {
    // Clear the draft data when canceling
    sessionStorage.removeItem('editingEventDraft');
    // Navigate back to home
    navigate('/');
  };

  if (loading) {
    return <LoadingSpinner message="Lade Termin..." size="large" />;
  }

  return (
    <div className="edit-event-container">
      <h1 className="edit-event-title">Termin bearbeiten</h1>
      
      <form className="edit-event-form" onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="title">Titel</label>
          <input
            type="text"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />
        </div>
        
        <div className="form-group">
          <label htmlFor="description">Beschreibung</label>
          <textarea
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={4}
          />
        </div>
        
        <div className="form-group form-checkbox">
          <input
            type="checkbox"
            id="allDay"
            checked={allDay}
            onChange={(e) => setAllDay(e.target.checked)}
          />
          <label htmlFor="allDay">Ganztägig</label>
        </div>
        
        <div className="form-row">
          <div className="form-group">
            <label htmlFor="startDate">Startdatum</label>
            <input
              type="date"
              id="startDate"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
            />
          </div>
          
          {!allDay && (
            <div className="form-group">
              <label htmlFor="startTime">Startzeit</label>
              <input
                type="time"
                id="startTime"
                value={startTime}
                onChange={(e) => setStartTime(e.target.value)}
              />
            </div>
          )}
        </div>
        
        <div className="form-row">
          <div className="form-group">
            <label htmlFor="endDate">Enddatum</label>
            <input
              type="date"
              id="endDate"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
            />
          </div>
          
          {!allDay && (
            <div className="form-group">
              <label htmlFor="endTime">Endzeit</label>
              <input
                type="time"
                id="endTime"
                value={endTime}
                onChange={(e) => setEndTime(e.target.value)}
              />
            </div>
          )}
        </div>
        
        <div className="edit-event-actions">
          <button type="button" className="cancel-button" onClick={handleCancel}>
            Abbrechen
          </button>
          <button type="submit" className="save-button">
            Speichern
          </button>
        </div>
      </form>
    </div>
  );
};

export default EditEvent; 