// src\app\components\admin\blocks\BlogGrid.tsx

'use client';

import { useEffect, useState, useRef } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Calendar, Clock, User, ChevronRight, ArrowRight } from 'lucide-react';
import { BlogGridProps, BlogPost } from '@/lib/page-builder/types';

// Helper function to format date
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// Helper to truncate excerpt
const truncateExcerpt = (excerpt: string | null, length: number) => {
  if (!excerpt) return '';
  if (excerpt.length <= length) return excerpt;
  return excerpt.substring(0, length) + '...';
};

// Helper to get grid classes based on columns
const getGridClass = (columns: number) => {
  switch (columns) {
    case 2:
      return 'grid md:grid-cols-2 gap-6 lg:gap-8';
    case 3:
      return 'grid md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8';
    case 4:
      return 'grid md:grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8';
    default:
      return 'grid md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8';
  }
};

// Hook to fetch blog posts from API
function useBlogPosts(props: BlogGridProps) {
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // Use ref to track previous source to detect changes
  const prevSourceRef = useRef(props.source);

  useEffect(() => {
    let isMounted = true;
    
    const fetchData = async () => {
      // Handle mock data
      if (props.source === 'mock') {
        setLoading(false);
        setError(null);
        
        let filteredPosts = [...(props.mockPosts || [])];
        
        // Apply filters to mock data
        if (props.filterType === 'featured' || props.showFeatured) {
          filteredPosts = filteredPosts.filter(post => post.is_featured === true);
        }
        
        // Limit posts
        const limitedPosts = filteredPosts.slice(0, props.postsToShow || 6);
        
        if (isMounted) {
          setPosts(limitedPosts);
        }
        return;
      }

      // Handle API data
      if (props.source === 'api') {
        setLoading(true);
        setError(null);
        
        try {
          // Build query params
          const params = new URLSearchParams();
          params.append('limit', (props.postsToShow || 6).toString());
          
          if (props.filterType === 'featured' || props.showFeatured) {
            params.append('featured', 'true');
          }

          const response = await fetch(`/api/frontend/getblogs?${params.toString()}`);
          
          if (!response.ok) {
            throw new Error('Failed to fetch posts');
          }
          
          const data = await response.json();
          
          if (!isMounted) return;
          
          // Transform API response to match BlogPost interface
          const transformedPosts: BlogPost[] = data.posts.map((post: BlogPost) => ({
            id: post.id,
            post_category: post.category || post.post_category,
            post_title: post.post_title,
            post_slug: post.post_slug,
            post_content: post.post_content,
            post_excerpt: post.post_excerpt,
            post_featured_image: post.post_featured_image,
            post_featured_image_alt_text: post.post_featured_image_alt_text,
            post_meta_title: post.post_meta_title,
            post_meta_description: post.post_meta_description,
            post_schemas: post.post_schemas,
            author_id: post.author || post.author_id,
            is_indexable: post.is_indexable,
            post_status: post.post_status,
            reading_time_minutes: post.reading_time_minutes,
            is_featured: post.is_featured,
            post_sidebar_id: post.post_sidebar_id,
            post_sidebar_on_mobile: post.post_sidebar_on_mobile,
            post_create_date: post.post_create_date,
            post_update_date: post.post_update_date,
            category: post.category,
            author: post.author
          }));
          
          setPosts(transformedPosts);
        } catch (err) {
          if (isMounted) {
            setError(err instanceof Error ? err.message : 'Failed to load posts');
          }
        } finally {
          if (isMounted) {
            setLoading(false);
          }
        }
      }
    };

    // Force reset posts when source changes
    if (prevSourceRef.current !== props.source) {
      setPosts([]);
      prevSourceRef.current = props.source;
    }

    fetchData();

    return () => {
      isMounted = false;
    };
  }, [
    props.source,
    props.mockPosts,
    props.postsToShow,
    props.filterType,
    props.showFeatured
  ]);

  return { posts, loading, error };
}

// Blog Card Component
function BlogCard({ post }: { post: BlogPost }) {
  // Get category name
  const categoryName = typeof post.post_category === 'object' 
    ? post.post_category?.name 
    : post.category?.name || 'Uncategorized';
  
  const categorySlug = typeof post.post_category === 'object'
    ? post.post_category?.slug
    : post.category?.slug || '';

  // Get author name
  const authorName = typeof post.author_id === 'object'
    ? post.author_id?.full_name
    : post.author?.full_name || 'Unknown Author';

  // Generate post URL
  const postUrl = `/blog/${post.post_slug}`;

  // Get featured image
  const featuredImage = post.post_featured_image || '/images/placeholder-blog.jpg';
  const imageAlt = post.post_featured_image_alt_text || post.post_title;

  // Format date
  const formattedDate = formatDate(post.post_create_date);

  // Get excerpt
  const excerpt = truncateExcerpt(
    post.post_excerpt || post.post_content.substring(0, 150),
    120
  );

  return (
    <article className="group bg-white rounded-lg shadow-md overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-xl">
      {/* Image */}
      <Link href={postUrl} className="block relative overflow-hidden">
        <div className="aspect-video relative">
          <Image
            src={featuredImage}
            alt={imageAlt}
            fill
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            className="object-cover transition-transform duration-500 group-hover:scale-110"
          />
          
          {/* Category badge */}
          <div className="absolute top-3 left-3 z-10">
            <Link
              href={`/blog/category/${categorySlug}`}
              className="inline-block px-3 py-1 text-xs font-medium rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors"
            >
              {categoryName}
            </Link>
          </div>
        </div>
      </Link>

      {/* Content */}
      <div className="p-5">
        {/* Title */}
        <Link href={postUrl}>
          <h3 className="text-lg font-bold mb-2 hover:text-blue-600 transition-colors line-clamp-2">
            {post.post_title}
          </h3>
        </Link>

        {/* Excerpt */}
        <p className="text-gray-600 text-sm mb-3 line-clamp-3">
          {excerpt}
        </p>

        {/* Meta information */}
        <div className="flex flex-wrap items-center gap-3 text-xs text-gray-500 mb-4">
          <div className="flex items-center gap-1">
            <User className="w-3 h-3" />
            <span>{authorName}</span>
          </div>
          
          <div className="flex items-center gap-1">
            <Calendar className="w-3 h-3" />
            <span>{formattedDate}</span>
          </div>
          
          {post.reading_time_minutes && (
            <div className="flex items-center gap-1">
              <Clock className="w-3 h-3" />
              <span>{post.reading_time_minutes} min read</span>
            </div>
          )}
        </div>

        {/* Read More Button */}
        <Link
          href={postUrl}
          className="inline-flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700 transition-colors group/btn"
        >
          <span>Read More</span>
          <ChevronRight className="w-4 h-4 transition-transform group-hover/btn:translate-x-1" />
        </Link>
      </div>
    </article>
  );
}

// Main Blog Grid Component
export default function BlogGrid(props: BlogGridProps) {
  const { 
    id,
    title = 'Latest Blog Posts',
    description,
    columns = 3,
    postsToShow = 6,
    showViewAllButton = true,
    viewAllText = 'View All Posts',
    viewAllLink = '/blog',
    className = ''
  } = props;

  const { posts, loading, error } = useBlogPosts(props);

  // Show loading skeleton only on initial load
  if (loading && posts.length === 0) {
    return (
      <section id={id} className={`py-12 px-4 ${className}`}>
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <div className="h-8 w-64 bg-gray-200 rounded animate-pulse mx-auto mb-4" />
            {description && <div className="h-4 w-96 bg-gray-200 rounded animate-pulse mx-auto" />}
          </div>
          <div className={getGridClass(columns)}>
            {[...Array(postsToShow)].map((_, i) => (
              <div key={i} className="bg-gray-100 rounded-lg p-4 animate-pulse">
                <div className="aspect-video bg-gray-200 rounded-lg mb-4" />
                <div className="h-4 bg-gray-200 rounded w-3/4 mb-2" />
                <div className="h-4 bg-gray-200 rounded w-1/2 mb-4" />
                <div className="h-3 bg-gray-200 rounded w-full mb-2" />
                <div className="h-3 bg-gray-200 rounded w-5/6" />
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section id={id} className={`py-12 px-4 ${className}`}>
        <div className="max-w-7xl mx-auto text-center">
          <div className="bg-red-50 text-red-600 p-6 rounded-lg">
            <p className="font-medium">Error loading blog posts</p>
            <p className="text-sm mt-2">{error}</p>
          </div>
        </div>
      </section>
    );
  }

  if (posts.length === 0 && !loading) {
    return (
      <section id={id} className={`py-12 px-4 ${className}`}>
        <div className="max-w-7xl mx-auto text-center">
          <div className="bg-gray-50 text-gray-600 p-6 rounded-lg">
            <p className="font-medium">No blog posts found</p>
            <p className="text-sm mt-2">Check back later for new content</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id={id} className={`py-12 px-4 ${className}`}>
      <div className="max-w-7xl mx-auto">
        {/* Section Header */}
        {(title || description) && (
          <div className="text-center mb-12">
            {title && <h2 className="text-3xl md:text-4xl font-bold mb-4">{title}</h2>}
            {description && <p className="text-xl text-gray-600 max-w-2xl mx-auto">{description}</p>}
          </div>
        )}

        {/* Blog Grid */}
        <div className={getGridClass(columns)}>
          {posts.map((post) => (
            <BlogCard key={post.id} post={post} />
          ))}
        </div>

        {/* View All Button */}
        {showViewAllButton && posts.length > 0 && (
          <div className="text-center mt-12">
            <Link
              href={viewAllLink}
              className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors group"
            >
              <span>{viewAllText}</span>
              <ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-1" />
            </Link>
          </div>
        )}
      </div>
    </section>
  );
}