import { useEffect, useState } from "react";
import placeholderLight from "../assets/placeholder-light.png";
import placeholderDark from "../assets/placeholder-dark.png";

function RecipeDetails({ recipe, onEditClick, onDeleteClick, onShowDeleteModal, isAuthenticated, currentUser }) {
  const [theme, setTheme] = useState(document.documentElement.getAttribute('data-theme') || 'dark');
  
  useEffect(() => {
    const observer = new MutationObserver(() => {
      setTheme(document.documentElement.getAttribute('data-theme') || 'dark');
    });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => observer.disconnect();
  }, []);
  
  const placeholderImage = theme === 'dark' ? placeholderDark : placeholderLight;
  if (!recipe) {
    return (
      <section className="panel placeholder">
        <p>עדיין לא נבחר מתכון. בחר מתכון מהרשימה או צור מתכון חדש.</p>
      </section>
    );
  }

  const handleDelete = () => {
    onShowDeleteModal(recipe.id, recipe.name);
  };

  // Debug ownership check
  console.log('Recipe ownership check:', {
    recipeUserId: recipe.user_id,
    recipeUserIdType: typeof recipe.user_id,
    currentUserId: currentUser?.id,
    currentUserIdType: typeof currentUser?.id,
    isEqual: recipe.user_id === currentUser?.id
  });

  return (
    <section className="panel recipe-card">
      {/* Recipe Image */}
      <div className="recipe-image-container">
        <img src={recipe.image || placeholderImage} alt={recipe.name} className="recipe-image" />
      </div>

      <header className="recipe-header">
        <div>
          <h2>{recipe.name}</h2>
          <p className="recipe-subtitle">
            {translateMealType(recipe.meal_type)} · {recipe.time_minutes} דקות הכנה
          </p>
          {(recipe.made_by || recipe.owner_display_name) && (
            <h4 className="recipe-made-by">המתכון של: {recipe.made_by || recipe.owner_display_name}</h4>
          )}
        </div>
        <div className="pill-row">
          <span className="pill">⏱ {recipe.time_minutes} דק׳</span>
          <span className="pill">🍽 {translateMealType(recipe.meal_type)}</span>
        </div>
      </header>

      <div className="recipe-body">
        <div className="recipe-column">
          <h3>מצרכים</h3>
          <ul>
            {recipe.ingredients.map((ing, idx) => (
              <li key={idx}>{ing}</li>
            ))}
          </ul>
        </div>

        <div className="recipe-column">
          <h3>שלבים</h3>
          <ol>
            {recipe.steps.map((step, idx) => (
              <li key={idx}>{step}</li>
            ))}
          </ol>
        </div>
      </div>

      {recipe.tags && recipe.tags.length > 0 && (
        <footer className="tags">
          {recipe.tags.map((tag, idx) => (
            <span key={idx} className="tag">
              #{tag}
            </span>
          ))}
        </footer>
      )}

      {isAuthenticated && currentUser && (Number(recipe.user_id) === Number(currentUser.id) || currentUser.is_admin) && (
        <div className="recipe-actions">
          <button className="btn ghost small" onClick={() => onEditClick(recipe)}>
            ✏️ ערוך
          </button>
          <button className="btn ghost small" onClick={handleDelete}>
            🗑 מחק
          </button>
        </div>
      )}
    </section>
  );
}

function translateMealType(type) {
  switch (type) {
    case "breakfast":
      return "בוקר";
    case "lunch":
      return "צהריים";
    case "dinner":
      return "ערב";
    case "snack":
      return "קינוחים";
    default:
      return type;
  }
}

export default RecipeDetails;
