import * as Bun from "bun";
import { Suspense } from "react";
import { TwitterApiService } from "../lib/twitter-api";
import { BookmarkList } from "../components/bookmark-list";

async function BookmarkFetcher() {
  const cookie = Bun.env.TWATTER_COKI;

  if (!cookie) {
    return (
      <div className="text-red-600">Missing Twitter cookie configuration</div>
    );
  }

  try {
    const twitterService = new TwitterApiService(cookie);
    const bookmarks = await twitterService.fetchAllBookmarks();
    const file = Bun.file("testData.json");
    await file.write(JSON.stringify(bookmarks));

    return (
      <div className="space-y-6">
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h2 className="text-xl font-semibold mb-4">Your Bookmarks</h2>
          <BookmarkList bookmarks={bookmarks} />
        </div>
      </div>
    );
  } catch (error) {
    return (
      <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
        Error loading bookmarks:{" "}
        {error instanceof Error ? error.message : "Unknown error"}
      </div>
    );
  }
}

function LoadingSpinner() {
  return (
    <div className="flex items-center justify-center py-12">
      <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      <span className="ml-3 text-gray-600">
        Loading your Twitter bookmarks...
      </span>
    </div>
  );
}

export default async function HomePage() {
  return (
    <div className="max-w-4xl mx-auto">
      <title>SORMARK - Twitter Bookmark Manager</title>
      <div className="mb-8">
        <h1 className="text-4xl font-bold tracking-tight mb-4">SORMARK</h1>
        <p className="text-lg text-gray-600">
          Your Twitter bookmark manager powered by AI
        </p>
      </div>

      <Suspense fallback={<LoadingSpinner />}>
        <BookmarkFetcher />
      </Suspense>
    </div>
  );
}

export const getConfig = async () => {
  return {
    render: "static",
  } as const;
};
