"use client"

import React from 'react'
import { deleteGallery, galleryVilla, syncGallery, updateGallery } from '@/actions/ttd';
import { Button } from '@/components/ui/button';
import { CheckCheckIcon, PlusIcon, RefreshCwIcon, SaveIcon } from 'lucide-react';
import { toast } from 'sonner';
import { ReactSortable } from "react-sortablejs";
import { cn } from '@/lib/utils';
import Image from 'next/image';
import { Checkbox } from '@/components/ui/checkbox';
import AddGallery from './add-gallery';
import DeleteGallery from './delete-gallery';
import { useLoading } from '@/lib/useLoading';

interface Props {
    data: any;
}
const GallerySection = ({ data }: Props) => {

    const [gallery, setGallery] = React.useState<any[]>([]);
    const [galleryArray, setGalleryArray] = React.useState<string[]>([]);
    const [selectAll, setSelectAll] = React.useState(false);
    const { setLoading } = useLoading()
    const [open, setOpen] = React.useState(false)

    const toggleOpen = () => setOpen(!open)

    const fetchData = async () => {
        setLoading(true)
        const response = await galleryVilla(data._id)
        if(response.success){
            setGallery(response.data)
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }

    React.useEffect(() => {
        fetchData()
    }, [data])

    const fetchingGallery = async () => {
        setLoading(true)
        const response = await syncGallery(data._id)
        if(response.success){
            setGallery(response.data)
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }
    
    const handleSelectAll = () => {
        const newSelectAll = !selectAll;
    
        setSelectAll(newSelectAll);
        setGalleryArray(newSelectAll ? gallery.map(({ _id }) => _id) : []);
    };
    
    
    const saveReorder = async () => {
        setLoading(true)
        const newGallery = gallery.map((item: any, index) => ({
            image: item.image,
            order: index + 1
        }))
        const bodyData = {
            gallery: newGallery
        }
        const response = await updateGallery(data._id, bodyData);
        if(response.success){
            toast.success(response.message)
            fetchData();
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }

    const handleCheckbox = (id: string, checked: boolean) => {
        setGalleryArray((prev) => 
            checked ? [...prev, id] : prev.filter((item) => item !== id)
        );
    };


    const handleDelete = async () => {
        setLoading(true)
        const body = {
            id: data._id,
            data: galleryArray
        }
        const response = await deleteGallery(body);
        if(response.success){
            setGalleryArray([]);
            setLoading(false)
            toast.success(response.message)
            fetchData()
        }else{
            setLoading(false)
            toast.error(response.message)
        }
    }

    return (
        <div className='md:px-6 space-y-6 border rounded-lg py-6'>
            <div className='flex items-center justify-between'>
                <Button 
                    size="sm" 
                    type="button" 
                    variant="outline" 
                    onClick={handleSelectAll}
                >
                    <CheckCheckIcon />
                    <span>Select all</span>
                </Button>
                <div className='flex items-center justify-end gap-6'>
                    {galleryArray.length > 0 && (
                        <DeleteGallery 
                            onDelete={() => handleDelete()}
                            title={`Delete (${galleryArray.length}) Gallery`}
                        />
                    )}
                    <Button type="button" size="sm" onClick={toggleOpen}>
                        <PlusIcon />
                        <span>Add</span>
                    </Button>
                    <Button type="button" size="sm" variant="green" onClick={fetchData}>
                        <RefreshCwIcon />
                        <span>Refresh</span>
                    </Button>
                    <Button type="button" size="sm" variant="semi" onClick={fetchingGallery}>
                        <RefreshCwIcon />
                        <span>Sync Gallery with old System</span>
                    </Button>
                    <Button type="button" size="sm" variant="blue" onClick={saveReorder} disabled={open}>
                        <SaveIcon />
                        <span>Save</span>
                    </Button>
                </div>
            </div>
            <AddGallery
                open={open}
                setOpen={setOpen}
                id={data._id} 
                name={data.name} 
                refetch={fetchData}
                setLoading={setLoading}
            />
            <div className='border rounded-lg bg-muted p-6 space-y-3'>
                <ReactSortable 
                    list={gallery} 
                    setList={setGallery}
                    animation={150}
                    className="grid lg:grid-cols-7 grid-cols-3 gap-4 select-none " // Grid layout
                    chosenClass="choosen"
                >   
                    {gallery.length > 0 ? 
                        gallery.map((item, index) => (
                            <div key={item._id || index} className={cn("relative p-1 rounded-lg", galleryArray.includes(item._id) ? "bg-gundam-red" : "")}>
                                <div className='absolute top-1 left-1 z-30 w-[96%] h-1/2 bg-gradient-to-b from-neutral-900 to-transparent rounded-t-lg' />
                                <Image
                                    className="pointer-events-none object-cover w-56 h-40 rounded-lg"
                                    alt={`gallery-image-${item._id}`}
                                    src={`https://imagedelivery.net/wO6ihUlg1M7aee1mES2PLg/${item.image}/public`}
                                    width={500}
                                    height={500}
                                />
                                <div className='absolute top-4 left-4 z-40 bg-gundam-semi-black h-6 w-6 rounded-sm flex items-center justify-center'>
                                    <legend className='text-center text-sm font-bold text-white'>{item.order}</legend>
                                </div>
                                <div className='absolute top-4 right-4 z-40'>
                                    <Checkbox 
                                        className="bg-white border-none h-6 w-6 data-[state=checked]:bg-gundam-red" 
                                        checked={galleryArray.includes(item._id)}
                                        onCheckedChange={(checked) => handleCheckbox(item._id, Boolean(checked))} 
                                    />
                                </div>
                            </div>
                        )) : (
                            <div className='col-span-full'>
                                <p className='text-center font-bold'>No Galleries Found</p>
                            </div>
                        )
                    }
                </ReactSortable>
            </div>
        </div>
    )
}

export default GallerySection