import { ensureSchema, getDb } from '@/lib/db';
import Editor from './Editor';

type PageProps = { params: Promise<{ id: string }> };

type RecipeRow = {
  id: number;
  created_at: string;
  source_url: string;
  platform: 'tiktok' | 'instagram' | 'unknown';
  description: string | null;
  transcript: string | null;
  analysis_json: string;
  thumbnail: Buffer | null;
};

export default async function RecipeDetailPage({ params }: PageProps) {
  const { id } = await params;
  const idNum = Number(id);
  if (!idNum || Number.isNaN(idNum)) {
    return (
      <main className="min-h-screen p-6 md:p-12 lg:p-16 max-w-3xl mx-auto">
        <div className="text-red-600">Invalid recipe id</div>
      </main>
    );
  }

  await ensureSchema();
  const db = getDb();
  const [rows] = await db.query(
    'SELECT id, created_at, source_url, platform, description, transcript, CAST(analysis_json AS CHAR) AS analysis_json, thumbnail FROM recipes WHERE id = ? LIMIT 1',
    [idNum],
  );
  const [foldersRows] = await db.query('SELECT id, name FROM folders ORDER BY name ASC');
  const row = (rows as RecipeRow[])[0];
  if (!row) {
    return (
      <main className="min-h-screen p-6 md:p-12 lg:p-16 max-w-3xl mx-auto">
        <div className="text-neutral-700 dark:text-neutral-300">Recipe not found.</div>
      </main>
    );
  }

  const analysis = (() => { try { return JSON.parse(row.analysis_json); } catch { return null; } })();
  const thumb = row.thumbnail ? `data:image/jpeg;base64,${Buffer.from(row.thumbnail).toString('base64')}` : null;

  return (
    <main className="min-h-screen p-6 md:p-12 lg:p-16 flex flex-col gap-6 max-w-3xl mx-auto">
      <a href="/" className="underline">← Back to saved recipes</a>
      <div className="space-y-3">
        <h1 className="text-3xl font-bold">{row.title || `Recipe #${row.id}`}</h1>
        <div className="text-sm text-neutral-600 dark:text-neutral-300">
          <span className="capitalize font-medium">{row.platform}</span>{' '}•{' '}
          <a href={row.source_url} target="_blank" rel="noreferrer" className="underline">Open source link</a>{' '}•{' '}
          {new Date(row.created_at).toLocaleString()}
        </div>
      </div>

      {thumb && <img src={thumb} alt="thumbnail" className="w-full h-auto rounded" />}

      {row.description && (
        <div className="whitespace-pre-wrap text-neutral-700 dark:text-neutral-300"><span className="font-medium">Description:</span> {row.description}</div>
      )}

      <Editor
        id={row.id}
        title={row.title || ''}
        description={row.description || ''}
        transcript={row.transcript || ''}
        analysis={analysis || { ingredients: [], prep_steps: [], cooking_steps: [] }}
        folders={(foldersRows as any[]).map((f) => ({ id: f.id, name: f.name }))}
        folderId={(row as any).folder_id ?? null}
      />
    </main>
  );
}


