import { Button } from '@/components/ui/button';
import { GridSkeleton } from '@/components/ui/grid-skeleton';
import { Input } from '@/components/ui/input';
import { MediaItem } from '@/components/ui/media-item';
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="text-muted-foreground 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">
                                    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="text-muted-foreground 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">
                                    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="text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2" />
                            <Input
                                placeholder={`Search ${activeTab === 'memes' ? 'memes' : 'backgrounds'}...`}
                                value={searchQueries[activeTab]}
                                onChange={(e) => handleSearchChange(e.target.value)}
                                onKeyDown={handleSearchKeyDown}
                                className="pr-10 pl-10"
                            />
                            {searchQueries[activeTab] && (
                                <button
                                    onClick={handleClearSearch}
                                    className="text-muted-foreground hover:text-foreground absolute top-1/2 right-3 -translate-y-1/2"
                                >
                                    <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="text-muted-foreground w-full p-8 text-center">
                                <p className="mb-4 text-sm">No backgrounds found.</p>
                                <div className="flex flex-col gap-3">
                                    {searchQueries.backgrounds && (
                                        <Button variant="secondary" onClick={handleClearSearch} className="rounded-full text-sm">
                                            Clear Search
                                        </Button>
                                    )}
                                    {import.meta.env.VITE_DISCORD_LINK && (
                                        <Button variant="" asChild className="rounded-full text-sm">
                                            <a href={import.meta.env.VITE_DISCORD_LINK} target="_blank" rel="noopener noreferrer">
                                                Request in Discord
                                            </a>
                                        </Button>
                                    )}
                                </div>
                            </div>
                        )}
                        {!isFetchingBackgrounds && backgrounds.length > 0 && (
                            <>
                                <div className="grid grid-cols-2 gap-2 p-2">
                                    {backgrounds.map((item, index) => (
                                        <MediaItem
                                            key={item.ids}
                                            src={item.media_url}
                                            alt="Background"
                                            onClick={() => handleBackgroundSelect(item)}
                                            isSelected={selectedBackground?.ids === item.ids}
                                            className="transition-all hover:ring-2 hover:ring-blue-500"
                                        />
                                    ))}
                                </div>
                            </>
                        )}
                    </TabsContent>

                    <TabsContent value="memes" className="">
                        {isFetchingMemes && <GridSkeleton itemCount={6} />}
                        {!isFetchingMemes && memes.length === 0 && (
                            <div className="text-muted-foreground w-full p-8 text-center">
                                <p className="mb-4 text-sm">No memes found.</p>
                                <div className="flex flex-col gap-2">
                                    {searchQueries.memes && (
                                        <Button variant="outline" onClick={handleClearSearch} className="text-sm">
                                            Clear Search
                                        </Button>
                                    )}
                                    {import.meta.env.VITE_DISCORD_LINK && (
                                        <Button variant="secondary" asChild className="text-sm">
                                            <a href={import.meta.env.VITE_DISCORD_LINK} target="_blank" rel="noopener noreferrer">
                                                Request in Discord
                                            </a>
                                        </Button>
                                    )}
                                </div>
                            </div>
                        )}
                        {!isFetchingMemes && memes.length > 0 && (
                            <>
                                <div className="grid grid-cols-2 gap-2 p-2">
                                    {memes.map((item, index) => (
                                        <MediaItem
                                            key={item.ids}
                                            src={item.gif_url}
                                            alt="Meme"
                                            onClick={() => handleMemeSelect(item)}
                                            isSelected={selectedMeme?.ids === item.ids}
                                            className="transition-all hover:ring-2 hover:ring-blue-500"
                                        />
                                    ))}
                                </div>
                            </>
                        )}
                    </TabsContent>
                </Tabs>
            </SheetContent>
        </Sheet>
    );
}
