import { useState } from 'react';
import { Upload, Modal } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { NotifOk, NotifAlert } from '../../../../components/Global/ToastNotif';
import { uploadFile, getFolderFromFileType } from '../../../../api/file-uploads';

const FileUploadHandler = ({
    solutionFields,
    fileList,
    onFileUpload,
    onFileRemove
}) => {
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');

    const getBase64 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });

    const handleUploadPreview = async (file) => {
        const preview = await getBase64(file);
        setPreviewImage(preview);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
        setPreviewOpen(true);
    };

    const handleFileUpload = async (file) => {
        const isAllowedType = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif'].includes(file.type);
        if (!isAllowedType) {
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: `${file.name} bukan file PDF atau gambar yang diizinkan.`
            });
            return Upload.LIST_IGNORE;
        }

        try {
            const fileExtension = file.name.split('.').pop().toLowerCase();
            const isImage = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(fileExtension);
            const fileType = isImage ? 'image' : 'pdf';
            const folder = getFolderFromFileType(fileType);

            const uploadResponse = await uploadFile(file, folder);
            const actualPath = uploadResponse.data?.path_solution || '';

            if (actualPath) {
                file.uploadPath = actualPath;
                file.solution_name = file.name;
                file.solutionId = solutionFields[0];
                file.type_solution = fileType;
                onFileUpload(file);
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `${file.name} berhasil diupload!`
                });
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: `Gagal mengupload ${file.name}`
                });
            }
        } catch (error) {
            console.error('Error uploading file:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: `Gagal mengupload ${file.name}. Silakan coba lagi.`
            });
        }

        return false;
    };

    const uploadProps = {
        multiple: true,
        accept: '.pdf,.jpg,.jpeg,.png,.gif',
        onRemove: onFileRemove,
        beforeUpload: handleFileUpload,
        fileList,
        onPreview: handleUploadPreview,
    };

    return (
        <>
            <Upload.Dragger {...uploadProps}>
                <p className="ant-upload-drag-icon">
                    <UploadOutlined />
                </p>
                <p className="ant-upload-text">Click or drag file to this area to upload</p>
                <p className="ant-upload-hint">Support for PDF and image files only</p>
            </Upload.Dragger>

            <Modal
                open={previewOpen}
                title={previewTitle}
                footer={null}
                onCancel={() => setPreviewOpen(false)}
                width="80%"
                style={{ top: 20 }}
            >
                {previewImage && (
                    <img
                        alt={previewTitle}
                        style={{ width: '100%' }}
                        src={previewImage}
                    />
                )}
            </Modal>
        </>
    );
};

export default FileUploadHandler;