import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { deleteRecipe, getRecipe, pdfDownloadUrl, uploadedImageUrl } from "../api/client";
import type { Recipe } from "../types/recipe";

const TIMING_LABELS: { key: keyof Recipe; label: string }[] = [
  { key: "preptime", label: "Vorbereitung" },
  { key: "cooktime", label: "Kochzeit" },
  { key: "baketime", label: "Backzeit" },
  { key: "cooltime", label: "Kühlzeit" },
  { key: "marinade_time", label: "Marinierzeit" },
  { key: "robot_time", label: "Küchenmaschine" },
  { key: "servings", label: "Portionen" },
];

export default function RecipeDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [recipe, setRecipe] = useState<Recipe | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);

  useEffect(() => {
    if (!id) return;
    getRecipe(Number(id)).then(setRecipe).catch((e) => setError(e.message));
  }, [id]);

  if (error) return <p className="error">{error}</p>;
  if (!recipe) return <p>Lädt…</p>;

  const timingParts = TIMING_LABELS.filter(({ key }) => recipe[key]);

  async function handleDelete() {
    if (!recipe || !confirm(`"${recipe.name}" wirklich löschen?`)) return;
    await deleteRecipe(recipe.id);
    navigate("/");
  }

  async function handleDownload() {
    if (!recipe) return;
    setDownloading(true);
    setError(null);
    try {
      const res = await fetch(pdfDownloadUrl(recipe.id));
      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.detail ?? `PDF-Erstellung fehlgeschlagen (${res.status})`);
      }
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${recipe.slug}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setDownloading(false);
    }
  }

  return (
    <div className="page">
      <div className="page-header">
        <h1>{recipe.name}</h1>
        <div className="actions">
          <button className="button primary" onClick={handleDownload} disabled={downloading}>
            {downloading ? "Erstelle PDF…" : "PDF herunterladen"}
          </button>
          <Link className="button" to={`/recipes/${recipe.id}/edit`}>Bearbeiten</Link>
          <button className="button danger" onClick={handleDelete}>Löschen</button>
        </div>
      </div>

      {error && <p className="error">{error}</p>}

      {recipe.image_filename && (
        <img className="detail-image" src={uploadedImageUrl(recipe.image_filename)} alt="" />
      )}

      {recipe.category && <p className="tag">{recipe.category}</p>}

      {timingParts.length > 0 && (
        <div className="timing-summary">
          {timingParts.map(({ key, label }) => (
            <span key={key}><strong>{label}:</strong> {recipe[key] as string}</span>
          ))}
        </div>
      )}

      <div className="detail-columns">
        <div>
          <h2>Zutaten</h2>
          <ul className="ingredient-list">
            {recipe.ingredients.map((ing) =>
              ing.kind === "section_header" ? (
                <li key={ing.id} className="section-header">{ing.text}</li>
              ) : (
                <li key={ing.id}>
                  <span className="qty">{[ing.quantity, ing.unit].filter(Boolean).join(" ")}</span>
                  <span>{ing.text}</span>
                </li>
              ),
            )}
          </ul>
          {recipe.notes && (
            <>
              <h2>Notizen</h2>
              <p className="notes">{recipe.notes}</p>
            </>
          )}
        </div>

        <div>
          <h2>Zubereitung</h2>
          <ol className="step-list">
            {recipe.steps.map((step) => (
              <li key={step.id}>{step.text}</li>
            ))}
          </ol>
        </div>
      </div>

      {(recipe.kcal || recipe.kh || recipe.protein || recipe.fett) && (
        <div className="nutrition-summary">
          {recipe.kcal && <span>Kalorien: {recipe.kcal}</span>}
          {recipe.kh && <span>Kohlenhydrate: {recipe.kh}</span>}
          {recipe.protein && <span>Protein: {recipe.protein}</span>}
          {recipe.fett && <span>Fett: {recipe.fett}</span>}
        </div>
      )}
    </div>
  );
}
