
import Image from 'next/image';
import { APP_NAME } from '@/constants';
import { notFound } from 'next/navigation';
import type { Metadata, ResolvingMetadata } from 'next';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, ArrowLeft, Building, Users } from 'lucide-react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { getPublicProjectById, getPublicProjects } from '@/lib/actions'; // Import actions
import type { Project } from '@/types';
import { ProjectDetailImage } from '@/components/projects/ProjectDetailImage'; // Import the new client component

type Props = {
  params: { id: string };
};

export async function generateStaticParams() {
  const projects = await getPublicProjects(); // Fetch projects from Firestore
  return projects.map((project) => ({
    id: project.id,
  }));
}

export async function generateMetadata(
  { params }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const project: Project | null = await getPublicProjectById(params.id); // Fetch project by ID

  if (!project) {
    return {
      title: `Project Not Found | ${APP_NAME}`,
      description: `Details for the requested project could not be found.`,
    };
  }

  return {
    title: `${project.title} | ${APP_NAME}`,
    description: project.description.substring(0, 160) + "...",
    openGraph: {
      title: `${project.title} | ${APP_NAME}`,
      description: project.description.substring(0, 160) + "...",
      images: [
        {
          url: project.imageUrl || `https://placehold.co/600x400.png?text=${encodeURIComponent(project.title)}`, // Fallback for OpenGraph
          width: 600,
          height: 400,
          alt: project.title,
        },
      ],
    },
  };
}

export default async function ProjectDetailPage({ params }: Props) {
  const project: Project | null = await getPublicProjectById(params.id);

  if (!project) {
    notFound();
  }

  return (
    <div className="bg-background text-foreground">
      {/* Project Header Section */}
      <section className="py-12 md:py-16 bg-primary/5">
        <div className="container mx-auto px-4">
          <Button variant="outline" asChild className="mb-8 group">
            <Link href="/projects">
              <ArrowLeft className="mr-2 h-4 w-4 group-hover:-translate-x-1 transition-transform" />
              Back to All Projects
            </Link>
          </Button>
          <h1 className="text-3xl md:text-4xl font-bold text-primary mb-3 text-shadow-primary">{project.title}</h1>
          <div className="flex items-center text-muted-foreground mb-6">
            <Building className="h-5 w-5 mr-2 text-accent" />
            <span>In collaboration with: <strong className="text-foreground">{project.organization}</strong></span>
          </div>
        </div>
      </section>

      {/* Project Content Section */}
      <section className="py-12 md:py-16">
        <div className="container mx-auto px-4">
          <div className="grid lg:grid-cols-3 gap-8 lg:gap-12">
            {/* Main Content Area */}
            <div className="lg:col-span-2 space-y-8">
              <ProjectDetailImage
                src={project.imageUrl}
                alt={project.title}
                title={project.title}
                imageHint={project.imageHint}
              />

              <Card className="shadow-lg">
                <CardHeader>
                  <CardTitle className="text-2xl text-primary text-shadow-primary">Project Overview</CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-muted-foreground leading-relaxed whitespace-pre-line">
                    {project.description}
                  </p>
                </CardContent>
              </Card>
            </div>

            {/* Sidebar Area for Key Impacts */}
            <div className="lg:col-span-1">
              <Card className="shadow-lg sticky top-24">
                <CardHeader>
                  <CardTitle className="text-xl flex items-center text-primary text-shadow-primary">
                    <Users className="h-6 w-6 mr-3 text-accent" />
                    Key Impacts & Outcomes
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  {project.impact && project.impact.length > 0 ? (
                    <ul className="space-y-3">
                      {project.impact.map((item, index) => (
                        <li key={index} className="flex items-start text-sm">
                          <CheckCircle className="h-5 w-5 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
                          <span className="text-muted-foreground">{item}</span>
                        </li>
                      ))}
                    </ul>
                  ) : (
                    <p className="text-sm text-muted-foreground">Details on impact and outcomes will be updated soon.</p>
                  )}
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </section>

      {/* Related Projects or CTA (Optional) */}
      <section className="py-12 md:py-16 bg-muted/30">
        <div className="container mx-auto px-4 text-center">
            <h2 className="text-2xl font-semibold text-foreground mb-4">Interested in similar initiatives?</h2>
            <p className="text-muted-foreground mb-6 max-w-xl mx-auto">
                {APP_NAME} is dedicated to driving positive change. Explore more of our work or partner with us.
            </p>
            <div className="flex gap-4 justify-center">
                <Button asChild>
                    <Link href="/projects">View Other Projects</Link>
                </Button>
                <Button variant="outline" asChild>
                    <Link href="/contact">Contact Us</Link>
                </Button>
            </div>
        </div>
      </section>
    </div>
  );
}
