'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Header } from '@/app/components/Header';
import { Footer } from '@/app/components/Footer';
import api from '@/lib/api';

export default function ProgramProjectsPage() {
  const params = useParams();
  const thematicAreaSlug = params?.slug as string;
  const programSlug = params?.programSlug as string;
  
  const [program, setProgram] = useState<any>(null);
  const [projects, setProjects] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [expandedProjects, setExpandedProjects] = useState<Record<number, boolean>>({});

  useEffect(() => {
    if (programSlug) {
      fetchProgram();
    }
  }, [programSlug]);

  useEffect(() => {
    if (!loading && program) {
      setTimeout(() => setIsVisible(true), 100);
    }
  }, [loading, program]);

  const fetchProgram = async () => {
    try {
      setLoading(true);
      setError(null);
      setIsVisible(false);
      const data: any = await api.getProgram(programSlug);
      
      setProgram(data);
      if (data.projects && Array.isArray(data.projects)) {
        setProjects(data.projects);
      } else {
        setProjects([]);
      }
    } catch (err: any) {
      console.error('Error fetching program:', err);
      setError(err?.message || 'Failed to load program');
    } finally {
      setLoading(false);
    }
  };


  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
            <p className="text-lg text-neutral-600">Loading projects...</p>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  if (error || !program) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <div className="text-center max-w-2xl">
            <h1 className="text-4xl md:text-5xl font-bold text-primary-500 mb-4">
              {error ? 'Error Loading Program' : 'Program Not Found'}
            </h1>
            <p className="text-lg md:text-xl text-neutral-600 mb-8">
              {error || 'The program you\'re looking for doesn\'t exist.'}
            </p>
            <Link 
              href={`/programs/${thematicAreaSlug}`}
              className="inline-flex items-center gap-2 px-6 py-3 bg-primary-500 text-neutral-900 rounded-lg hover:bg-primary-700 transition-colors font-semibold"
            >
              Back to Programs
            </Link>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  const thematicArea = program.thematic_area;

  return (
    <div className="min-h-screen bg-white">
      <Header />
      
      {/* Hero Section */}
      <section className="relative">
        {/* Breadcrumb */}
        <div className="absolute top-6 left-0 right-0 z-20 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <nav className="mb-0" aria-label="Breadcrumb">
            <ol className="flex items-center space-x-2 flex-wrap bg-white/95 backdrop-blur-md px-4 py-3 rounded-lg shadow-xl border border-white/20">
              <li>
                <Link 
                  href="/" 
                  className="text-neutral-700 hover:text-primary-600 transition-colors duration-200 text-sm md:text-base font-medium flex items-center gap-2 group"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                  </svg>
                  <span className="group-hover:underline">Home</span>
                </Link>
              </li>
              <li className="text-neutral-400">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </li>
              <li>
                <Link 
                  href="/#what-we-do" 
                  className="text-neutral-700 hover:text-primary-600 transition-colors duration-200 text-sm md:text-base font-medium group"
                >
                  <span className="group-hover:underline">What We Do</span>
                </Link>
              </li>
              {thematicArea && (
                <>
                  <li className="text-neutral-400">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                    </svg>
                  </li>
                  <li>
                    <Link 
                      href={`/programs/${thematicArea.slug}`}
                      className="text-neutral-700 hover:text-primary-600 transition-colors duration-200 text-sm md:text-base font-medium group"
                    >
                      <span className="group-hover:underline">{thematicArea.title}</span>
                    </Link>
                  </li>
                </>
              )}
              <li className="text-neutral-400">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </li>
              <li className="text-neutral-900 font-semibold text-sm md:text-base">{program.title}</li>
            </ol>
          </nav>
        </div>

        {/* Image Container */}
        <div className="relative w-full h-[40vh] min-h-[300px] md:h-[50vh] md:min-h-[400px] overflow-hidden flex items-center">
          <img 
            src={program.featured_image || program.image || program.image_large || program.image_medium || '/images/hero/slider-1.webp'}
            alt={program.title}
            className="absolute inset-0 w-full h-full object-cover object-center"
          />
          
          {/* Overlay */}
          <div className="absolute inset-0 bg-black/50" />
          
          {/* Title */}
          <div className={`relative z-10 max-w-7xl mx-auto w-full px-4 sm:px-6 lg:px-8 transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
            <div className="inline-block max-w-4xl">
              <h1 className="text-3xl md:text-4xl lg:text-5xl font-black text-white leading-tight px-10 py-8 bg-white/10 backdrop-blur-md rounded-2xl shadow-2xl border border-white/20">
                {program.title} - Projects
              </h1>
            </div>
          </div>
        </div>
      </section>

      {/* Projects Section - Alternating Layout */}
      <section className={`py-16 md:py-24 bg-white transition-all duration-1000 delay-100 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {projects.length > 0 ? (
            <>
              <div className="mb-16 text-center">
                <h2 className="text-4xl md:text-5xl font-bold text-primary-500 mb-4">
                  Our Projects
                </h2>
                <p className="text-xl text-neutral-600 max-w-3xl mx-auto">
                  Explore the projects we implement under {program.title} to create lasting impact.
                </p>
              </div>

              {/* Projects - Alternating Layout */}
              <div className="space-y-24 md:space-y-32">
                {projects.map((project: any, index: number) => {
                  const isEven = index % 2 === 0;
                  const projectImage = project.featured_image || project.image || project.image_large || project.image_medium;
                  
                  return (
                    <article
                      key={project.id}
                      className={`grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 items-start group transition-all duration-1000 ${
                        isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'
                      }`}
                      style={{
                        animationDelay: `${index * 150}ms`
                      }}
                    >
                      {/* Image Section */}
                      <div className={`order-1 ${isEven ? 'lg:order-1' : 'lg:order-2'}`}>
                        <div className="relative h-[400px] md:h-[500px] rounded-lg overflow-hidden shadow-lg group-hover:shadow-2xl transition-all duration-500">
                          {projectImage ? (
                            <>
                              <img 
                                src={projectImage}
                                alt={project.name}
                                className="absolute inset-0 w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-700"
                                style={{ objectPosition: 'top center' }}
                              />
                              <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent" />
                              {project.featured && (
                                <div className="absolute top-4 right-4 px-3 py-1.5 bg-yellow-400 rounded-full shadow-lg">
                                  <svg className="w-5 h-5 text-yellow-900" fill="currentColor" viewBox="0 0 20 20">
                                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                                  </svg>
                                </div>
                              )}
                            </>
                          ) : (
                            <>
                              <div className="absolute inset-0 bg-gradient-to-br from-primary-100 to-primary-200" />
                              <div className="absolute inset-0 flex items-center justify-center">
                                <svg className="w-24 h-24 text-primary-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                                </svg>
                              </div>
                            </>
                          )}
                          
                          {/* Overlay on hover */}
                          <div className="absolute inset-0 bg-primary-600/0 group-hover:bg-primary-600/10 transition-all duration-500" />
                        </div>
                      </div>

                      {/* Content Section */}
                      <div className={`order-2 ${isEven ? 'lg:order-2' : 'lg:order-1'}`}>
                        <div className="space-y-6">
                          {/* Title */}
                          <h3 className="text-3xl md:text-4xl font-bold text-neutral-900 leading-tight">
                            {project.name}
                          </h3>

                          {/* Description */}
                          {project.description && (
                            <p className="text-lg text-neutral-700 leading-relaxed text-justified">
                              {project.description}
                            </p>
                          )}

                          {/* Project Content */}
                          {project.content && (
                            <div>
                              <div 
                                className={`text-neutral-600 leading-relaxed prose prose-neutral max-w-none text-justified ${
                                  !expandedProjects[project.id] && project.content.length > 500 ? 'line-clamp-6' : ''
                                }`}
                                dangerouslySetInnerHTML={{ 
                                  __html: expandedProjects[project.id] 
                                    ? project.content 
                                    : project.content.length > 500 
                                      ? project.content.substring(0, 500) + '...' 
                                      : project.content
                                }} 
                              />
                              {project.content.length > 500 && (
                                <button
                                  onClick={() => setExpandedProjects(prev => ({
                                    ...prev,
                                    [project.id]: !prev[project.id]
                                  }))}
                                  className="mt-4 text-primary-600 hover:text-primary-700 font-semibold text-sm flex items-center gap-1 transition-colors"
                                >
                                  {expandedProjects[project.id] ? (
                                    <>
                                      <span>Show Less</span>
                                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                                      </svg>
                                    </>
                                  ) : (
                                    <>
                                      <span>Read More</span>
                                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                      </svg>
                                    </>
                                  )}
                                </button>
                              )}
                            </div>
                          )}

                          {/* Project Information */}
                          <div className="space-y-4 pt-4 border-t border-neutral-200">
                            {project.donor && (
                              <div className="flex items-center gap-3">
                                <div className="flex-shrink-0 w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center">
                                  <svg className="w-5 h-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                                  </svg>
                                </div>
                                <div>
                                  <div className="text-xs text-neutral-500 uppercase tracking-wide">Donor</div>
                                  <div className="text-base font-semibold text-neutral-900">{project.donor.name}</div>
                                </div>
                              </div>
                            )}

                            {project.provinces && project.provinces.length > 0 && (
                              <div className="flex items-start gap-3">
                                <div className="flex-shrink-0 w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center mt-0.5">
                                  <svg className="w-5 h-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                  </svg>
                                </div>
                                <div className="flex-1">
                                  <div className="text-xs text-neutral-500 uppercase tracking-wide mb-2">Provinces</div>
                                  <div className="flex flex-wrap gap-2">
                                    {project.provinces.map((province: any) => (
                                      <span 
                                        key={province.id}
                                        className="inline-block px-3 py-1 bg-primary-100 text-primary-700 rounded-full text-sm font-medium"
                                      >
                                        {province.name}
                                      </span>
                                    ))}
                                  </div>
                                </div>
                              </div>
                            )}

                            {project.districts && project.districts.length > 0 && (
                              <div className="flex items-start gap-3">
                                <div className="flex-shrink-0 w-10 h-10 bg-neutral-100 rounded-full flex items-center justify-center mt-0.5">
                                  <svg className="w-5 h-5 text-neutral-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                  </svg>
                                </div>
                                <div className="flex-1">
                                  <div className="text-xs text-neutral-500 uppercase tracking-wide mb-2">Districts</div>
                                  <div className="flex flex-wrap gap-2">
                                    {project.districts.map((district: any) => (
                                      <span 
                                        key={district.id}
                                        className="inline-block px-3 py-1 bg-neutral-200 text-neutral-700 rounded-full text-sm font-medium"
                                      >
                                        {district.name}
                                      </span>
                                    ))}
                                  </div>
                                </div>
                              </div>
                            )}

                            <div className="grid grid-cols-2 gap-4">
                              {project.start_date && project.end_date && (
                                <div className="flex items-center gap-3">
                                  <div className="flex-shrink-0 w-10 h-10 bg-neutral-100 rounded-full flex items-center justify-center">
                                    <svg className="w-5 h-5 text-neutral-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                  </div>
                                  <div>
                                    <div className="text-xs text-neutral-500 uppercase tracking-wide">Duration</div>
                                    <div className="text-sm font-semibold text-neutral-900">
                                      {new Date(project.start_date).getFullYear()} - {new Date(project.end_date).getFullYear()}
                                    </div>
                                  </div>
                                </div>
                              )}

                              {project.beneficiaries_count && (
                                <div className="flex items-center gap-3">
                                  <div className="flex-shrink-0 w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center">
                                    <svg className="w-5 h-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                                    </svg>
                                  </div>
                                  <div>
                                    <div className="text-xs text-neutral-500 uppercase tracking-wide">Beneficiaries</div>
                                    <div className="text-sm font-semibold text-neutral-900">
                                      {project.beneficiaries_count.toLocaleString()}
                                    </div>
                                  </div>
                                </div>
                              )}
                            </div>

                            {/* Status Badge */}
                            <div className="pt-2">
                              <span className={`inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold ${
                                project.status === 'active' ? 'bg-green-100 text-green-800' :
                                project.status === 'completed' ? 'bg-blue-100 text-blue-800' :
                                project.status === 'ongoing' ? 'bg-yellow-100 text-yellow-800' :
                                project.status === 'planned' ? 'bg-purple-100 text-purple-800' :
                                'bg-neutral-100 text-neutral-800'
                              }`}>
                                {project.status.charAt(0).toUpperCase() + project.status.slice(1)}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </article>
                  );
                })}
              </div>
            </>
          ) : (
            <div className="text-center py-20">
              <div className="inline-flex items-center justify-center w-20 h-20 bg-neutral-100 rounded-full mb-6">
                <svg className="w-10 h-10 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                </svg>
              </div>
              <h3 className="text-2xl font-bold text-neutral-900 mb-3">No Projects Available</h3>
              <p className="text-lg text-neutral-600 mb-8">
                Projects for this program are currently being developed. Check back soon!
              </p>
              <Link 
                href={`/programs/${thematicAreaSlug}`}
                className="inline-flex items-center gap-2 px-6 py-3 bg-primary-500 text-neutral-900 rounded-lg hover:bg-primary-700 transition-colors font-semibold"
              >
                Back to Programs
              </Link>
            </div>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
}

