import { DownloadOutlined, FileOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { IErrorResponse } from 'lemans-api/libs/Api/api.types';
import { ICategorySpecialistNotesData } from 'lemans-api/models/CategorySpecialist/categorySpecialist.types';
import { flash } from 'lemans-common';
import { service } from 'lemans-dashboard-common';
import { isEU, isUS } from 'lemans-dashboard-common/Config/Config.env';
import { ExpandableImage } from '../ExpandableImage';

export const uploadFileToMedia = (tempFile:any, setMediaId:any) => {
    service.media.classification.findId("ds", "CategorySpecialistNotes").then((mediaClassificationId:number | null) => 
        service.media.create("ds", {
            extension: tempFile.extension ? tempFile.extension: '',
            mediaClassificationId,
            originalFileName: tempFile.originalFileName ? tempFile.originalFileName: '',
            source: isUS ? 0 : isEU ? 2 : 0,
            tempId: tempFile.tempId ? tempFile.tempId : '',
        }).then((res: any) => {
            setMediaId(res.mediaId)
        })
        .catch((results:IErrorResponse) => {
            flash.error(results.response.body.messages[0].text || "", 9);
        })
    );
}
const imageSize = 50;
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

export const imgRender = (mediaUrl:any, notes: ICategorySpecialistNotesData, index:number) => {
    const ext = notes.extension?.toLowerCase();
    if (IMAGE_EXTENSIONS.includes(ext)) {
        return (
            <div className={'part-details-column-wrapper'}>
                <div style={{float: "left", width: `${imageSize}px`, height: `${imageSize}px`, marginRight: "8px"}}>
                    <ExpandableImage
                        id={`${mediaUrl}-${index}`}
                        mediaUrl={mediaUrl+'.'+notes.extension}
                        thumbnailSize={imageSize}
                        imageSize={500}
                    />
                </div>
                {notes.mediaId ? <Button type="primary" shape="circle" onClick={onDownload(notes.mediaId)}><DownloadOutlined /></Button> : ''}
            </div>
        );
    } else {
        // Render an icon or a download link for non-image files
        return (
            <div className={'part-details-column-wrapper'}>
                <div style={{ float: "left", width: `${imageSize}px`, height: `${imageSize}px`, marginRight: "8px", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <FileOutlined style={{ fontSize: imageSize }} />
                </div>
                {notes.mediaId ? <Button type="primary" shape="circle" onClick={onDownload(notes.mediaId)}><DownloadOutlined /></Button> : ''}
            </div>
        );
    }
};
    
export const dateRender = (date:string) => new Date(date).toLocaleDateString();

export const onDownload = (mediaId:any) => () => {
    service.media.download('ds', mediaId);
}