'use client';

import { useEffect, useState } from 'react';
import { Exercise } from '@prisma/client';
import WorkoutForm, { EditWorkoutData } from './WorkoutForm';
import { AI_WORKOUT_DRAFT_KEY } from '@/components/ai/GenerateWorkoutClient';
import { buildPrefillExercises, type AiWorkoutDraft } from '@/lib/ai/workoutDraft';

/**
 * Reads the ephemeral AI workout draft from sessionStorage (stashed by
 * GenerateWorkoutClient before navigating to /main/workouts/new?from=ai),
 * expands each suggested exercise into N pre-filled SetLogs, and renders
 * the normal WorkoutForm. Nothing is persisted until the user saves
 * through the regular workout path.
 *
 * The draft has no workout id, so WorkoutForm's first save CREATEs.
 * Effort follows the app convention: cardio → gear (1-5), else → rpe.
 *
 * If the draft is missing (e.g. a refresh cleared it), we fall back to a
 * blank form so the page is never broken.
 */
export default function AiWorkoutPrefill({
  exercises,
}: {
  exercises: Exercise[];
}) {
  // Read + build once on mount via a lazy initializer. This stays PURE
  // (no sessionStorage mutation) so React's StrictMode double-invoke is
  // safe — both passes read the same draft. The one-shot removal happens
  // in the effect below, after the value is captured.
  const [editWorkout] = useState<EditWorkoutData | undefined>(() => {
    if (typeof window === 'undefined') return undefined;
    const raw = sessionStorage.getItem(AI_WORKOUT_DRAFT_KEY);
    if (!raw) return undefined;

    let draft: AiWorkoutDraft;
    try {
      draft = JSON.parse(raw);
    } catch {
      return undefined;
    }

    const builtExercises: EditWorkoutData['exercises'] =
      buildPrefillExercises(draft, exercises);

    if (builtExercises.length === 0) return undefined;

    return {
      // No id → first save CREATEs a new workout.
      name: draft.name || '',
      date: new Date().toISOString(),
      notes: draft.notes,
      exercises: builtExercises,
    };
  });

  // Clear the one-shot draft after mount so a manual reload starts blank.
  // removeItem is idempotent, so StrictMode's double-run is harmless.
  useEffect(() => {
    sessionStorage.removeItem(AI_WORKOUT_DRAFT_KEY);
  }, []);

  return (
    <WorkoutForm
      exercises={exercises}
      recentlyUsedExercises={[]}
      editWorkout={editWorkout}
    />
  );
}
