"use client";

import React, { useState } from 'react';
import Image from 'next/image';
import { ArrowLeft, ArrowRight } from '@untitledui/icons';
import { Carousel } from '../elements/carousel/carousel-base';
import { Button, PaginationPageMinimalCenter, PhotoWithFallback, RoundButton } from '../elements';
import { cx } from '../../utils/cx';
import { isVideoUrl } from '../../utils/photo-helpers';
import type { SocialPost } from '../../types/api/social-post';

/** Get display image URLs from post (excludes video URLs so img/PhotoWithFallback don't break) */
function getPostImageUrls(post: SocialPost): string[] {
  const videoSet = post.video_urls?.length ? new Set(post.video_urls) : null;
  const isVideo = (url: string) => isVideoUrl(url) || (videoSet !== null && videoSet.has(url));
  if (post.image_urls?.length) {
    return post.image_urls.filter((url) => !isVideo(url));
  }
  const attachments = post.photo_attachments || [];
  const sorted = [...attachments].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));
  return sorted
    .map((pa) => pa.photo?.large_url || pa.photo?.original_url || pa.photo?.medium_url || pa.photo?.thumbnail_url)
    .filter((url): url is string => Boolean(url))
    .filter((url) => !isVideo(url));
}

interface SocialMediaGridProps {
    socialPosts?: SocialPost[] | null;
    title?: string;
    subtitle?: string;
}

const getPlatformBadge = (platform?: string) => {
    const platformLower = platform?.toLowerCase() || 'social';
    const colors: Record<string, string> = {
        facebook: 'bg-blue-600',
        instagram: 'bg-pink-600',
        twitter: 'bg-blue-400',
        linkedin: 'bg-blue-700',
        youtube: 'bg-red-600',
    };
    return colors[platformLower] || 'bg-gray-600';
};

const formatDate = (dateString?: string) => {
    if (!dateString) return 'Recent';
    try {
        return new Date(dateString).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    } catch {
        return 'Recent';
    }
};


export const SocialMediaGrid = ({
    socialPosts: postsData,
    title = "",
    subtitle = "",
}: SocialMediaGridProps) => {
    const posts = Array.isArray(postsData) ? postsData : [];
    const postsPerPage = 8;
    const backgroundColor = "bg-primary";
    const className = "";
    
    const [currentPage, setCurrentPage] = useState(1);
    
    const totalPages = Math.ceil(posts.length / postsPerPage);
    const startIndex = (currentPage - 1) * postsPerPage;
    const endIndex = startIndex + postsPerPage;
    const paginatedPosts = posts.slice(startIndex, endIndex);

    return (
        <section className={`${backgroundColor} py-16 md:py-24 ${className}`}>
            <div className="mx-auto w-full max-w-container px-4 md:px-8">
                {(title || subtitle) && (
                    <div className="mx-auto mb-12 flex w-full max-w-3xl flex-col items-center text-center">
                        {title && (
                            <h2 className="text-display-sm font-semibold text-primary md:text-display-md">
                                {title}
                            </h2>
                        )}
                        {subtitle && (
                            <p className="mt-4 text-lg text-tertiary md:mt-5 md:text-xl">
                                {subtitle}
                            </p>
                        )}
                    </div>
                )}

                {paginatedPosts.length > 0 ? (
                    <>
                        <ul className="grid grid-cols-1 gap-x-8 gap-y-10 sm:grid-cols-2 md:gap-y-12 lg:grid-cols-3 xl:grid-cols-4">
                            {paginatedPosts.map((post, index) => {
                                const images = getPostImageUrls(post);
                                const hasMultipleImages = images.length > 1;
                                const firstImage = images[0];
                                const content = post.content_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
                                
                                return (
                                    <li key={post.id || index} className="flex flex-col gap-5 md:gap-6">
                                        <div className="relative h-78 w-full overflow-hidden md:h-74">
                                            {firstImage ? (
                                                hasMultipleImages ? (
                                                    <Carousel.Root
                                                        opts={{ align: "start" }}
                                                        className="h-full w-full"
                                                    >
                                                        <Carousel.Content className="h-full">
                                                            {images.map((imgUrl: string, imgIndex: number) => (
                                                                <Carousel.Item key={imgIndex} className="h-full">
                                                                    <Image 
                                                                        src={imgUrl} 
                                                                        alt={`${post.platform} post image ${imgIndex + 1}`}
                                                                        className="size-full object-cover"
                                                                        width={600}
                                                                        height={600}
                                                                    />
                                                                </Carousel.Item>
                                                            ))}
                                                        </Carousel.Content>
                                                        <div className="absolute bottom-4 left-1/2 flex -translate-x-1/2 gap-2">
                                                            <Carousel.PrevTrigger asChild>
                                                                <RoundButton icon={ArrowLeft} />
                                                            </Carousel.PrevTrigger>
                                                            <Carousel.NextTrigger asChild>
                                                                <RoundButton icon={ArrowRight} />
                                                            </Carousel.NextTrigger>
                                                        </div>
                                                    </Carousel.Root>
                                                ) : (
                                                    <PhotoWithFallback
                                                        item={post}
                                                        photoUrl={firstImage}
                                                        photoAlt={`${post.platform} post`}
                                                        fallbackId={`social-post-${post.id || index}`}
                                                        className="size-full object-cover"
                                                    />
                                                )
                                            ) : (
                                                <PhotoWithFallback
                                                    item={post}
                                                    photoUrl={undefined}
                                                    photoAlt={`${post.platform} post`}
                                                    fallbackId={`social-post-${post.id || index}`}
                                                    className="size-full object-cover"
                                                />
                                            )}
                                            
                                            {post.platform && (
                                                <div className={cx(
                                                    "absolute top-4 right-4 rounded-full px-3 py-1.5 text-sm font-semibold text-white",
                                                    getPlatformBadge(post.platform)
                                                )}>
                                                    {post.platform.charAt(0).toUpperCase() + post.platform.slice(1)}
                                                </div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-4">
                                            <div className="flex items-center justify-between">
                                                <span className="text-sm text-tertiary">{formatDate(post.posted_at)}</span>
                                            </div>
                                            
                                            {content && (
                                                <p className="text-md text-tertiary line-clamp-4">
                                                    {content}
                                                </p>
                                            )}
                                            
                                            <Button 
                                                href={post.external_post_url || `https://${post.platform.toLowerCase()}.com`}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                color="link-color"
                                                size="md"
                                            >
                                                View on {post.platform}
                                            </Button>
                                        </div>
                                    </li>
                                );
                            })}
                        </ul>
                        
                        {totalPages > 1 && (
                            <div className="mt-12">
                                <PaginationPageMinimalCenter
                                    page={currentPage}
                                    total={totalPages}
                                    onPageChange={setCurrentPage}
                                />
                            </div>
                        )}
                    </>
                ) : (
                    <div className="text-center py-12">
                        <p className="text-gray-500">No social media posts available</p>
                    </div>
                )}
            </div>
        </section>
    );
};
