import React from 'react';
import Link from 'next/link';
import { Play, FileText, Clock, Mic, Calendar } from 'lucide-react';
import { sanitizeHTML } from '../../lib/sanitize';
import { prisma } from '../../lib/prisma';
import { InterviewType } from '@prisma/client';
import EventTimeline from '../../components/EventTimeline';

export const revalidate = 3600;

interface Props {
  searchParams: Promise<{ type?: string }>;
}

export default async function AfroLifePage({ searchParams }: Props) {
  const params = await searchParams;
  const rawFilter = params.type as string || 'ALL';
  const allowedFilters = ['ALL', 'EVENT', 'VIDEO', 'ARTICLE'];
  const filter = allowedFilters.includes(rawFilter) ? rawFilter : 'ALL';

  let items: any[] = [];
  const now = new Date();
  
  try {
    if (filter === 'EVENT') {
        const events = await prisma.event.findMany({
            where: {
                status: 'PUBLISHED',
                publishedAt: {
                    lte: now
                }
            },
            orderBy: { date: 'desc' }
        });
        items = events.map(e => ({
            ...e,
            guestName: 'Événement',
            companyName: e.location,
            excerpt: e.description,
            type: 'EVENT',
            duration: new Date(e.date).toLocaleDateString('fr-FR')
        }));
    } else {
        const where: any = {
            status: 'PUBLISHED',
            publishedAt: {
                lte: now
            }
        };
        if (filter !== 'ALL') {
            where.type = filter as InterviewType;
        }
        const interviews = await prisma.interview.findMany({
            where,
            orderBy: { createdAt: 'desc' }
        });
        items = interviews.map(i => ({ ...i }));
        
        // If 'ALL', we might want to also fetch events and mix them
        if (filter === 'ALL') {
            const events = await prisma.event.findMany({
                where: {
                    status: 'PUBLISHED',
                    publishedAt: {
                        lte: now
                    }
                },
                orderBy: { date: 'desc' },
                take: 10
            });
            const mappedEvents = events.map(e => ({
                ...e,
                guestName: 'Événement',
                companyName: e.location,
                excerpt: e.description,
                type: 'EVENT',
                duration: new Date(e.date).toLocaleDateString('fr-FR')
            }));
            items = [...items, ...mappedEvents].sort((a, b) => 
                new Date(b.createdAt || b.date).getTime() - new Date(a.createdAt || a.date).getTime()
            );
        }
    }
  } catch (error) {
    console.error("Database connection failed on Afro Life page:", error);
    items = [];
  }

  return (
    <div className="bg-white min-h-screen">
      {/* Hero Header */}
      <div className="bg-dark-900 text-white py-20 relative overflow-hidden">
        <div className="absolute inset-0 opacity-30 bg-[url('https://images.unsplash.com/photo-1523580494863-6f3031224c94?ixlib=rb-4.0.3&auto=format&fit=crop&w=1740&q=80')] bg-cover bg-center"></div>
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
           <span className="inline-block py-1 px-3 rounded-full bg-brand-600/20 border border-brand-500 text-brand-400 text-xs font-bold tracking-wider uppercase mb-4">
              Lifestyle & Inspiration
           </span>
           <h1 className="text-4xl md:text-6xl font-serif font-bold mb-6">Afro Life</h1>
           <p className="text-xl text-gray-300 max-w-2xl mx-auto">
             Plongez dans l'intimité des bâtisseurs. Entretiens exclusifs, parcours de vie et leçons de leadership.
           </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Filters */}
        <div className="flex justify-center mb-12 space-x-4">
            <Link 
                href="/afrolife?type=ALL"
                className={`px-6 py-2 rounded-full text-sm font-medium transition-all ${filter === 'ALL' ? 'bg-brand-600 text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            >
                Tout voir
            </Link>
            <Link 
                href="/afrolife?type=VIDEO"
                className={`flex items-center px-6 py-2 rounded-full text-sm font-medium transition-all ${filter === 'VIDEO' ? 'bg-brand-600 text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            >
                <Play className="w-4 h-4 mr-2" /> Vidéos
            </Link>
            <Link 
                href="/afrolife?type=ARTICLE"
                className={`flex items-center px-6 py-2 rounded-full text-sm font-medium transition-all ${filter === 'ARTICLE' ? 'bg-brand-600 text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            >
                <FileText className="w-4 h-4 mr-2" /> Articles
            </Link>
            <Link 
                href="/afrolife?type=EVENT"
                className={`flex items-center px-6 py-2 rounded-full text-sm font-medium transition-all ${filter === 'EVENT' ? 'bg-brand-600 text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            >
                <Calendar className="w-4 h-4 mr-2" /> Événements
            </Link>
        </div>

        {/* Grid or Timeline */}
        {items.length === 0 ? (
          <div className="text-center py-20 bg-gray-50 rounded-2xl border-2 border-dashed border-gray-200">
            <p className="text-gray-500">Aucun contenu trouvé dans cette catégorie.</p>
          </div>
        ) : filter === 'EVENT' ? (
          <EventTimeline events={items} />
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {items.map(item => {
                  const isPastEvent = item.type === 'EVENT' && new Date(item.date) < new Date();
                  
                  return (
                      <Link href={`/afrolife/${(item as any).slug || item.id}`} key={item.id} className={`group block h-full transition-all ${isPastEvent ? 'opacity-60 grayscale-[0.5]' : ''}`}>
                          <div className="relative h-64 rounded-xl overflow-hidden shadow-sm group-hover:shadow-xl transition-all duration-300">
                              <img 
                                  src={item.thumbnailUrl} 
                                  alt={item.title} 
                                  className="w-full h-full object-cover group-hover:scale-[1.05] transition-transform duration-700"
                                  style={{ 
                                    objectPosition: item.coverPosition || '50% 50%',
                                    transform: `scale(${item.coverZoom || 1})`,
                                    transformOrigin: item.coverPosition || '50% 50%'
                                  }}
                              />
                              <div className="absolute inset-0 bg-black/20 group-hover:bg-black/10 transition-colors"></div>
                              
                              {/* Type Badge */}
                              <div className="absolute top-4 left-4">
                                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wide text-white backdrop-blur-md ${
                                    isPastEvent ? 'bg-gray-600/90' :
                                    item.type === 'VIDEO' ? 'bg-red-600/90' : 
                                    item.type === 'EVENT' ? 'bg-amber-600/90' : 'bg-blue-600/90'
                                  }`}>
                                      {item.type === 'VIDEO' ? <Play className="w-3 h-3 mr-1 fill-current" /> : 
                                       item.type === 'EVENT' ? <Calendar className="w-3 h-3 mr-1" /> : <Mic className="w-3 h-3 mr-1" />}
                                      {item.type === 'VIDEO' ? 'Vidéo' : 
                                       item.type === 'EVENT' ? (isPastEvent ? 'Événement Passé' : 'Événement') : 'Interview'}
                                  </span>
                              </div>
      
                              {/* Play Icon Overlay for Videos */}
                              {item.type === 'VIDEO' && (
                                  <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                                      <div className="w-16 h-16 bg-white/30 backdrop-blur-sm rounded-full flex items-center justify-center border border-white/50">
                                          <Play className="w-8 h-8 text-white fill-current ml-1" />
                                      </div>
                                  </div>
                              )}
                          </div>
      
                          <div className="pt-6 px-2">
                              <div className="flex items-center text-xs text-gray-500 mb-3 space-x-3">
                                  <span className={`font-semibold uppercase ${isPastEvent ? 'text-gray-400' : 'text-brand-600'}`}>{item.guestName}</span>
                                  <span className="w-1 h-1 bg-gray-300 rounded-full"></span>
                                  <span className="truncate max-w-[100px]">{item.companyName}</span>
                                  <span className="w-1 h-1 bg-gray-300 rounded-full"></span>
                                  <span className="flex items-center flex-nowrap"><Clock className="w-3 h-3 mr-1 shrink-0"/> {item.duration || 'N/A'}</span>
                              </div>
                              <h3 className={`text-xl font-serif font-bold mb-2 transition-colors leading-tight line-clamp-2 ${isPastEvent ? 'text-gray-500' : 'text-gray-900 group-hover:text-brand-600'}`}>
                                  {item.title}
                              </h3>
                              <div className="text-gray-600 text-sm line-clamp-2 prose-sm" dangerouslySetInnerHTML={{ __html: sanitizeHTML(item.excerpt) }} />
                          </div>
                      </Link>
                  );
              })}
          </div>
        )}
      </div>
    </div>
  );
}
