import { Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useFormikContext } from 'formik';
import { ImageBaseURL } from '../../../../../api/config';

const MaltyFile = ({ tabKey }: any) => {
    const { t } = useTranslation();
    const formik = useFormikContext<any>();
    const name = `variable[${tabKey}].${"images"}`;

    // Construct imageUrl and fileList for each file
    const files = formik.values?.variable[tabKey]?.images || [];

    const fileItems = files.map((file: any, index: number) => {
        
        const FormikimageUrl = file ? ImageBaseURL + file :  '';      
        const imageUrl = typeof file === "string" ? (FormikimageUrl)?.replace("public", "/storage") : (file instanceof File) ? URL.createObjectURL(file) : "";
        // console.log(imageUrl?.replace("public", "/storage"),"imageUrl");
        
        return {
            uid: `-${index}`,
            name: file?.name || '',
            status: 'done',
            url: file,
            thumbUrl: imageUrl?.replace("public", "/storage")
        };
    });

    const FilehandleChange = ({ fileList }: { fileList: any }) => {
        console.log(fileList);
        
        formik.setFieldValue(
            name,
            fileList.map((file: any) => (file?.originFileObj ? file.originFileObj : file.url))
          );    };

    const customRequest = async ({ onSuccess }: any) => {
        onSuccess();
    };

    return (
        <div className="ValidationField">
            <label className="text">
                {t(`images`)}
            </label>
            <Upload
                listType="picture"
                defaultFileList={fileItems}
                onChange={FilehandleChange}
                customRequest={customRequest}
                className="w-100"
                maxCount={10}
            >
                <Button className="w-100" icon={<UploadOutlined />}>
                    {t("upload_image")}
                </Button>
            </Upload>
        </div>
    );
}

export default MaltyFile