import React from "react";
import BreadcrumbComBS from "../breadcrumb/BreadcrumbComBS";
import {useState, useRef} from "react";
import {useQuery, useMutation, useQueryClient} from "@tanstack/react-query";
import queryKeys from "../../services/queryKeys";
import {getMediaFileList, uploadFile} from "../../services/services";
import getImage from "../../utils/getImage";


export default function MyMedia() {

    const queryClient = useQueryClient()

    const basePath = process.env.REACT_APP_MAIN_API
    const [selectedFile, setSelectedFile] = useState(null);
    const [message, setMessage] = useState('');
    const [imageLink, setImageLink] = useState('')
console.log('imageLink', imageLink)
    // Function to handle file selection
    const handleFileChange = (event) => {
        setSelectedFile(event.target.files[0]);
        setMessage('');
    };

    // Function to handle the upload to the API
    const _handleUpload = async () => {
        if (!selectedFile) {
            setMessage('Please select a file first!');
            return;
        }

        const formData = new FormData();
        // 'file' is the field name that your API endpoint expects
        formData.append('file', selectedFile);
        formData.append("member_uid", localStorage.getItem('uid'));
        formData.append("token", localStorage.getItem('token'));

        try {
            // Replace with your actual API endpoint URL
            const apiEndpoint = basePath + '/upload/webfiles';
            const response = await fetch(apiEndpoint, {
                method: 'POST',
                // The browser automatically sets the 'Content-Type' header to
                // 'multipart/form-data' when you provide a FormData object as the body,
                // which is required for file uploads.
                body: formData,
            });

            if (response.ok) {
                const result = await response.json();
                setMessage('File uploaded successfully!');
                console.log('Success:', result);
            } else {
                setMessage('Upload failed.');
                console.error('Upload failed:', response.statusText);
            }
        } catch (error) {
            setMessage('An error occurred during the upload.');
            console.error('Error:', error);
        }
    }

    const uploadFileMutation = useMutation({
        mutationFn: (fields) => {
            if(!fields.file){
                throw({message: 'Please select a file first!'})
            }
            return uploadFile(fields)
        },
        onSuccess: (res) => {
            // console.log('res', res.data)
            // if(res.data.resultCode != '0' || !res?.data?.pending_uid){
            //     throw({message: res?.data?.resultDescription})
            // }
            setSelectedFile(null)
            queryClient.refetchQueries({
                queryKey: [...queryKeys.my_files],
                // type: 'active',
                // exact: true,
            })
        },
        onSettled: () => {
            setTimeout(()=>{
                uploadFileMutation.reset()
            }, 3000)
        }
    })

    const handleUpload = () => {
        let reqData = {
            token: localStorage.getItem("token"), // USER TOKEN
            member_uid: localStorage.getItem("uid"), // USER UID
            file: selectedFile
        };
        // console.log(reqData)
        uploadFileMutation.mutate(reqData)
    }

    const {data, isFetching, isError, error} = useQuery({
        queryKey: queryKeys.my_files,
        queryFn: () => {
            let reqData = {
                token: localStorage.getItem('token'), // USER TOKEN
                uid: localStorage.getItem('uid') // USER UID
            }
            return getMediaFileList(reqData)
        }
    })

    const mediaFileList = data?.data

    //debugger;

    return (
        <>
            <BreadcrumbComBS title='Files' paths={['Dashboard', 'Files']}/>

            <div className="row">
                <div className="col-xl-6 col-xxl-4 m-b-30">
                    <div className="card card-statistics h-50 mb-0 widget-support-list">
                        <div className="card-header">
                            <div className="card-heading">
                                <h4 className="card-title">Upload File</h4>
                            </div>
                        </div>
                        <div className="card-body pl-0 pr-0 scrollbar scroll_dark">
                            <div className="widget-text">

                                <div>
                                    <input className="form-control form-control-sm" type="file"
                                           onChange={handleFileChange}/>

                                    {selectedFile && (
                                        <div>
                                            <h4>Selected File Details:</h4>
                                            <ul>
                                                <li>Name: {selectedFile.name}</li>
                                                <li>Type: {selectedFile.type}</li>
                                                <li>Size: {selectedFile.size} bytes</li>
                                            </ul>
                                            <div style={{width: '100%', textAlign: 'right'}}>
                                                <button
                                                    className="btn btn-square btn-inverse-light btn-xs d-inline-block mt-2 mb-0"
                                                    onClick={handleUpload} disabled={!selectedFile || uploadFileMutation.isPending || uploadFileMutation.isSuccess}>
                                                    Upload
                                                </button>
                                            </div>

                                            <>
                                                {/* {message && <p>{message}</p>} */}
                                                <p>{uploadFileMutation.isPending ? 'uploading...' : uploadFileMutation.isError ? uploadFileMutation?.error?.message : uploadFileMutation.isSuccess ? 'File Uploaded' : ''}</p>
                                            </>
                                        </div>

                                    )}
                                </div>

                            </div>

                        </div>
                    </div>
                </div>
                <div className="col-xl-6 col-xxl-4 m-b-30">
                    <div className="card card-statistics h-100 mb-0 widget-downloads-list" style={{}}>
                        <div className="card-header d-flex justify-content-between">
                            <div className="card-heading">
                                <div className="card-heading">
                                    <h4 className="card-title">Files List</h4>
                                </div>
                            </div>
                        </div>
                        {isFetching ? 
                            <>
                                <div className="col-12">
                                    <p className='text-mute'>Loading...</p>
                                </div>
                            </>
                            : isError ?
                            <div className="col-12">
                                <p className='text-danger'>{error?.message}</p>
                            </div>
                            :
                            <div className="card-body scrollbar scroll_dark" style={{minHeight: '400px', maxHeight: '500px', overflowY: 'auto'}}>
                                {mediaFileList && mediaFileList?.file_list && mediaFileList?.file_list.map((item, index) => {
                                    const file_url = (mediaFileList?.media_server + "/" + item?.file_group + "/" + item?.file_uid + "/" + item.filename).toLowerCase();
                                    const avtarImage =
                                        item?.file_type === undefined
                                            ? "icons/01.png"
                                            : "icons/" + item.file_type + ".png";
                                    return (<div key={index} className="widget-text">
                                        <div className="media align-items-center" onClick={()=>setImageLink(file_url)} style={{cursor: 'pointer'}}>
                                            <img src={getImage(avtarImage)}
                                                // src={`assets/img/file-icon/${item.file_type}.png`}
                                                className="img-fluid"
                                                alt={`${item.file_type}`}/>
                                            <div className="media-body">
                                                <h4 className="mb-0 ml-3">{item.filename}</h4>
                                            </div>
                                          
                                            <div>
                                                <a href={`${file_url}`} target='_blank'
                                                className="btn btn-icon btn-round btn-outline-success">
                                                    <i className="ti ti-download"></i>
                                                </a>
                                                <a href="" className="btn btn-icon btn-round btn-outline-danger ml-2">
                                                    <i className="ti ti-close"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>)
                                })
                                }
                            </div>
                        }
                    </div>
                </div>
                <div className="col-xl-6 col-xxl-4 m-b-30">
                    <div className="card card-statistics h-100 mb-0 widget-branches-list">
                        <div className="card-header">
                            <div className="card-heading">
                                <h4 className="card-title">Preview</h4>
                            </div>
                        </div>
                        <div className="card-body d-flex justify-content-center align-items-center pl-0 pr-0 scrollbar scroll_dark">
                            {imageLink &&
                                <img src={imageLink} alt='file-image' />
                            }
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}