import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import type { Recipe } from '../services/api';
import { recipeApi } from '../services/api';
import './RecipeEdit.css';

interface FormData {
  title: string;
  description: string;
  category: string;
  servings: number;
  ingredients: string;
  preparation: string;
  instructions: string;
  comment: string;
}

const RecipeEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [recipe, setRecipe] = useState<Recipe | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  
  const [formData, setFormData] = useState<FormData>({
    title: '',
    description: '',
    category: '',
    servings: 1,
    ingredients: '',
    preparation: '',
    instructions: '',
    comment: '',
  });

  // Load recipe data
  useEffect(() => {
    const loadRecipe = async () => {
      if (!id) {
        setError('Keine Rezept-ID angegeben');
        setLoading(false);
        return;
      }

      try {
        setError(null);
        const response = await recipeApi.getRecipe(parseInt(id));
        
        if (response.success) {
          const recipeData = response.data;
          setRecipe(recipeData);
          setFormData({
            title: recipeData.title || '',
            description: recipeData.description || '',
            category: recipeData.category || '',
            servings: recipeData.servings || 1,
            ingredients: recipeData.ingredients || '',
            preparation: recipeData.preparation || '',
            instructions: recipeData.instructions || '',
            comment: recipeData.comment || '',
          });
        } else {
          setError('Rezept konnte nicht geladen werden');
        }
      } catch (err) {
        setError('Verbindungsfehler - Ist der Server gestartet?');
        console.error('Error loading recipe:', err);
      } finally {
        setLoading(false);
      }
    };

    loadRecipe();
  }, [id]);

  // Handle form field changes
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'servings' ? parseInt(value) || 1 : value
    }));
    
    // Clear messages when user starts typing
    if (error) setError(null);
    if (successMessage) setSuccessMessage(null);
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!id || !recipe) {
      setError('Rezept nicht gefunden');
      return;
    }

    // Basic validation
    if (!formData.title.trim()) {
      setError('Titel ist erforderlich');
      return;
    }

    if (formData.servings < 1 || formData.servings > 50) {
      setError('Portionen müssen zwischen 1 und 50 liegen');
      return;
    }

    setSaving(true);
    setError(null);
    setSuccessMessage(null);

    try {
      const updateData = {
        ...formData,
        title: formData.title.trim(),
        description: formData.description.trim() || undefined,
        category: formData.category.trim() || undefined,
        ingredients: formData.ingredients.trim() || undefined,
        preparation: formData.preparation.trim() || undefined,
        instructions: formData.instructions.trim() || undefined,
        comment: formData.comment.trim() || undefined,
      };

      const response = await recipeApi.updateRecipe(parseInt(id), updateData);
      
      if (response.success) {
        setSuccessMessage('Rezept erfolgreich gespeichert!');
        setRecipe(response.data);
        
        // Redirect after successful save
        setTimeout(() => {
          navigate(`/recipes/${id}`);
        }, 1500);
      } else {
        setError(response.message || 'Fehler beim Speichern des Rezepts');
      }
    } catch (err) {
      setError('Verbindungsfehler beim Speichern');
      console.error('Error updating recipe:', err);
    } finally {
      setSaving(false);
    }
  };

  // Handle cancel
  const handleCancel = () => {
    navigate(`/recipes/${id}`);
  };

  if (loading) {
    return (
      <div className="recipe-edit">
        <div className="loading">Lade Rezept...</div>
      </div>
    );
  }

  if (error && !recipe) {
    return (
      <div className="recipe-edit">
        <div className="error">
          <h3>Fehler</h3>
          <p>{error}</p>
          <div className="error-actions">
            <button onClick={() => window.location.reload()} className="retry-button">
              Erneut versuchen
            </button>
            <Link to="/" className="back-button">
              Zurück zur Liste
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="recipe-edit">
      {/* Header */}
      <div className="recipe-edit-header">
        <div className="breadcrumb">
          <Link to="/" className="breadcrumb-link">Alle Rezepte</Link>
          <span className="breadcrumb-separator">›</span>
          <Link to={`/recipes/${id}`} className="breadcrumb-link">{recipe?.title}</Link>
          <span className="breadcrumb-separator">›</span>
          <span className="breadcrumb-current">Bearbeiten</span>
        </div>
        
        <h1>Rezept bearbeiten</h1>
      </div>

      {/* Messages */}
      {error && (
        <div className="message error-message">
          <span className="message-icon">⚠️</span>
          <span className="message-text">{error}</span>
        </div>
      )}

      {successMessage && (
        <div className="message success-message">
          <span className="message-icon">✅</span>
          <span className="message-text">{successMessage}</span>
        </div>
      )}

      {/* Form */}
      <form onSubmit={handleSubmit} className="recipe-form">
        <div className="form-grid">
          {/* Left Column - Basic Info */}
          <div className="form-section">
            <h3>Grundinformationen</h3>
            
            <div className="form-group">
              <label htmlFor="title" className="required">Titel</label>
              <input
                type="text"
                id="title"
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                placeholder="z.B. Pasta Gamberoni"
                maxLength={200}
                required
              />
            </div>

            <div className="form-row">
              <div className="form-group">
                <label htmlFor="category">Kategorie</label>
                <select
                  id="category"
                  name="category"
                  value={formData.category}
                  onChange={handleInputChange}
                >
                  <option value="">Kategorie wählen</option>
                  <option value="Vegan">Vegan</option>
                  <option value="Vegetarisch">Vegetarisch</option>
                  <option value="Fleisch">Fleisch</option>
                  <option value="Fisch">Fisch</option>
                  <option value="Fisch, Garnelen">Fisch, Garnelen</option>
                  <option value="Dessert">Dessert</option>
                  <option value="Suppe">Suppe</option>
                  <option value="Salat">Salat</option>
                  <option value="Beilage">Beilage</option>
                </select>
              </div>

              <div className="form-group">
                <label htmlFor="servings" className="required">Portionen</label>
                <input
                  type="number"
                  id="servings"
                  name="servings"
                  value={formData.servings}
                  onChange={handleInputChange}
                  min="1"
                  max="50"
                  required
                />
              </div>
            </div>

            <div className="form-group">
              <label htmlFor="description">Beschreibung</label>
              <textarea
                id="description"
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                placeholder="Kurze Beschreibung des Rezepts..."
                rows={4}
                maxLength={1000}
              />
            </div>
          </div>

          {/* Right Column - Recipe Content */}
          <div className="form-section">
            <h3>Rezeptinhalt</h3>
            
            <div className="form-group">
              <label htmlFor="ingredients">Zutaten</label>
              <textarea
                id="ingredients"
                name="ingredients"
                value={formData.ingredients}
                onChange={handleInputChange}
                placeholder="Eine Zutat pro Zeile, z.B.&#10;200g Pasta&#10;400g Garnelen&#10;2 Knoblauchzehen"
                rows={8}
                maxLength={5000}
              />
              <div className="form-hint">
                Eine Zutat pro Zeile eingeben
              </div>
            </div>

            <div className="form-group">
              <label htmlFor="preparation">Vorbereitung</label>
              <textarea
                id="preparation"
                name="preparation"
                value={formData.preparation}
                onChange={handleInputChange}
                placeholder="Vorbereitungsschritte, z.B.&#10;Garnelen putzen&#10;Knoblauch schneiden"
                rows={6}
                maxLength={3000}
              />
            </div>

            <div className="form-group">
              <label htmlFor="instructions">Zubereitung</label>
              <textarea
                id="instructions"
                name="instructions"
                value={formData.instructions}
                onChange={handleInputChange}
                placeholder="Detaillierte Zubereitungsschritte..."
                rows={10}
                maxLength={10000}
              />
              <div className="form-hint">
                Jeden Schritt in einer neuen Zeile beschreiben
              </div>
            </div>

            <div className="form-group">
              <label htmlFor="comment">Tipps & Hinweise</label>
              <textarea
                id="comment"
                name="comment"
                value={formData.comment}
                onChange={handleInputChange}
                placeholder="Zusätzliche Tipps oder Hinweise..."
                rows={4}
                maxLength={2000}
              />
            </div>
          </div>
        </div>

        {/* Form Actions */}
        <div className="form-actions">
          <button 
            type="button" 
            onClick={handleCancel}
            className="cancel-button"
            disabled={saving}
          >
            Abbrechen
          </button>
          
          <button 
            type="submit" 
            className="save-button"
            disabled={saving}
          >
            {saving ? (
              <>
                <span className="loading-spinner"></span>
                Speichert...
              </>
            ) : (
              <>
                💾 Speichern
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default RecipeEdit;