'use client'
import React from 'react';

import { FilePondFile, FilePondInitialFile } from 'filepond';
import { FilePond, registerPlugin } from 'react-filepond';
import 'filepond/dist/filepond.min.css';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css';
import '@/styles/filepond-style.css';

import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type';
import FilePondPluginFileEncode from 'filepond-plugin-file-encode';
import { SaveIcon, XIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { addGallery } from '@/actions/ttd';

registerPlugin(FilePondPluginImagePreview, FilePondPluginFileValidateType, FilePondPluginFileEncode);

interface Props {
    id: string;
    name: string;
    refetch: () => void;
    open: boolean;
    setOpen: (value: boolean) => void;
    setLoading: (value: boolean) => void;
}
const AddGallery = ({id, name, refetch, open, setOpen, setLoading}: Props) => {

    const [files, setFiles] = React.useState<(string | Blob | FilePondInitialFile)[]>([]);
    const pondRef = React.useRef<FilePond | null>(null);


    const handleUpdateFiles = (fileItems: FilePondFile[]) => {
        const mappedFiles = fileItems.map(fileItem => fileItem.file); // Extract the actual file
        setFiles(mappedFiles);
    };
    

    const onSubmit = async() => {
        setLoading(true)
        const formData = new FormData()

        formData.append('id', id);
        formData.append('name', name);
        pondRef.current?.getFiles().forEach((fileItem) => {
            formData.append('gallery', fileItem.file as Blob);
        });
        try {

            const response = await addGallery(formData)
            if(response.success){
                setLoading(false)
                toast.success(response.message)
                setFiles([])
                refetch()
                setOpen(false)
            }else{
                setLoading(false)
                toast.error(response.message)
            }
        } catch (error) {
            setLoading(false)
            toast.error('Error uploading files' + error)
        }
    };

    const handleClose = async () => {
        setFiles([]);
        setOpen(false)
    }
    if(!open) return null;

    return (
        <div className='border rounded-lg p-4'>
            <div className='ml-3'>
                <p className='font-medium text-lg'>Add Gallery</p>
            </div>
            <div className="p-2 overflow-y-auto max-h-[620px] pr-4">
                <FilePond
                    ref={pondRef}
                    files={files}
                    onupdatefiles={handleUpdateFiles}
                    allowReorder={true}
                    allowMultiple={true}
                    maxFiles={100}
                    acceptedFileTypes={['image/*']}
                    labelIdle='Drag & Drop your images or <span class="filepond--label-action">Browse</span>'
                />
            </div>
            <div className='flex items-center justify-center gap-3 mt-3'>
                <Button type='reset' variant="red" onClick={handleClose}>
                    <XIcon />
                    <span>Close Add Gallery</span>
                </Button>
                <Button type='button' variant="blue" onClick={onSubmit}>
                    <SaveIcon />
                    <span>Save New Gallery</span>
                </Button>
            </div>
        </div>
    )

}

export default AddGallery