"use client"

import { useState, useRef, useEffect } from "react"
import { X, Search, Check, ChevronDown } from "lucide-react"
import { Button } from "@/Components/UI/Button"


export default function SideGallery({ isOpen, onClose, onApply, t, media }) {
    const [activeTab, setActiveTab] = useState("all")
    const [selectedPlatform, setSelectedPlatform] = useState("all")
    const [searchQuery, setSearchQuery] = useState("")
    const [selectedMedia, setSelectedMedia] = useState([])
    const [isPlatformDropdownOpen, setIsPlatformDropdownOpen] = useState(false)
    const panelRef = useRef(null)



    const filteredMedia = media.filter((item) => {
        const matchesTab = activeTab === "all" || item.type === activeTab
        const matchesPlatform = selectedPlatform === "all" || item.platform === selectedPlatform
        const matchesSearch = item.alt.toLowerCase().includes(searchQuery.toLowerCase())
        return matchesTab && matchesPlatform && matchesSearch
    })

    const toggleMediaSelection = (mediaId) => {
        setSelectedMedia((prev) => {
            if (prev.includes(mediaId)) {
                return prev.filter((id) => id !== mediaId)
            } else {
                return [...prev, mediaId]
            }
        })
    }

    // Handle apply button
    const handleApply = () => {
        const selectedMediaItems = media.filter((item) => selectedMedia.includes(item.id))
        onApply(selectedMediaItems)
        setSelectedMedia([])
        onClose()
    }

    // Handle click outside to close
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (panelRef.current && !panelRef.current.contains(event.target)) {
                onClose()
            }
        }

        if (isOpen) {
            document.addEventListener("mousedown", handleClickOutside)
            document.addEventListener("touchstart", handleClickOutside)
        }

        return () => {
            document.removeEventListener("mousedown", handleClickOutside)
            document.removeEventListener("touchstart", handleClickOutside)
        }
    }, [isOpen, onClose])

    // Platform options similar to PostTemplate.jsx
    const platforms = [
        { id: "all", name: "All Platform" },
        { id: "facebook", name: "Facebook" },
        { id: "instagram", name: "Instagram" },
        { id: "x", name: "X" },
        { id: "youtube", name: "YouTube" },
        { id: "linkedin", name: "LinkedIn" },
        { id: "tiktok", name: "TikTok" },
        { id: "threads", name: "Threads" },
    ]

    // Platform selection handler
    const handlePlatformSelect = (platformId) => {
        setSelectedPlatform(platformId)
        setIsPlatformDropdownOpen(false)
    }

    if (!isOpen) return null

    return (
        <>
            {/* Backdrop */}
            <div className="fixed inset-0 bg-black/20 backdrop-blur-sm z-40" />

            {/* Side Panel */}
            <div
                ref={panelRef}
                className="fixed top-0 right-0 h-full w-96 bg-white dark:bg-zinc-900 shadow-2xl z-50 transform transition-transform duration-300 ease-out flex flex-col"
            >
                {/* Header */}
                <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-zinc-800 flex-shrink-0">
                    <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{t("Gallery")}</h2>
                    <button
                        onClick={onClose}
                        className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                    >
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Platform Dropdown and Search Section */}
                <div className="p-4 space-y-4 border-b border-gray-200 dark:border-zinc-800 flex-shrink-0">
                    {/* Search Bar */}
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder={t("Search media")}
                            className="w-full pl-10 pr-4 py-2 bg-gray-100 dark:bg-gray-700 border-0 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-cyan-500 focus:bg-white dark:focus:bg-gray-600 transition-colors"
                        />
                    </div>

                    {/* Platform Dropdown */}
                    <div className="relative">
                        <button
                            onClick={() => setIsPlatformDropdownOpen(!isPlatformDropdownOpen)}
                            className="w-full flex items-center justify-between px-4 py-2 bg-gray-100 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-gray-100 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                        >
                            <span>{platforms.find((p) => p.id === selectedPlatform)?.name}</span>
                            <ChevronDown className="w-4 h-4" />
                        </button>

                        {isPlatformDropdownOpen && (
                            <div className="absolute top-full left-0 right-0 mt-1 bg-white dark:bg-zinc-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-10">
                                {platforms.map((platform) => (
                                    <button
                                        key={platform.id}
                                        onClick={() => handlePlatformSelect(platform.id)}
                                        className="w-full text-left px-4 py-2 text-gray-900 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-600 first:rounded-t-lg last:rounded-b-lg transition-colors"
                                    >
                                        {platform.name}
                                    </button>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* Tab Navigation */}
                <div className="flex items-center space-x-1 p-4 pb-2 flex-shrink-0">
                    <button
                        onClick={() => setActiveTab("all")}
                        className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === "all"
                            ? "bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
                            : "text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                            }`}
                    >
                        {t("All")}
                    </button>
                    <button
                        onClick={() => setActiveTab("image")}
                        className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === "image"
                            ? "bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
                            : "text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                            }`}
                    >
                        {t("Image")}
                    </button>
                    <button
                        onClick={() => setActiveTab("video")}
                        className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === "video"
                            ? "bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary"
                            : "text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                            }`}
                    >
                        {t("Video")}
                    </button>
                </div>

                {/* Media Grid */}
                <div className="flex-1 overflow-y-auto px-4 min-h-0">
                    <div className="grid grid-cols-2 gap-3 pb-4">
                        {filteredMedia.map((item) => (
                            <div
                                key={item.id}
                                className="relative aspect-square rounded-lg overflow-hidden cursor-pointer group"
                                onClick={() => toggleMediaSelection(item.id)}
                            >

                                {item.isVideo ? (
                                    <video
                                        src={item.thumbnail}
                                        muted
                                        playsInline
                                        loop
                                        autoPlay
                                        className="w-full h-full object-cover rounded-lg"
                                    />
                                ) : (
                                    <img
                                        src={item.thumbnail || "/placeholder.svg"}
                                        alt={item.alt}
                                        className="w-full h-full object-cover transition-transform group-hover:scale-105 rounded-lg"
                                    />
                                )}


                                {/* Selection Checkbox */}
                                <div className="absolute bottom-2 right-2">
                                    <div
                                        className={`w-6 h-6 rounded border-2 flex items-center justify-center transition-colors ${selectedMedia.includes(item.id)
                                            ? "bg-cyan-500 border-primary"
                                            : "bg-white/80 border-white/80 hover:bg-white hover:border-white"
                                            }`}
                                    >
                                        {selectedMedia.includes(item.id) && <Check className="w-4 h-4 text-white" />}
                                    </div>
                                </div>

                                {/* Video indicator */}
                                {item.type === "video" && (
                                    <div className="absolute top-2 left-2 bg-black/60 text-white text-xs px-2 py-1 rounded">Video</div>
                                )}

                                {/* Platform indicator */}
                                <div className="absolute top-2 right-2 bg-black/60 text-white text-xs px-2 py-1 rounded capitalize">
                                    {item.platform}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Apply Button */}
                <div className="p-4 bg-white dark:bg-zinc-900 border-t border-gray-200 dark:border-zinc-800 flex-shrink-0">
                    <Button
                        variant="default"
                        onClick={handleApply}
                        disabled={selectedMedia.length === 0}
                        className="w-full py-3 disabled:bg-gray-300 disabled:cursor-not-allowed"
                    >
                        {t("Apply")} {selectedMedia.length > 0 && `(${selectedMedia.length})`}
                    </Button>
                </div>
            </div>
        </>
    )
}
