import { Button } from '@/components/ui/button';
import { GridSkeleton } from '@/components/ui/grid-skeleton';
import { Input } from '@/components/ui/input';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
import useMediaStore from '@/stores/MediaStore';
import { Edit3, Search, X } from 'lucide-react';
import { useEffect, useState } from 'react';

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

    // Track the current active tab
    const [activeTab, setActiveTab] = useState('memes');
    
    // Track search queries
    const [searchQueries, setSearchQueries] = useState({
        memes: '',
        backgrounds: ''
    });
    
    // Track if data has been loaded for each tab (to prevent infinite loading on empty results)
    const [dataLoaded, setDataLoaded] = useState({
        memes: false,
        backgrounds: false
    });

    // Fetch data when sidebar opens for the current active tab
    useEffect(() => {
        if (isOpen) {
            if (activeTab === 'memes' && !dataLoaded.memes && !isFetchingMemes) {
                const query = searchQueries.memes;
                if (query) {
                    searchMemes(query).finally(() => {
                        setDataLoaded(prev => ({ ...prev, memes: true }));
                    });
                } else {
                    fetchMemes().finally(() => {
                        setDataLoaded(prev => ({ ...prev, memes: true }));
                    });
                }
            } else if (activeTab === 'backgrounds' && !dataLoaded.backgrounds && !isFetchingBackgrounds) {
                const query = searchQueries.backgrounds;
                if (query) {
                    searchBackgrounds(query).finally(() => {
                        setDataLoaded(prev => ({ ...prev, backgrounds: true }));
                    });
                } else {
                    fetchBackgrounds().finally(() => {
                        setDataLoaded(prev => ({ ...prev, backgrounds: true }));
                    });
                }
            }
        }
    }, [isOpen, activeTab, dataLoaded.memes, dataLoaded.backgrounds, isFetchingMemes, isFetchingBackgrounds]);

    const handleTabChange = (value) => {
        setActiveTab(value);
        if (value === 'memes' && !dataLoaded.memes && !isFetchingMemes) {
            const query = searchQueries.memes;
            if (query) {
                searchMemes(query).finally(() => {
                    setDataLoaded(prev => ({ ...prev, memes: true }));
                });
            } else {
                fetchMemes().finally(() => {
                    setDataLoaded(prev => ({ ...prev, memes: true }));
                });
            }
        } else if (value === 'backgrounds' && !dataLoaded.backgrounds && !isFetchingBackgrounds) {
            const query = searchQueries.backgrounds;
            if (query) {
                searchBackgrounds(query).finally(() => {
                    setDataLoaded(prev => ({ ...prev, backgrounds: true }));
                });
            } else {
                fetchBackgrounds().finally(() => {
                    setDataLoaded(prev => ({ ...prev, backgrounds: true }));
                });
            }
        }
    };

    // Handle search input changes
    const handleSearchChange = (value) => {
        setSearchQueries(prev => ({
            ...prev,
            [activeTab]: value
        }));
    };

    // Handle search submission
    const handleSearch = () => {
        const query = searchQueries[activeTab];
        if (activeTab === 'memes') {
            searchMemes(query).finally(() => {
                setDataLoaded(prev => ({ ...prev, memes: true }));
            });
        } else if (activeTab === 'backgrounds') {
            searchBackgrounds(query).finally(() => {
                setDataLoaded(prev => ({ ...prev, backgrounds: true }));
            });
        }
    };

    // Handle clearing search
    const handleClearSearch = () => {
        setSearchQueries(prev => ({
            ...prev,
            [activeTab]: ''
        }));
        
        // Reset data loaded state and fetch fresh data without search
        if (activeTab === 'memes') {
            fetchMemes().finally(() => {
                setDataLoaded(prev => ({ ...prev, memes: true }));
            });
        } else if (activeTab === 'backgrounds') {
            fetchBackgrounds().finally(() => {
                setDataLoaded(prev => ({ ...prev, backgrounds: true }));
            });
        }
    };

    // Handle Enter key in search input
    const handleSearchKeyDown = (e) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    };

    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-0">
                    <div className="flex justify-center gap-3">
                        {/* Selected Meme */}
                        <div className="text-center" onClick={() => setActiveTab('memes')}>
                            {selectedMeme ? (
                                <div
                                    className={cn(
                                        'aspect-[9/16] h-[200px] overflow-hidden rounded-lg bg-gray-100',
                                        activeTab === 'memes' ? 'ring-2 ring-blue-500' : '',
                                    )}
                                >
                                    <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>

                        {/* Selected Background */}
                        <div className="text-center" onClick={() => setActiveTab('backgrounds')}>
                            {selectedBackground ? (
                                <div
                                    className={cn(
                                        'aspect-[9/16] h-[200px] overflow-hidden rounded-lg bg-gray-100',
                                        activeTab === 'backgrounds' ? 'ring-2 ring-blue-500' : '',
                                    )}
                                >
                                    <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>
                    </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>

                    {/* Search Bar */}
                    <div className="relative flex items-center gap-2 px-2 pt-3">
                        <div className="relative flex-1">
                            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                            <Input
                                placeholder={`Search ${activeTab === 'memes' ? 'memes' : 'backgrounds'}...`}
                                value={searchQueries[activeTab]}
                                onChange={(e) => handleSearchChange(e.target.value)}
                                onKeyDown={handleSearchKeyDown}
                                className="pl-10 pr-10"
                            />
                            {searchQueries[activeTab] && (
                                <button
                                    onClick={handleClearSearch}
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                >
                                    <X className="h-4 w-4" />
                                </button>
                            )}
                        </div>
                        <Button
                            onClick={handleSearch}
                            variant="outline"
                            size="sm"
                            className="px-3"
                        >
                            <Search className="h-4 w-4" />
                        </Button>
                    </div>

                    <TabsContent value="backgrounds" className="">
                        {isFetchingBackgrounds && <GridSkeleton itemCount={6} />}
                        {!isFetchingBackgrounds && backgrounds.length === 0 && <div className="w-full text-center p-8 text-gray-500">No backgrounds found.</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 && <GridSkeleton itemCount={6} />}
                        {!isFetchingMemes && memes.length === 0 && <div className="w-full text-center p-8 text-gray-500">No memes found.</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>
    );
}
