'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { useApi } from '@/lib/useApi';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import { RecipeEditor } from '../../RecipeEditor';
import { getRecipe } from '@/services/recipes';
import type { z } from 'zod/v4';
import type { RecipeResponseSchema } from '@meshitrack/shared';

type Recipe = z.infer<typeof RecipeResponseSchema>;

export default function EditRecipePage() {
  const params = useParams<{ id: string }>();
  const { householdId, isLoading: sessionLoading } = useApi();
  const [recipe, setRecipe] = useState<Recipe | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!householdId || !params.id) return;
    getRecipe(householdId, params.id)
      .then(setRecipe)
      .catch((err) => setError(err instanceof Error ? err.message : 'Failed to load recipe'))
      .finally(() => setLoading(false));
  }, [householdId, params.id]);

  const title = recipe?.name ? `Edit: ${recipe.name}` : 'Edit Recipe';

  if (sessionLoading || loading) {
    return (
      <>
        <SetPageHeader title="Edit Recipe" crumbs={['Recipes', 'Edit']} />
        <div style={{ padding: '28px 32px', color: 'var(--ink-muted)', fontSize: 14 }}>
          Loading...
        </div>
      </>
    );
  }

  if (error || !recipe) {
    return (
      <>
        <SetPageHeader title="Edit Recipe" crumbs={['Recipes', 'Edit']} />
        <div style={{ padding: '28px 32px', color: 'var(--danger)', fontSize: 14 }}>
          {error || 'Recipe not found'}
        </div>
      </>
    );
  }

  return (
    <>
      <SetPageHeader title={title} crumbs={['Recipes', recipe.name, 'Edit']} />
      <div style={{ padding: '28px 32px 56px' }}>
        <RecipeEditor householdId={householdId!} existing={recipe} />
      </div>
    </>
  );
}
