
import type { Metadata } from 'next';
import { APP_NAME, TARI_GENERAL_IMAGES_FOLDER } from '@/constants';
import { listTariImages } from '@/lib/actions';
import { UploadImageForm } from '@/components/staff-portal/images/upload-image-form';
import { ImageListClient } from '@/components/staff-portal/images/image-list-client';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Terminal } from 'lucide-react';

export const metadata: Metadata = {
  title: `Admin: Manage General Images | ${APP_NAME}`,
  description: `Manage general images for ${APP_NAME}, stored on Tari File Management.`,
  robots: {
    index: false,
    follow: false,
  },
};

export const dynamic = 'force-dynamic'; // Ensure fresh data on each request

export default async function AdminImagesPage() {
  console.log("AdminImagesPage: Fetching images from Tari folder:", TARI_GENERAL_IMAGES_FOLDER);
  const imageListResult = await listTariImages(TARI_GENERAL_IMAGES_FOLDER);

  let imageContent;
  if (imageListResult.success && imageListResult.files) {
    imageContent = <ImageListClient initialImages={imageListResult.files} />;
  } else {
    imageContent = (
      <Alert variant="destructive" className="mt-6">
        <Terminal className="h-4 w-4" />
        <AlertTitle>Error Fetching Images</AlertTitle>
        <AlertDescription>
          Could not load images from Tari: {imageListResult.error || "Unknown error"}. 
          Please check server logs and ensure Tari API credentials and permissions are correct.
          <p className="mt-2 text-xs">
            Note: Images are managed via the Tari API. To use an image as the site logo,
            copy its URL and update the `LOGO_URL` constant in `src/constants/index.ts`.
            For favicons, typically you replace files like `public/favicon.ico` or update 
            `&lt;link&gt;` tags in `src/app/layout.tsx`.
          </p>
        </AlertDescription>
      </Alert>
    );
  }

  return (
    <div className="w-full space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Manage General Images (Tari API)</h1>
          <p className="text-muted-foreground">
            Upload, view, and delete general purpose images. These are stored on Tari.
          </p>
        </div>
        <UploadImageForm />
      </div>
      {imageContent}
    </div>
  );
}
