
import type { Metadata } from 'next';
import { AddProjectForm } from '@/components/staff-portal/projects/add-project-form';
import { collection, getDocs, query, orderBy, Timestamp } from 'firebase/firestore';
import { db } from '@/lib/firebase';
import type { Project as ProjectType } from '@/types';
import { ProjectListClient } from '@/components/staff-portal/projects/project-list-client';
import { APP_NAME } from '@/constants';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Info } from "lucide-react";
import { SeedProjectsButton } from '@/components/staff-portal/projects/seed-projects-button'; // Import the new button

export const metadata: Metadata = {
  title: `Admin: Manage Projects | ${APP_NAME}`,
  description: `Manage company projects for ${APP_NAME}. Add, edit, or delete project listings. Images managed via Tari API.`,
  robots: {
    index: false,
    follow: false,
  },
};
export const dynamic = 'force-dynamic'; // Ensure fresh data on each request

async function getProjectsFromFirestore(): Promise<ProjectType[]> {
  // console.log("AdminProjectsPage: Attempting to fetch projects from Firestore...");
  if (!db) {
    console.error("AdminProjectsPage: Firestore database instance (db) is not available. Ensure Firebase is initialized correctly.");
    return [];
  }

  try {
    const projectsCol = collection(db, 'projects');
    // Re-added orderBy, ensure Firestore index exists for this
    const q = query(projectsCol, orderBy('createdAt', 'desc')); 
    
    const projectSnapshot = await getDocs(q);
    // console.log(`AdminProjectsPage: Fetched ${projectSnapshot.docs.length} project documents.`);
    
    const projectList: ProjectType[] = projectSnapshot.docs.map((doc) => {
      const data = doc.data();
      let projectItem: ProjectType;

      try {
        if (!data) {
          throw new Error("Document data is undefined.");
        }
        const title = typeof data.title === 'string' ? data.title : 'Untitled Project';
        const organization = typeof data.organization === 'string' ? data.organization : 'N/A';
        const description = typeof data.description === 'string' ? data.description : 'No description.';
        
        const imageUrl = typeof data.imageUrl === 'string' ? data.imageUrl : ''; 
        const imagePathTari = typeof data.imagePathTari === 'string' ? data.imagePathTari : undefined;
        
        const imageHint = typeof data.imageHint === 'string' ? data.imageHint : 'project image';
        
        let impactArray: string[] = [];
        if (Array.isArray(data.impact)) {
          impactArray = data.impact.filter((item: any): item is string => typeof item === 'string');
        } else if (typeof data.impact === 'string' && data.impact.trim() !== '') {
          impactArray = data.impact.split(',').map((s: string) => s.trim()).filter(Boolean);
        }
        
        let createdAtString: string | undefined = undefined;
        if (data.createdAt instanceof Timestamp) {
          createdAtString = data.createdAt.toDate().toISOString();
        } else if (data.createdAt && typeof data.createdAt.seconds === 'number') {
          createdAtString = new Timestamp(data.createdAt.seconds, data.createdAt.nanoseconds || 0).toDate().toISOString();
        } else if (typeof data.createdAt === 'string') {
           try {
            createdAtString = new Date(data.createdAt).toISOString();
          } catch (e) {
            // console.warn(`Could not parse date string for doc ${doc.id}:`, data.createdAt);
            createdAtString = undefined;
          }
        }
        
        projectItem = {
          id: doc.id, title, organization, description, imageUrl, imageHint, impact: impactArray, createdAt: createdAtString, imagePathTari
        };
      } catch (mapError: any) {
        console.error(`AdminProjectsPage: Error mapping document ID ${doc.id}. Error: ${mapError.message}`, "Raw data:", data);
        projectItem = {
          id: doc.id, title: 'Error: Invalid Data', organization: 'N/A', description: 'Corrupted data.', imageUrl: '', imageHint: 'error', impact: []
        };
      }
      return projectItem;
    });
    // console.log("AdminProjectsPage: Projects mapped successfully.");
    return projectList;
  } catch (error: any) {
    console.error("AdminProjectsPage: Encountered an error while fetching projects from Firestore.");
    console.error("Error object:", JSON.stringify(error, Object.getOwnPropertyNames(error)));

    if (typeof error === 'object' && error !== null) {
      const errorCode = (error as any).code;
      if (errorCode) console.error(`  Error Code: ${errorCode}`);
      if (errorCode === 'failed-precondition') {
        console.error("  RECOMMENDATION: This 'failed-precondition' error often indicates a missing Firestore index. Please check your Firebase console for any index creation links suggested in Firestore error messages, especially for queries with 'orderBy'. You likely need an index on 'projects' collection for 'createdAt' field (descending).");
      } else if (errorCode === 'permission-denied') {
        console.error("  RECOMMENDATION: This 'permission-denied' error indicates that your Firestore security rules are preventing access. Please check and update your Firestore security rules to allow reads by the server/admin.");
      }
      if ((error as any).message) console.error(`  Error Message: ${(error as any).message}`);
    }
    return []; 
  }
}

export default async function AdminProjectsPage() {
  // console.log("AdminProjectsPage: Rendering page...");
  const projects = await getProjectsFromFirestore();
  // console.log(`AdminProjectsPage: Received ${projects.length} projects to render.`);

  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 Company Projects</h1>
          <p className="text-muted-foreground">
            Add, view, search, and manage company projects. Images are managed via Tari API.
          </p>
        </div>
        <div className="flex gap-2">
          <SeedProjectsButton />
          <AddProjectForm />
        </div>
      </div>
      
      <Alert variant="default" className="bg-primary/5 border-primary/20">
        <Info className="h-4 w-4 text-primary" />
        <AlertTitle className="text-primary">Note on Importing Content</AlertTitle>
        <AlertDescription className="text-primary/80">
          The "Import Initial Project Content" button is for a one-time operation to add static project data (from the codebase) to Firestore.
          It does not check for duplicates by default if clicked multiple times. Use with caution.
        </AlertDescription>
      </Alert>

      <ProjectListClient initialProjects={projects} />
      
      <p className="text-xs text-muted-foreground mt-4">
        Ensure Firestore indexes are set up if ordering is used (e.g., by 'createdAt'). Check server logs for specific errors.
        Images are uploaded to and deleted from an external service (files.tari.africa).
      </p>
    </div>
  );
}
