import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { KeywordBadge } from '@/components/ui/keyword-badge';
import Footer from '@/pages/home/partials/Footer';
import { Link, router } from '@inertiajs/react';
import { Edit, Search } from 'lucide-react';
import { useState } from 'react';
import { route } from 'ziggy-js';
import BrandLogo from '../home/partials/BrandLogo';

interface MemeMedia {
    ids: string;
    name: string;
    description: string;
    keywords: string[];
    action_keywords: string[];
    emotion_keywords: string[];
    misc_keywords: string[];
    mov_url: string;
    webm_url: string;
    gif_url: string;
    webp_url: string;
    slug: string;
}

interface PaginationLinks {
    url: string | null;
    label: string;
    active: boolean;
}

interface PaginatedMemes {
    data: MemeMedia[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: PaginationLinks[];
}

interface Props {
    memes: PaginatedMemes;
    types: string[];
    popularKeywords: string[];
    filters: {
        search?: string;
    };
}

export default function MemesIndex({ memes, popularKeywords, filters }: Props) {
    const [search, setSearch] = useState(filters.search || '');

    const handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        navigateToSearch(search);
    };

    const handleKeywordClick = (keyword: string) => {
        setSearch(keyword);
        navigateToSearch(keyword);
    };

    const navigateToSearch = (searchTerm: string) => {
        if (!searchTerm.trim()) {
            router.get(route('memes.index'));
            return;
        }

        const trimmedSearch = searchTerm.trim();

        // Convert spaces to + for URL segment
        const urlSegment = trimmedSearch.replace(/\s+/g, '+');
        router.get(route('memes.search', urlSegment));
    };

    const handlePageChange = (url: string) => {
        router.get(url);
    };

    return (
        <>
            <div className="min-h-screen bg-neutral-50 pb-10 dark:bg-black">
                <div className="container mx-auto px-4 pt-8 pb-0">
                    <BrandLogo className="py-3"></BrandLogo>
                    {/* Header */}
                    <div className="mb-8 text-center">
                        <h1 className="text-foreground mb-4 text-4xl font-bold">Meme Library</h1>
                        <p className="text-muted-foreground mx-auto max-w-2xl text-xl">
                            Thousands of memes ready for TikTok, Reels, Threads and YouTube Shorts. No signup needed - click any meme to start
                            creating!
                        </p>
                    </div>

                    {/* Search and Filters */}
                    <Card className="mb-8">
                        <CardContent className="p-6">
                            <form onSubmit={handleSearch} className="mb-4 flex flex-col gap-4 md:flex-row">
                                <div className="flex-1">
                                    <div className="relative">
                                        <Search className="text-muted-foreground absolute top-4 left-4 h-5 w-5" />
                                        <Input
                                            type="text"
                                            placeholder="Search memes..."
                                            value={search}
                                            onChange={(e) => setSearch(e.target.value)}
                                            className="h-12 pl-12 text-lg"
                                        />
                                    </div>
                                </div>
                                <Button
                                    type="submit"
                                    size="lg"
                                    className="h-12 bg-gradient-to-r from-purple-600 to-pink-600 text-lg text-white hover:from-purple-700 hover:to-pink-700"
                                >
                                    Search
                                </Button>
                            </form>

                            {/* Popular Keywords */}
                            <div className="mt-4">
                                <h3 className="text-foreground mb-3 text-sm font-medium">Popular Keywords</h3>
                                <div className="flex flex-wrap gap-2">
                                    {popularKeywords.map((keyword) => (
                                        <KeywordBadge key={keyword} keyword={keyword} size="lg" />
                                    ))}
                                </div>
                            </div>

                            {/* Active Search */}
                            {filters.search && (
                                <div className="mt-4 flex flex-wrap gap-2">
                                    <Badge variant="secondary" className="flex items-center gap-1">
                                        Search: {filters.search}
                                        <button
                                            onClick={() => {
                                                setSearch('');
                                                router.get(route('memes.index'));
                                            }}
                                            className="ml-1 hover:text-red-500"
                                        >
                                            ×
                                        </button>
                                    </Badge>
                                </div>
                            )}
                        </CardContent>
                    </Card>

                    {/* Results Count */}
                    <div className="mb-6 flex items-center justify-between">
                        <p className="text-muted-foreground">
                            Showing {memes.data.length} of {memes.total} memes
                        </p>
                    </div>

                    {/* Memes Grid */}
                    <div className="xs:grid-cols-2 mb-8 grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6">
                        {memes.data.map((meme) => (
                            <Card key={meme.ids} className="group flex flex-col overflow-hidden p-0 transition-shadow hover:shadow-lg">
                                <div className="relative aspect-[9/16] overflow-hidden bg-[#00FF00]">
                                    <img
                                        src={meme.webp_url}
                                        alt={meme.name}
                                        className="h-full w-full object-cover transition-transform group-hover:scale-105"
                                    />
                                    <Link
                                        href={route('memes.show', meme.slug)}
                                        className="bg-opacity-0 absolute inset-0 flex items-center justify-center transition-all group-hover:opacity-40 hover:bg-black"
                                    >
                                        <Edit className="h-8 w-8 text-white opacity-0 transition-opacity group-hover:opacity-100" />
                                    </Link>
                                </div>
                                <div className="flex flex-grow flex-col px-4 pt-0 pb-4">
                                    <h3 className="text-foreground mb-2 line-clamp-2 text-sm font-semibold">{meme.name}</h3>
                                    <div className="mb-3 flex flex-wrap gap-1">
                                        {meme.keywords?.slice(0, 6).map((keyword, index) => <KeywordBadge key={index} keyword={keyword} />)}
                                        {meme.keywords && meme.keywords.length > 6 && (
                                            <Badge variant="secondary" className="text-xs">
                                                +{meme.keywords.length - 6} more
                                            </Badge>
                                        )}
                                    </div>
                                    <div className="mt-auto">
                                        <Link href={route('memes.show', meme.slug)}>
                                            <Button
                                                size="sm"
                                                className="w-full bg-gradient-to-r from-purple-600 to-pink-600 text-white hover:from-purple-700 hover:to-pink-700"
                                            >
                                                Use meme
                                            </Button>
                                        </Link>
                                    </div>
                                </div>
                            </Card>
                        ))}
                    </div>

                    {/* Pagination */}
                    {memes.last_page > 1 && (
                        <div className="flex items-center justify-center gap-2">
                            {memes.links.map((link, index) => (
                                <Button
                                    key={index}
                                    variant={link.active ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => link.url && handlePageChange(link.url)}
                                    disabled={!link.url}
                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                />
                            ))}
                        </div>
                    )}
                </div>
                <Footer />
            </div>
        </>
    );
}
