import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Spinner } from '@/components/ui/spinner';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import useMediaStore from '@/stores/MediaStore';
import { Edit3 } from 'lucide-react';
import { useEffect, useState } from 'react';

interface EditSidebarProps {
    isOpen: boolean;
    onClose: () => void;
}

export default function EditSidebar({ isOpen, onClose }: EditSidebarProps) {
    const {
        memes,
        backgrounds,
        isFetchingMemes,
        isFetchingBackgrounds,
        selectedMeme,
        selectedBackground,
        fetchMemes,
        fetchBackgrounds,
        selectMeme,
        selectBackground,
        clearSelectedMeme,
        clearSelectedBackground,
    } = useMediaStore();

    // Track the current active tab
    const [activeTab, setActiveTab] = useState('backgrounds');

    // Fetch data when sidebar opens for the current active tab
    useEffect(() => {
        if (isOpen) {
            if (activeTab === 'memes' && memes.length === 0 && !isFetchingMemes) {
                fetchMemes();
            } else if (activeTab === 'backgrounds' && backgrounds.length === 0 && !isFetchingBackgrounds) {
                fetchBackgrounds();
            }
        }
    }, [isOpen, activeTab, memes.length, backgrounds.length, isFetchingMemes, isFetchingBackgrounds]);

    const handleTabChange = (value: string) => {
        setActiveTab(value);
        if (value === 'memes' && memes.length === 0 && !isFetchingMemes) {
            fetchMemes();
        } else if (value === 'backgrounds' && backgrounds.length === 0 && !isFetchingBackgrounds) {
            fetchBackgrounds();
        }
    };

    const handleMemeSelect = (meme) => {
        selectMeme(meme);
    };

    const handleBackgroundSelect = (background) => {
        selectBackground(background);
    };

    return (
        <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <SheetContent side="right" className="w-80 overflow-y-auto px-2">
                <SheetHeader>
                    <SheetTitle className="flex items-center gap-3">
                        <Edit3 className="h-6 w-6" />
                        Edit Media
                    </SheetTitle>
                </SheetHeader>

                {/* Currently Selected Items */}
                <div className="pb-6">
                    <div className="flex justify-center gap-3">
                        {/* Selected Background */}
                        <div className="text-center">
                            {selectedBackground ? (
                                <div className="aspect-[9/16] h-[200px] overflow-hidden rounded-lg bg-gray-100">
                                    <img src={selectedBackground.media_url} alt="Selected Background" className="h-full w-full object-cover" />
                                </div>
                            ) : (
                                <div className="flex aspect-[9/16] h-[200px] items-center justify-center rounded-lg border-2 border-dashed border-gray-300 p-2 text-center text-xs text-gray-500">
                                    No background
                                </div>
                            )}
                            <p className="mb-1 text-xs text-gray-600">Background</p>
                        </div>

                        {/* Selected Meme */}
                        <div className="text-center">
                            {selectedMeme ? (
                                <div className="aspect-[9/16] h-[200px] overflow-hidden rounded-lg bg-gray-100">
                                    <img src={selectedMeme.gif_url} alt="Selected Meme" className="h-full w-full object-cover" />
                                </div>
                            ) : (
                                <div className="flex aspect-[9/16] h-[200px] items-center justify-center rounded-lg border-2 border-dashed border-gray-300 p-2 text-center text-xs text-gray-500">
                                    No meme
                                </div>
                            )}
                            <p className="mb-1 text-xs text-gray-600">Meme Overlay</p>
                        </div>
                    </div>
                </div>

                <Tabs value={activeTab} className="w-full" onValueChange={handleTabChange}>
                    <TabsList className="grid w-full grid-cols-2">
                        <TabsTrigger value="memes">Meme</TabsTrigger>

                        <TabsTrigger value="backgrounds">Background</TabsTrigger>
                    </TabsList>

                    <TabsContent value="backgrounds" className="">
                        {isFetchingBackgrounds && <Spinner className="h-4 w-4"></Spinner>}
                        {!isFetchingBackgrounds && backgrounds.length === 0 && <div className="w-full text-center">No backgrounds available.</div>}
                        {!isFetchingBackgrounds && backgrounds.length > 0 && (
                            <div className="grid grid-cols-2 gap-2">
                                {backgrounds.map((item, index) => (
                                    <Button
                                        key={item.ids}
                                        variant="ghost"
                                        className={`aspect-[9/16] h-auto w-full overflow-hidden rounded-lg bg-gray-100 p-0 transition-all hover:bg-gray-100 hover:ring-2 hover:ring-blue-500 ${
                                            selectedBackground?.ids === item.ids ? 'ring-2 ring-blue-500' : ''
                                        }`}
                                        onClick={() => handleBackgroundSelect(item)}
                                    >
                                        <img src={item.media_url} alt="Background" width={150} height={150} className="h-full w-full object-cover" />
                                    </Button>
                                ))}
                            </div>
                        )}
                    </TabsContent>

                    <TabsContent value="memes" className="">
                        {isFetchingMemes && <Spinner className="h-4 w-4"></Spinner>}
                        {!isFetchingMemes && memes.length === 0 && <div className="w-full text-center">No memes available.</div>}
                        {!isFetchingMemes && memes.length > 0 && (
                            <div className="grid grid-cols-2 gap-2 p-2">
                                {memes.map((item, index) => (
                                    <Button
                                        key={item.ids}
                                        variant="ghost"
                                        className={`aspect-[9/16] h-auto w-full overflow-hidden rounded-lg bg-gray-100 p-0 transition-all hover:bg-gray-100 hover:ring-2 hover:ring-blue-500 ${
                                            selectedMeme?.ids === item.ids ? 'ring-2 ring-blue-500' : ''
                                        }`}
                                        onClick={() => handleMemeSelect(item)}
                                    >
                                        <img src={item.gif_url} alt="Meme" width={150} height={150} className="h-full w-full object-cover" />
                                    </Button>
                                ))}
                            </div>
                        )}
                    </TabsContent>
                </Tabs>
            </SheetContent>
        </Sheet>
    );
}
