import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { recipeApi, imageApi } from '../services/api';
import FileUpload from './FileUpload';
import './RecipeEdit.css'; // Reuse the same styles

const RecipeCreate: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  // Form state
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    category: '',
    servings: 4,
    ingredients: '',
    preparation: '',
    instructions: '',
    comment: '',
    recipeNumber: ''
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'servings' ? parseInt(value) || 1 : value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      // Validation
      if (!formData.title.trim()) {
        throw new Error('Titel ist erforderlich');
      }

      // First create the recipe
      const response = await recipeApi.createRecipe(formData);
      
      if (response.success) {
        const recipeId = response.data.id;
        
        // Upload images if any were selected
        if (selectedFiles.length > 0) {
          try {
            await imageApi.uploadImages(recipeId, selectedFiles, setUploadProgress);
          } catch (uploadError) {
            console.warn('Image upload failed:', uploadError);
            // Don't fail the entire process if image upload fails
          }
        }
        
        setSuccess(true);
        // Redirect to the new recipe detail page after a short delay
        setTimeout(() => {
          navigate(`/recipes/${recipeId}`);
        }, 1500);
      } else {
        setError('Fehler beim Erstellen des Rezepts');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler');
      console.error('Error creating recipe:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleFilesSelected = (files: File[]) => {
    setSelectedFiles(files);
  };

  if (success) {
    return (
      <div className="recipe-edit">
        <div className="success-message">
          <h2>✅ Rezept erfolgreich erstellt!</h2>
          <p>Sie werden zur Rezept-Detailseite weitergeleitet...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="recipe-edit">
      {/* Header */}
      <div className="recipe-header">
        <div className="breadcrumb">
          <Link to="/" className="breadcrumb-link">Alle Rezepte</Link>
          <span className="breadcrumb-separator">›</span>
          <span className="breadcrumb-current">Neues Rezept</span>
        </div>
        
        <div className="recipe-actions">
          <button onClick={() => navigate(-1)} className="back-button">
            ← Zurück
          </button>
        </div>
      </div>

      {/* Form */}
      <div className="recipe-form-container">
        <form onSubmit={handleSubmit} className="recipe-form">
          <h1>Neues Rezept erstellen</h1>

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

          <div className="form-row">
            {/* Left Column */}
            <div className="form-column">
              <div className="form-group">
                <label htmlFor="title">Titel *</label>
                <input
                  type="text"
                  id="title"
                  name="title"
                  value={formData.title}
                  onChange={handleInputChange}
                  placeholder="Name des Rezepts..."
                  required
                />
              </div>

              <div className="form-group">
                <label htmlFor="recipeNumber">Rezeptnummer</label>
                <input
                  type="text"
                  id="recipeNumber"
                  name="recipeNumber"
                  value={formData.recipeNumber}
                  onChange={handleInputChange}
                  placeholder="z.B. R031"
                />
              </div>

              <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="Vorspeise">Vorspeise</option>
                  <option value="Hauptgericht">Hauptgericht</option>
                  <option value="Nachspeise">Nachspeise</option>
                  <option value="Beilage">Beilage</option>
                  <option value="Suppe">Suppe</option>
                  <option value="Salat">Salat</option>
                  <option value="Fleisch">Fleisch</option>
                  <option value="Fisch">Fisch</option>
                  <option value="Vegetarisch">Vegetarisch</option>
                  <option value="Vegan">Vegan</option>
                  <option value="Dessert">Dessert</option>
                  <option value="Getränk">Getränk</option>
                </select>
              </div>

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

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

              <div className="form-group">
                <label htmlFor="ingredients">Zutaten</label>
                <textarea
                  id="ingredients"
                  name="ingredients"
                  value={formData.ingredients}
                  onChange={handleInputChange}
                  rows={8}
                  placeholder="Eine Zutat pro Zeile...&#10;z.B.:&#10;500g Mehl&#10;2 Eier&#10;250ml Milch"
                />
              </div>
            </div>

            {/* Right Column - now empty or for other content */}
            <div className="form-column">
              {/* Right column is now available for other fields if needed */}
            </div>
          </div>

          {/* Full Width Sections */}
          <div className="form-group">
            <label htmlFor="preparation">Vorbereitung</label>
            <textarea
              id="preparation"
              name="preparation"
              value={formData.preparation}
              onChange={handleInputChange}
              rows={4}
              placeholder="Vorbereitungsschritte..."
            />
          </div>

          <div className="form-group">
            <label htmlFor="instructions">Zubereitung</label>
            <textarea
              id="instructions"
              name="instructions"
              value={formData.instructions}
              onChange={handleInputChange}
              rows={8}
              placeholder="Detaillierte Zubereitungsschritte...&#10;Ein Schritt pro Zeile für optimale Darstellung mit Bildern."
            />
          </div>

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

          {/* Image Upload Section */}
          <div className="form-group">
            <label>Bilder hochladen</label>
            <p className="form-hint">
              Laden Sie Bilder für Ihr Rezept hoch. Das erste Bild wird als Hauptbild verwendet, 
              weitere Bilder werden den Zubereitungsschritten zugeordnet.
            </p>
            <FileUpload
              onFilesSelected={handleFilesSelected}
              maxFiles={10}
              maxFileSize={5}
              disabled={loading}
            />
            {uploadProgress > 0 && uploadProgress < 100 && (
              <div className="upload-progress">
                <div className="upload-progress-bar" style={{ width: `${uploadProgress}%` }}></div>
                <span className="upload-progress-text">{uploadProgress}% hochgeladen</span>
              </div>
            )}
          </div>

          {/* Form Actions */}
          <div className="form-actions">
            <button
              type="button"
              onClick={() => navigate('/')}
              className="cancel-button"
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={loading}
              className="save-button"
            >
              {loading ? 'Wird erstellt...' : 'Rezept erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default RecipeCreate;