"use client";

import axios from "axios";
import { ApiServerBaseUrl } from "@/utils/baseurl.utils";
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

type MediaItem = {
    id: string;
    caption?: string;
    media_type: string;
    media_url: string;
    thumbnail_url?: string;
    permalink: string;
    timestamp: string;
    like_count?: number;
    comments_count?: number;
};

const Sales = () => {

    const router = useRouter()

    const [media, setMedia] = useState<MediaItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {
        const fetchMedia = async () => {
            try {
                const res = await axios.get(`${ApiServerBaseUrl}/social/media?userId=${localStorage.getItem('user_email')}`);
                setMedia(res.data?.data || []);
            } catch (err: any) {
                setError(
                    err.response?.data?.message || err.message || "Failed to fetch media"
                );
            } finally {
                setLoading(false);
            }
        };
        fetchMedia();
    }, []);

    return (    
        <div className="
            min-h-screen p-6
            bg-gradient-to-br from-[#0073C6]/25 via-[#E44DB3]/20 to-[#0047A3]/25
        ">
            <h2 className="text-3xl font-extrabold mb-8 tracking-wide text-gray-900">
                Instagram Media Library
            </h2>

            {loading && (
                <p className="text-gray-700 text-lg">Loading media...</p>
            )}

            {error && (
                <p className="text-red-600 text-lg">Error: {error}</p>
            )}

            {/* Premium Media Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-7">
                {media?.map((item) => (
                    <div
                        key={item.id}
                        className="
                            backdrop-blur-xl bg-white/30 border border-white/40
                            rounded-3xl shadow-2xl overflow-hidden
                            hover:scale-[1.03] hover:shadow-xl transition-all duration-300
                        "
                    >
                        {/* IMAGE */}
                        {item.media_type === "IMAGE" && (
                            <div className="relative">
                                <img
                                    src={item.media_url}
                                    alt="instagram media"
                                    className="w-full h-72 object-cover"
                                />
                                <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent"></div>
                            </div>
                        )}

                        {/* VIDEO */}
                        {item.media_type === "VIDEO" && (
                            <div className="relative">
                                <video
                                    src={item.media_url}
                                    poster={item.thumbnail_url}
                                    className="w-full h-72 object-cover"
                                    autoPlay
                                    loop
                                    muted
                                    playsInline
                                />

                                {/* Gradient Overlay */}
                                <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent"></div>
                            </div>
                        )}


                        {/* Content Section */}
                        <div className="p-4">
                            {/* Caption */}
                            {item.caption && (
                                <p className="text-sm text-gray-800 mb-3 line-clamp-3 leading-relaxed">
                                    {item.caption}
                                </p>
                            )}

                            {/* Like + Comment */}
                            <div className="flex items-center justify-between text-sm text-gray-700 mb-4">
                                <p>❤️ {item.like_count || 0}</p>
                                <p>💬 {item.comments_count || 0}</p>
                            </div>

                            {/* Buttons */}
                            <div className="flex gap-3 mt-2">
                                {/* View on Instagram */}
                                <a
                                    href={item.permalink}
                                    target="_blank"
                                    className="
            flex-1 text-center
            bg-gradient-to-r from-blue-600 to-purple-600
            hover:from-blue-700 hover:to-purple-700
            text-white py-2 rounded-xl
            font-semibold shadow-lg
            transition-all duration-300
        "
                                >
                                    View on Instagram
                                </a>

                                {/* View Details */}
                                <button
                                    onClick={() => router.push(`/social-media-posts/${item.id}`)}
                                    className="
            flex-1 text-center
          bg-gradient-to-r from-[#0073C6] to-[#E44DB3]
                            text-white shadow-md  hover:to-purple-700
            text-white py-2 rounded-xl
            font-semibold shadow-lg
            transition-all duration-300 "
                                >
                                    View Details
                                </button>
                            </div>
                        </div>

                        {/* Badge */}
                        <span className="
                            absolute top-3 right-3
                            bg-black/30 backdrop-blur-md
                            text-white text-xs font-bold
                            px-3 py-1 rounded-full shadow-lg
                        ">
                            {item.media_type}
                        </span>
                    </div>
                ))}
            </div>

            {media.length === 0 && !loading && (
                <p className="text-gray-700 mt-8">No media available.</p>
            )}
        </div>
    );
};

export default Sales;
