"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { ArrowUpRight } from "lucide-react";
import { cn } from "@/lib/utils";

interface Pin {
    title: string;
    link: string;
    image: string;
}

export default function PinterestFeed() {
    const [pins, setPins] = useState<Pin[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);
    const [visibleCount, setVisibleCount] = useState<number>(8);

    useEffect(() => {
        const fetchPins = async () => {
            try {
                const res = await fetch("/api/pinterest");
                const data = await res.json();
                if (data.success) {
                    // Filter out any pins that don't have images
                    const validPins = data.pins.filter((pin: Pin) => pin.image && pin.image.trim() !== "");
                    setPins(validPins); // Keep all valid pins to support load more pagination
                } else {
                    setError(data.error || "Failed to load feed");
                }
            } catch (err: any) {
                setError(err.message || "Something went wrong");
            } finally {
                setLoading(false);
            }
        };

        fetchPins();
    }, []);

    // Pinterest Logo SVG
    const PinterestIcon = () => (
        <svg viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
            <path d="M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.906 2.17-2.906 1.024 0 1.517.769 1.517 1.691 0 1.029-.655 2.57-.992 3.996-.283 1.195.599 2.169 1.777 2.169 2.133 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.005-4.882-3.409 0-5.413 2.561-5.413 5.207 0 1.03.397 2.133.893 2.733a.3.3 0 0 1 .069.288c-.098.408-.315 1.279-.358 1.458-.058.24-.192.291-.444.175-1.66-.772-2.697-3.193-2.697-5.138 0-4.186 3.041-8.03 8.78-8.03 4.609 0 8.191 3.284 8.191 7.674 0 4.581-2.89 8.268-6.906 8.268-1.348 0-2.616-.701-3.05-1.53l-1.047 3.99c-.378 1.442-1.402 3.249-2.083 4.354 1.127.348 2.317.537 3.551.537 6.621 0 11.986-5.37 11.986-11.986C23.99 5.367 18.634 0 12.017 0z" />
        </svg>
    );

    return (
        <section id="pinterest-gallery-section" className="py-24 bg-white border-t border-zinc-100 relative overflow-hidden">
            {/* Background design elements */}
            <div className="absolute top-1/2 left-1/3 w-80 h-80 bg-brand-accent/5 rounded-full filter blur-3xl pointer-events-none opacity-40" />

            <div className="max-w-[1400px] mx-auto px-6 relative z-10">
                {/* Header */}
                <div className="flex flex-col md:flex-row md:items-end justify-between gap-8 mb-16 text-center md:text-left">
                    <div className="max-w-2xl">
                        <div className="flex items-center justify-center md:justify-start gap-4 mb-4">
                            <div className="h-[1.5px] w-8 bg-brand-accent" />
                            <span className="text-[10px] md:text-[11px] font-semibold text-brand-accent uppercase tracking-[0.3em] md:tracking-[0.4em] flex items-center gap-2">
                                <PinterestIcon />
                                Inspiration Gallery
                            </span>
                        </div>
                        <h2 className="text-3xl md:text-5xl font-bold text-brand-dark tracking-tight leading-none">
                            Discover Us on <span className="text-brand-accent">Pinterest</span>
                        </h2>
                        <p className="text-xs md:text-sm text-zinc-500 font-medium leading-relaxed mt-4 max-w-xl">
                            Explore our latest designs, installation highlights, and roofing inspirations synced directly from our official Pinterest board.
                        </p>
                    </div>

                    <a
                        href="https://www.pinterest.com/irooflk"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="mx-auto md:mx-0 inline-flex items-center justify-center bg-brand-accent hover:bg-red-800 text-white px-8 py-4 rounded-xl text-[11px] font-medium uppercase tracking-[0.2em] transition-all duration-300 hover:scale-105 active:scale-95 shadow-md shadow-brand-dark/10 hover:shadow-brand-accent/20 cursor-pointer"
                    >
                        Visit Pinterest Profile
                        <ArrowUpRight className="w-4 h-4 ml-2" />
                    </a>
                </div>

                {/* Skeletons Loading State */}
                {loading && (
                    <div className="columns-2 md:columns-3 lg:columns-4 gap-6 space-y-6">
                        {[1, 2, 3, 4, 5, 6, 7, 8].map((i) => (
                            <div
                                key={i}
                                className={cn(
                                    "w-full rounded-2xl bg-zinc-50 border border-zinc-100 overflow-hidden break-inside-avoid shadow-sm animate-pulse",
                                    i % 2 === 0 ? "h-64" : "h-80"
                                )}
                            />
                        ))}
                    </div>
                )}

                {/* Error State */}
                {!loading && error && (
                    <div className="text-center py-16 bg-red-50/50 rounded-2xl border border-red-100 max-w-xl mx-auto">
                        <p className="text-sm font-semibold text-red-600 mb-4">Could not load Pinterest Feed</p>
                        <a
                            href="https://www.pinterest.com/irooflk"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center text-xs font-bold uppercase tracking-wider text-brand-accent hover:text-brand-dark transition-colors"
                        >
                            View directly on Pinterest <ArrowUpRight className="w-3.5 h-3.5 ml-1" />
                        </a>
                    </div>
                )}

                {/* Masonry Feed */}
                {!loading && !error && pins.length > 0 && (
                    <div>
                        <div className="columns-2 md:columns-3 lg:columns-4 gap-6 space-y-6">
                            {pins.slice(0, visibleCount).map((pin, idx) => (
                                <a
                                    key={idx}
                                    href={pin.link}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="group relative block w-full rounded-2xl overflow-hidden border border-zinc-100 bg-zinc-50 shadow-sm hover:shadow-xl hover:border-brand-accent/20 transition-all duration-300 break-inside-avoid hover:-translate-y-1 cursor-pointer"
                                >
                                    {/* Pin Image */}
                                    <div className="relative w-full h-auto">
                                        {/* We use an unoptimized img tag or Next Image with layout. Since height varies, standard img is great inside masonry columns */}
                                        <img
                                            src={pin.image}
                                            alt={pin.title || "Pinterest Inspiration"}
                                            className="w-full h-auto object-cover block group-hover:scale-[1.03] transition-transform duration-700"
                                            loading="lazy"
                                        />
                                    </div>

                                    {/* Custom Glassmorphic Slide-up Overlay */}
                                    <div className="absolute inset-0 bg-gradient-to-t from-brand-dark/90 via-brand-dark/40 to-transparent opacity-0 group-hover:opacity-100 transition-all duration-500 flex flex-col justify-end p-6">
                                        <div className="transform translate-y-4 group-hover:translate-y-0 transition-transform duration-500 flex flex-col gap-2">
                                            <div className="w-8 h-8 rounded-full bg-brand-accent flex items-center justify-center text-white shadow-lg self-start">
                                                <PinterestIcon />
                                            </div>
                                            <p className="text-white text-xs font-medium leading-relaxed line-clamp-3 text-left">
                                                {pin.title || "Explore this design inspiration on our Pinterest board."}
                                            </p>
                                            <span className="text-[9px] font-bold text-white/50 uppercase tracking-widest text-left mt-2 flex items-center gap-1">
                                                View Pin <ArrowUpRight className="w-3 h-3" />
                                            </span>
                                        </div>
                                    </div>
                                </a>
                            ))}
                        </div>

                        {/* Pagination Buttons */}
                        <div className="flex flex-wrap justify-center items-center gap-4 mt-12">
                            {pins.length > visibleCount && (
                                <button
                                    onClick={() => setVisibleCount(prev => prev + 8)}
                                    className="inline-flex items-center justify-center bg-brand-accent hover:bg-red-800 text-white px-8 py-3.5 rounded-xl text-[10px] md:text-[11px] font-semibold uppercase tracking-[0.2em] transition-all duration-300 hover:scale-105 active:scale-95 shadow-md shadow-brand-dark/10 hover:shadow-brand-accent/20 cursor-pointer"
                                >
                                    Load More Pins
                                </button>
                            )}

                            {visibleCount > 8 && (
                                <button
                                    onClick={() => {
                                        setVisibleCount(8);
                                        document.getElementById("pinterest-gallery-section")?.scrollIntoView({ behavior: "smooth" });
                                    }}
                                    className="inline-flex items-center justify-center bg-zinc-800 hover:bg-zinc-900 text-white px-8 py-3.5 rounded-xl text-[10px] md:text-[11px] font-bold uppercase tracking-[0.2em] transition-all duration-300 hover:scale-105 active:scale-95 shadow-md shadow-zinc-800/10 cursor-pointer"
                                >
                                    Show Less
                                </button>
                            )}
                        </div>
                    </div>
                )}
            </div>
        </section>
    );
}
