import { useEffect, useState } from "react";

function RecipeFormDrawer({ open, onClose, onSubmit }) {
  const [name, setName] = useState("");
  const [mealType, setMealType] = useState("lunch");
  const [timeMinutes, setTimeMinutes] = useState(15);
  const [tags, setTags] = useState("");

  const [ingredients, setIngredients] = useState([""]);
  const [steps, setSteps] = useState([""]);

  useEffect(() => {
    if (open) {
      setName("");
      setMealType("lunch");
      setTimeMinutes(15);
      setTags("");
      setIngredients([""]);
      setSteps([""]);
    }
  }, [open]);

  if (!open) return null;

  const handleAddIngredient = () => {
    setIngredients((prev) => [...prev, ""]);
  };

  const handleChangeIngredient = (idx, value) => {
    setIngredients((prev) => prev.map((v, i) => (i === idx ? value : v)));
  };

  const handleRemoveIngredient = (idx) => {
    setIngredients((prev) => prev.filter((_, i) => i !== idx || prev.length === 1));
  };

  const handleAddStep = () => {
    setSteps((prev) => [...prev, ""]);
  };

  const handleChangeStep = (idx, value) => {
    setSteps((prev) => prev.map((v, i) => (i === idx ? value : v)));
  };

  const handleRemoveStep = (idx) => {
    setSteps((prev) => prev.filter((_, i) => i !== idx || prev.length === 1));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const cleanIngredients = ingredients.map((s) => s.trim()).filter(Boolean);
    const cleanSteps = steps.map((s) => s.trim()).filter(Boolean);
    const tagsArr = tags
      .split(",")
      .map((t) => t.trim())
      .filter(Boolean);

    onSubmit({
      name,
      meal_type: mealType,
      time_minutes: Number(timeMinutes),
      tags: tagsArr,
      ingredients: cleanIngredients,
      steps: cleanSteps,
    });
  };

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <div className="drawer" onClick={(e) => e.stopPropagation()}>
        <header className="drawer-header">
          <h2>מתכון חדש</h2>
          <button className="icon-btn" onClick={onClose}>
            ✕
          </button>
        </header>

        <form className="drawer-body" onSubmit={handleSubmit}>
          <div className="field">
            <label>שם המתכון</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
              placeholder="שקשוקה חריפה, פסטה שמנת, חזה עוף בתנור..."
            />
          </div>

          <div className="two-cols">
            <div className="field">
              <label>סוג ארוחה</label>
              <select value={mealType} onChange={(e) => setMealType(e.target.value)}>
                <option value="breakfast">בוקר</option>
                <option value="lunch">צהריים</option>
                <option value="dinner">ערב</option>
                <option value="snack">נשנוש</option>
              </select>
            </div>

            <div className="field">
              <label>זמן הכנה (דקות)</label>
              <input
                type="number"
                min="1"
                value={timeMinutes}
                onChange={(e) => setTimeMinutes(e.target.value)}
                required
              />
            </div>
          </div>

          <div className="field">
            <label>תגיות (מופרד בפסיקים)</label>
            <input
              value={tags}
              onChange={(e) => setTags(e.target.value)}
              placeholder="מהיר, טבעוני, משפחתי..."
            />
          </div>

          <div className="field">
            <label>מצרכים</label>
            <div className="dynamic-list">
              {ingredients.map((val, idx) => (
                <div key={idx} className="dynamic-row">
                  <input
                    value={val}
                    onChange={(e) => handleChangeIngredient(idx, e.target.value)}
                    placeholder="למשל: 2 ביצים"
                  />
                  <button
                    type="button"
                    className="icon-btn small"
                    onClick={() => handleRemoveIngredient(idx)}
                  >
                    −
                  </button>
                </div>
              ))}
              <button
                type="button"
                className="btn ghost small"
                onClick={handleAddIngredient}
              >
                + הוספת מצרך
              </button>
            </div>
          </div>

          <div className="field">
            <label>שלבים</label>
            <div className="dynamic-list">
              {steps.map((val, idx) => (
                <div key={idx} className="dynamic-row">
                  <input
                    value={val}
                    onChange={(e) => handleChangeStep(idx, e.target.value)}
                    placeholder="למשל: לחמם את התנור ל־180 מעלות"
                  />
                  <button
                    type="button"
                    className="icon-btn small"
                    onClick={() => handleRemoveStep(idx)}
                  >
                    −
                  </button>
                </div>
              ))}
              <button
                type="button"
                className="btn ghost small"
                onClick={handleAddStep}
              >
                + הוספת שלב
              </button>
            </div>
          </div>

          <footer className="drawer-footer">
            <button type="button" className="btn ghost" onClick={onClose}>
              ביטול
            </button>
            <button type="submit" className="btn primary">
              שמירת מתכון
            </button>
          </footer>
        </form>
      </div>
    </div>
  );
}

export default RecipeFormDrawer;
