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

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

export default async function Home() {
  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 ORDER BY id DESC LIMIT 100',
  );
  const [foldersRows] = await db.query('SELECT id, name FROM folders ORDER BY name ASC');
  const recipes = (rows as RecipeRow[]).map((r) => ({
    id: r.id,
    created_at: r.created_at,
    url: r.source_url,
    platform: r.platform,
    title: (r as any).title || null,
    folder_id: (r as any).folder_id || null,
    thumbnailBase64: r.thumbnail ? `data:image/jpeg;base64,${Buffer.from(r.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-4xl mx-auto">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl md:text-4xl font-bold">Saved Recipes</h1>
        <a href="/recipe" className="underline">Analyze new video →</a>
      </div>
      <FoldersBar initialFolders={(foldersRows as any[]).map((f) => ({ id: f.id, name: f.name }))} />
      {/* Folders sections */}
      {(foldersRows as any[]).map((f: any) => (
        <section key={f.id} id={`folder-${f.id}`} className="space-y-3">
          <h2 className="text-xl font-semibold">{f.name}</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            {recipes.filter((r) => r.folder_id === f.id).map((r) => (
              <a key={r.id} href={`/recipes/${r.id}`} className="border rounded overflow-hidden hover:shadow">
                {r.thumbnailBase64 ? (
                  <img src={r.thumbnailBase64} alt="thumb" className="w-full h-48 object-cover" />
                ) : (
                  <div className="w-full h-48 bg-neutral-200 dark:bg-neutral-800" />
                )}
                <div className="p-3 text-sm">
                  <div className="font-medium">{r.title || r.url}</div>
                  <div className="text-neutral-500">{new Date(r.created_at).toLocaleString()}</div>
                </div>
              </a>
            ))}
            {!recipes.some((r) => r.folder_id === f.id) && (
              <div className="text-neutral-600 dark:text-neutral-300">No recipes in this folder yet.</div>
            )}
          </div>
        </section>
      ))}

      {/* Unsorted */}
      <section className="space-y-3">
        <h2 className="text-xl font-semibold">Unsorted</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
        {recipes.filter((r) => !r.folder_id).map((r) => (
          <a key={r.id} href={`/recipes/${r.id}`} className="border rounded overflow-hidden hover:shadow">
            {r.thumbnailBase64 ? (
              <img src={r.thumbnailBase64} alt="thumb" className="w-full h-48 object-cover" />
            ) : (
              <div className="w-full h-48 bg-neutral-200 dark:bg-neutral-800" />
            )}
            <div className="p-3 text-sm">
              <div className="font-medium">{r.title || r.url}</div>
              <div className="text-neutral-500">{new Date(r.created_at).toLocaleString()}</div>
            </div>
          </a>
        ))}
        {!recipes.length && (
          <div className="text-neutral-600 dark:text-neutral-300">No recipes saved yet.</div>
        )}
        </div>
      </section>
    </main>
  );
}
