'use client';

import Dropzone from 'react-dropzone';
import UploadIcon from '@icons/upload.svg';
import { Button } from '@/components/ui';
import { useEffect, useState } from 'react';

export function FileDropzone() {
    const [file, setFile] = useState<File | null>(null);
    const [preview, setPreview] = useState<string | null>(null);

    useEffect(() => {
        return () => {
            if (preview) URL.revokeObjectURL(preview);
        };
    }, [preview]);

    return (
        <Dropzone
            multiple={false}
            accept={{ 'image/*': [] }}
            onDrop={(acceptedFiles) => {
                const f = acceptedFiles[0];
                if (!f) return;

                const url = URL.createObjectURL(f);

                setFile(f);
                setPreview(url);
            }}
        >
            {({ getRootProps, getInputProps }) => (
                <div
                    {...getRootProps({
                        className:
                            'w-[900px] h-[508px] flex flex-col gap-[20px]',
                    })}
                >
                    <input {...getInputProps()} />

                    <div
                        className={`
        w-full
        flex-1
        relative
        overflow-hidden
        rounded-[10px]
        border border-violet
        ${preview ? 'bg-violet/30' : 'bg-background'}
    `}
                    >
                        {!preview ? (
                            <div className="w-full h-full flex flex-col justify-center items-center gap-[60px] p-[30px]">
                                <UploadIcon />
                                <span className="text-center">
                                    Выбери файлы на компьютере или перетащи
                                    сюда. JPG, PNG до 20MB.
                                </span>
                            </div>
                        ) : (
                            <img
                                src={preview}
                                alt="preview"
                                className="w-full h-full object-contain"
                            />
                        )}
                    </div>
                    <Button size="lg">
                        {preview ? 'Заменить' : 'Выбрать'}
                    </Button>
                </div>
            )}
        </Dropzone>
    );
}
