import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useRecipe } from '../hooks/useRecipe';
import { useToastContext } from '../App';
import { RecipeForm, type RecipeFormData } from '../components/RecipeForm';
import { createRecipe, updateRecipe, deleteRecipe, fetchRecipeTags, assignTagToRecipe, removeTagFromRecipe } from '../services/api';
import type { Tag, Ingredient } from '../types/recipe';
import { radius } from '../theme';

/**
 * RecipeDetailPage - View, create, and edit recipes (visual refresh - task 3)
 */
export function RecipeDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const toast = useToastContext();
  // Parse ID or null for "new" route
  const recipeId = id === 'new' ? null : (id ? parseInt(id, 10) : null);
  const { recipe, loading, error } = useRecipe(recipeId);
  const [isEditing, setIsEditing] = useState(recipeId === null);
  const [deleteConfirm, setDeleteConfirm] = useState(false);
  const [recipeTags, setRecipeTags] = useState<Tag[]>([]);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    if (recipeId !== null) {
      fetchRecipeTags(recipeId)
        .then(setRecipeTags)
        .catch((err) => {
          console.error('Failed to load recipe tags:', err);
          toast.error('Failed to load recipe tags');
        });
    }
  }, [recipeId, toast]);

  function toApiIngredients(ingredients: string[]): Ingredient[] {
    return ingredients.map((item, idx) => ({
      id: 0,
      recipe_id: 0,
      position: idx + 1,
      item,
      quantity: null,
      unit: null,
      notes: null,
    }));
  }

  const handleSubmit = async (data: RecipeFormData, tags: Tag[]) => {
    try {
      if (recipeId === null) {
        const newRecipe = await createRecipe({
          ...data,
          ingredients: toApiIngredients(data.ingredients),
          instructions: data.instructions,
        });
        for (const tag of tags) { try { await assignTagToRecipe(newRecipe.id, tag.id); } catch {} }
        toast.success('Recipe created successfully!');
        navigate(`/recipe/${newRecipe.id}`);
      } else {
        await updateRecipe(recipeId, {
          ...data,
          ingredients: toApiIngredients(data.ingredients),
          instructions: data.instructions,
        });
        const currentTagIds = recipeTags.map(t => t.id);
        const newTagIds = tags.map(t => t.id);
        for (const tagId of currentTagIds) {
          if (!newTagIds.includes(tagId)) { try { await removeTagFromRecipe(recipeId, tagId); } catch {} }
        }
        for (const tagId of newTagIds) {
          if (!currentTagIds.includes(tagId)) { try { await assignTagToRecipe(recipeId, tagId); } catch {} }
        }
        toast.success('Recipe updated successfully!');
        setIsEditing(false);
        window.location.reload();
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to save recipe';
      toast.error(errorMessage);
      throw err;
    }
  };

  const handleDelete = async () => {
    if (recipeId === null) return;
    try {
      setIsDeleting(true);
      await deleteRecipe(recipeId);
      toast.success('Recipe deleted successfully');
      navigate('/');
    } catch (err) {
      setIsDeleting(false);
      setDeleteConfirm(false);
      const errorMessage = err instanceof Error ? err.message : 'Failed to delete recipe';
      toast.error(errorMessage);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-24">
        <div className="inline-block h-9 w-9 animate-spin rounded-full border-b-2 border-primary"></div>
        <p className="mt-6 text-base font-medium text-gray-500">Loading recipe...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="mx-auto mt-12 flex max-w-xl flex-col items-center rounded-xl border border-red-200 bg-red-50 p-8 shadow-card">
        <h3 className="mb-3 text-xl font-bold text-red-800">Error Loading Recipe</h3>
        <p className="mb-2 text-base text-red-600">{error}</p>
        <Link to="/" className="mt-4 rounded-md bg-primary px-4 py-2 font-medium text-white hover:bg-blue-700">← Back to recipes</Link>
      </div>
    );
  }

  if (recipeId === null) {
    return (
      <div className="mx-auto max-w-3xl pt-8">
        <div
          className="mb-6 overflow-hidden border border-blue-100 bg-gradient-to-br from-white via-blue-50/70 to-indigo-50/80 shadow-card"
          style={{ borderRadius: radius.lg }}
        >
          <div className="flex items-center justify-between px-6 py-5">
            <div>
              <p className="text-xs font-semibold uppercase tracking-wider text-blue-600">New Recipe</p>
              <h2 className="text-3xl font-bold text-gray-900">Create New Recipe</h2>
              <p className="mt-1 text-base text-gray-600">Fill in the details below to add a new recipe.</p>
            </div>
            <div className="hidden rounded-xl border border-blue-100 bg-white/80 p-4 text-3xl md:block">🧾</div>
          </div>
        </div>
        <div className="rounded-xl bg-white p-8 shadow-card">
          <RecipeForm initialTags={[]} onSubmit={handleSubmit} onCancel={() => navigate('/')} submitLabel="Create Recipe" />
        </div>
      </div>
    );
  }

  if (!recipe) {
    return (
      <div className="mx-auto mt-12 flex max-w-md flex-col items-center rounded-xl border border-yellow-200 bg-yellow-50 p-8 shadow-card">
        <h3 className="mb-2 text-xl font-bold text-yellow-800">Recipe Not Found</h3>
        <p className="mb-2 text-base text-yellow-600">The recipe you are looking for does not exist.</p>
        <Link to="/" className="mt-4 rounded-md bg-primary px-4 py-2 font-medium text-white hover:bg-blue-700">← Back to recipes</Link>
      </div>
    );
  }

  if (isEditing) {
    return (
      <div className="mx-auto max-w-3xl pt-8">
        <div
          className="mb-6 overflow-hidden border border-violet-100 bg-gradient-to-br from-white via-violet-50/70 to-indigo-50/70 shadow-card"
          style={{ borderRadius: radius.lg }}
        >
          <div className="flex items-center justify-between px-6 py-5">
            <div>
              <p className="text-xs font-semibold uppercase tracking-wider text-violet-600">Editing</p>
              <h2 className="text-3xl font-bold text-gray-900">Edit Recipe</h2>
              <p className="mt-1 text-base text-gray-600">Update recipe information below.</p>
            </div>
            <div className="hidden rounded-xl border border-violet-100 bg-white/80 p-4 text-3xl md:block">✏️</div>
          </div>
        </div>
        <div className="rounded-xl bg-white p-8 shadow-card">
          <RecipeForm recipe={recipe} initialTags={recipeTags} onSubmit={handleSubmit} onCancel={() => setIsEditing(false)} submitLabel="Save Changes" />
        </div>
      </div>
    );
  }

  const statCards = [
    recipe.servings ? { label: 'Servings', value: String(recipe.servings), icon: '🍽️' } : null,
    recipe.prep_time_minutes ? { label: 'Prep Time', value: `${recipe.prep_time_minutes} min`, icon: '⏱️' } : null,
    recipe.cook_time_minutes ? { label: 'Cook Time', value: `${recipe.cook_time_minutes} min`, icon: '🔥' } : null,
  ].filter(Boolean) as Array<{ label: string; value: string; icon: string }>;

  return (
    <div className="mx-auto max-w-5xl pt-8">
      <section
        className="relative mb-6 overflow-hidden border border-slate-200/80 bg-white/95 shadow-card"
        style={{ borderRadius: radius.lg }}
      >
        <div className="absolute inset-x-0 top-0 h-28 bg-gradient-to-r from-orange-100 via-amber-50 to-blue-100" />
        <div className="relative px-6 pb-6 pt-7 md:px-8">
          <div className="mb-5 flex items-start justify-between gap-5">
            <div className="min-w-0 flex-1">
              <p className="mb-1 text-xs font-semibold uppercase tracking-wider text-orange-600">Recipe Details</p>
              <h2 className="mb-1 break-words text-4xl font-extrabold text-gray-900">{recipe.title}</h2>
              {recipe.description && (
                <p className="mt-2 max-w-3xl break-words text-base text-gray-600 md:text-lg">{recipe.description}</p>
              )}
              {recipeTags.length > 0 && (
                <div className="mt-4 flex flex-wrap gap-2">
                  {recipeTags.map(tag => (
                    <span
                      key={tag.id}
                      className="rounded-full px-3 py-1 text-xs font-semibold text-white shadow"
                      style={{ backgroundColor: tag.color || '#3B82F6' }}
                    >
                      {tag.name}
                    </span>
                  ))}
                </div>
              )}
            </div>
            <div className="hidden rounded-2xl border border-white/80 bg-white/75 p-4 text-4xl shadow-sm md:block">🍲</div>
          </div>

          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <button onClick={() => setIsEditing(true)} className="inline-flex items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2.5 font-semibold text-white shadow transition-all duration-200 hover:-translate-y-0.5 hover:bg-blue-700 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"><span aria-hidden="true">✏️</span> Edit Recipe</button>
            <Link to={`/recipe/${recipe.id}/cook`} className="inline-flex items-center justify-center gap-2 rounded-lg bg-green-600 px-4 py-2.5 text-center font-semibold text-white shadow transition-all duration-200 hover:-translate-y-0.5 hover:bg-green-700 focus-visible:ring-2 focus-visible:ring-green-500 focus-visible:ring-offset-2"><span aria-hidden="true">🍳</span>Cook Mode</Link>
            {!deleteConfirm ? (
              <button onClick={() => setDeleteConfirm(true)} className="inline-flex items-center justify-center gap-2 rounded-lg bg-red-600 px-4 py-2.5 font-semibold text-white shadow transition-all duration-200 hover:-translate-y-0.5 hover:bg-red-700 focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"><span aria-hidden="true">🗑️</span>Delete Recipe</button>
            ) : (
              <div className="grid grid-cols-2 gap-2 sm:col-span-2 lg:col-span-2">
                <button
                  onClick={handleDelete}
                  disabled={isDeleting}
                  className="rounded-lg bg-red-700 px-3 py-2.5 text-sm font-semibold text-white shadow transition-all duration-200 hover:-translate-y-0.5 hover:bg-red-800 focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:bg-gray-400"
                >
                  {isDeleting ? 'Deleting...' : 'Confirm Delete'}
                </button>
                <button
                  onClick={() => setDeleteConfirm(false)}
                  disabled={isDeleting}
                  className="rounded-lg bg-slate-200 px-3 py-2.5 text-sm font-semibold text-slate-700 transition-all duration-200 hover:-translate-y-0.5 hover:bg-slate-300 focus-visible:ring-2 focus-visible:ring-slate-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
                >
                  Cancel
                </button>
              </div>
            )}
          </div>
        </div>
      </section>

      {statCards.length > 0 && (
        <section className="mb-6 grid grid-cols-1 gap-4 text-center md:grid-cols-3">
          {statCards.map((stat) => (
            <div key={stat.label} className="rounded-xl border border-slate-200/80 bg-white/90 p-4 shadow-card">
              <div className="mb-1 text-2xl" aria-hidden="true">{stat.icon}</div>
              <div className="text-xs font-semibold uppercase tracking-wide text-gray-500">{stat.label}</div>
              <div className="mt-1 text-lg font-bold text-gray-900">{stat.value}</div>
            </div>
          ))}
        </section>
      )}

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        <section className="overflow-hidden rounded-xl border border-slate-200/80 bg-white shadow-card">
          <div className="border-b border-slate-100 bg-gradient-to-r from-blue-50 to-white px-6 py-4">
            <h3 className="text-xl font-semibold text-gray-900">Ingredients</h3>
            <p className="text-sm text-gray-500">Everything you need before you start cooking.</p>
          </div>
          <ul className="space-y-3 px-6 py-5">
            {Array.isArray(recipe.ingredients) ? recipe.ingredients.map((ingredient, index) => (
              <li key={index} className="flex items-start gap-3 rounded-lg border border-slate-100 bg-slate-50/70 px-3 py-2.5">
                <span className="mt-1 inline-block h-2.5 w-2.5 rounded-full bg-blue-500"></span>
                <span className="font-mono text-base text-gray-800">{'item' in ingredient ? ingredient.item : ingredient}</span>
              </li>
            )) : null}
          </ul>
        </section>

        <section className="overflow-hidden rounded-xl border border-slate-200/80 bg-white shadow-card">
          <div className="border-b border-slate-100 bg-gradient-to-r from-orange-50 to-white px-6 py-4">
            <h3 className="text-xl font-semibold text-gray-900">Instructions</h3>
            <p className="text-sm text-gray-500">Follow these steps for best results.</p>
          </div>
          <ol className="space-y-3 px-6 py-5">
            {Array.isArray(recipe.instructions) ? recipe.instructions.map((instruction, index) => (
              <li key={index} className="flex items-start gap-3 rounded-lg border border-slate-100 bg-slate-50/70 px-3 py-2.5">
                <span className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-blue-600 text-sm font-bold text-white">{index + 1}</span>
                <span className="pt-1 text-base leading-6 text-gray-800">{instruction}</span>
              </li>
            )) : null}
          </ol>
        </section>
      </div>

      {(recipe.source_url || recipe.notes) && (
        <section className="mt-8 overflow-hidden rounded-xl border border-slate-200/80 bg-white shadow-card">
          <div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-6 py-4">
            <h3 className="text-xl font-semibold text-gray-900">Additional Information</h3>
          </div>
          <div className="space-y-5 px-6 py-5">
            {recipe.source_url && (
              <div>
                <div className="mb-1 text-sm font-medium text-gray-700">Source</div>
                <a href={recipe.source_url} target="_blank" rel="noopener noreferrer" className="break-all text-primary underline hover:text-blue-700">{recipe.source_url}</a>
              </div>
            )}
            {recipe.notes && (
              <div>
                <div className="mb-1 text-sm font-medium text-gray-700">Notes</div>
                <p className="whitespace-pre-wrap text-gray-800">{recipe.notes}</p>
              </div>
            )}
          </div>
        </section>
      )}

      <div className="mt-8 text-center">
        <Link to="/" className="inline-flex items-center gap-1 font-medium text-primary transition-colors hover:text-blue-700 focus-visible:ring-2 focus-visible:ring-blue-500 rounded-sm">← Back to all recipes</Link>
      </div>
    </div>
  );
}
