import React, { useState } from 'react';
import { Table, Row, Col, Button, Form, Modal, InputGroup, Breadcrumb, Spinner } from 'react-bootstrap';
import { Link, useParams } from 'react-router-dom';
import useUpdateMaterials from '../hooks/useUpdateMaterials';
import ModalOperation from '../../../../components/ui/adminMessageModal/ModalOperation';

const UpdateMaterials = () => {
    const { materialId } = useParams();
    const { 
        loading, 
        error, 
        materialData, 
        formData, 
        levelName,
        sectionName, 
        topicName, 
        mediaPath, 
        audioPreview,
        imagePreview,
        audioPreviewTitle,
        imagePreviewTitle,
        handleFormChange, 
        handleFormChangeAudio,
        handleFormChangeImage,
        handleRemoveMedia,
        updateMaterials,
        showLoader,
        handleCloseLoader,
        loaderState,

    } = useUpdateMaterials(materialId);

    const [viewImg, setMediaImg] = useState(false);
    const [show, setShow] = useState(false);
    const [mediaLoading, setMediaLoad] = useState(true);

    const handleClose = () => {setShow(false);setMediaLoad(true);};
    const handleViewMedia = (p) => {
        setMediaImg(p);
        setShow(true);
    };

    const handleMediaLoaded = () => {
        setMediaLoad(false);
    };

    const triggerFileInput = (e) => {
        e.target.previousElementSibling.click();
    };

    return (
        <div className='admin-teachers'>
            <Row className='mb-45'>
                <Col className="d-flex align-items-center breadcrumb-con">
                    <Button as={Link} className='btn btn-blue btn-square-back' to='/admin/material'>
                        <i className="bi bi-arrow-90deg-left"></i>
                    </Button>
                    <Breadcrumb className='custom-breadcrumb'>
                        <Breadcrumb.Item href="#">Learning</Breadcrumb.Item>
                        <Breadcrumb.Item href="/admin/material" className='text-capitalize'>Materials</Breadcrumb.Item>
                        <Breadcrumb.Item active>Update Materials</Breadcrumb.Item>
                    </Breadcrumb>
                </Col>
            </Row>
            <Row className='mb-45'>
                <Col>
                    <div className="cards">
                        <div className="cards-title d-flex">
                            <h4>{sectionName} : {topicName} - <span className='text-blue'>{levelName}</span></h4>
                        </div>
                        <div className="cards-body">
                            {loading?(
                                <div className='w-100 d-flex justify-content-center align-items-center' style={{height:"20vh"}}>
                                    <Spinner animation="grow" variant="primary" />
                                    <Spinner animation="grow" variant="secondary" />
                                    <Spinner animation="grow" variant="success" />
                                    <Spinner animation="grow" variant="danger" />
                                    <Spinner animation="grow" variant="warning" />
                                    <Spinner animation="grow" variant="info" />
                                </div>
                            ):(
                                <Form onSubmit={(e) => { e.preventDefault(); updateMaterials(); }}>
                                    <Row className="mb-2">
                                        <Form.Group as={Col} controlId="formGridEmail">
                                            <Form.Label>Material Content<sup className='text-red fw-bold'>*</sup></Form.Label>
                                            <Form.Control as="textarea" rows={5} className='mb-2' placeholder='Type the meterial content here...'
                                                value={formData.content || ''}
                                                onChange={handleFormChange}
                                                name='content'
                                            />
                                        </Form.Group>
                                    </Row>
                                    <Row className='mb-4'>
                                        <Form.Group as={Col}>
                                            <Form.Label>
                                                Audio File (optional) 
                                                {materialData.AUDIO || audioPreview ?(
                                                    <span className='ms-2 text-blue cursor-pointer' onClick={(e) => { e.preventDefault(); handleViewMedia(false); }}>
                                                        view media
                                                    </span>

                                                ):(
                                                    <></>
                                                )}
                                            </Form.Label>
                                            <InputGroup className="input-group-icon">
                                                <InputGroup.Text id="basic-addon1" className='border-dashed'><i className="bi bi-music-note-beamed"></i></InputGroup.Text>
                                                <Form.Control type='file' accept="audio/*"
                                                    placeholder="Choose Audio"
                                                    aria-label="fullname"
                                                    aria-describedby="basic-addon1"
                                                    className='border-dashed d-none'
                                                    onChange={handleFormChangeAudio}
                                                    name='audio'
                                                />
                                                <Form.Control readOnly onClick={(e) => {e.preventDefault();triggerFileInput(e)}}
                                                    placeholder="Choose Audio"
                                                    aria-label="fullname"
                                                    aria-describedby="basic-addon1"
                                                    className='border-dashed cursor-pointer'
                                                    value={audioPreviewTitle ? audioPreviewTitle : formData.audio || ''}
                                                    onChange={(e)=>{e.preventDefault();}}
                                                />
                                                {audioPreview || formData.audio ?(
                                                    <Button variant="outline-danger" className='fs-14p' onClick={(e) => { e.preventDefault(); handleRemoveMedia('audio'); }}>
                                                        remove
                                                    </Button>
                                                ):(<></>)}
                                            </InputGroup>
                                            <small>Ensure the file size is no larger than 5 MB</small>
                                        </Form.Group>
                                        <Form.Group as={Col}>
                                            <Form.Label>
                                                Image File (optional) 
                                                {materialData.IMAGE || imagePreview ?(
                                                    <span className='ms-2 text-blue cursor-pointer' onClick={(e) => { e.preventDefault(); handleViewMedia(true); }}>
                                                        view media
                                                    </span>

                                                ):(
                                                    <></>
                                                )}
                                            </Form.Label>
                                            <InputGroup className="input-group-icon">
                                                <InputGroup.Text id="basic-addon1" className='border-dashed'><i className="bi bi-image"></i></InputGroup.Text>
                                                <Form.Control type='file' accept="image/*"
                                                    placeholder="Choose Image"
                                                    aria-label="fullname"
                                                    aria-describedby="basic-addon1"
                                                    className='border-dashed d-none'
                                                    onChange={handleFormChangeImage}
                                                    name='image'
                                                />
                                                <Form.Control readOnly onClick={(e) => {e.preventDefault();triggerFileInput(e)}}
                                                    placeholder="Choose Image"
                                                    aria-label="fullname"
                                                    aria-describedby="basic-addon1"
                                                    className='border-dashed cursor-pointer'
                                                    value={imagePreviewTitle ? imagePreviewTitle : formData.image || ''}
                                                    onChange={(e)=>{e.preventDefault();}}
                                                />
                                                {imagePreview || formData.image ?(
                                                    <Button variant="outline-danger" className='fs-14p' onClick={(e) => { e.preventDefault(); handleRemoveMedia('image'); }}>
                                                        remove
                                                    </Button>
                                                ):(<></>)}
                                            </InputGroup>
                                            <small>Ensure the file size is no larger than 5 MB</small>
                                        </Form.Group>
                                        <Form.Group as={Col}>
                                            <Form.Label>Video Link (optional)</Form.Label>
                                            <InputGroup className="input-group-icon">
                                                <InputGroup.Text id="basic-addon1" className='border-dashed'><i className="bi bi-film"></i></InputGroup.Text>
                                                <Form.Control type='url'
                                                    placeholder="Enter Video URL"
                                                    aria-label="fullname"
                                                    aria-describedby="basic-addon1"
                                                    className='border-dashed'
                                                    value={formData.video || ''}
                                                    onChange={handleFormChange}
                                                    name='video'
                                                />
                                            </InputGroup>
                                            <small>Make sure the Link is valid</small>
                                        </Form.Group>
                                    </Row>
                                    <div className="d-flex justify-content-end">
                                        <Button variant="outline-blue" type="reset" className='ms-auto py-2 rounded-35'>
                                            reset
                                        </Button>
                                        <Button variant="blue" type="submit" className='ms-2 py-2 px-5 rounded-35'>
                                            Add
                                        </Button>
                                    </div>
                                </Form>
                            )}
                        </div>
                    </div>
                </Col>
            </Row>

            <Modal show={show} onHide={handleClose} className='modal-admin' centered>
                <Modal.Header closeButton>
                    <Modal.Title>View Media</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    {mediaLoading?(
                        <div className='py-3 d-flex justify-content-center align-items-center'>
                            <Spinner animation="grow" variant="primary" />
                            <Spinner animation="grow" variant="secondary" />
                            <Spinner animation="grow" variant="success" />
                            <Spinner animation="grow" variant="danger" />
                            <Spinner animation="grow" variant="warning" />
                            <Spinner animation="grow" variant="info" />
                        </div>
                    ):(
                        <></>
                    )}
                    {viewImg?(
                        imagePreview?(
                            <img 
                                className='w-100' 
                                src={imagePreview} 
                                alt="material image" 
                                onLoad={handleMediaLoaded}
                                style={{ display: mediaLoading ? 'none' : 'block' }}
                            />
                        ):(
                            <img 
                                className='w-100' 
                                src={`${mediaPath}/image/${materialData.IMAGE}`} 
                                alt="material image" 
                                onLoad={handleMediaLoaded}
                                style={{ display: mediaLoading ? 'none' : 'block' }}
                            />
                        )
                    ):(
                        audioPreview?(
                            <div className='w-100 d-flex justify-content-center align-items-center'>
                                <audio controls 
                                    src={audioPreview} 
                                    onCanPlay={handleMediaLoaded}
                                    style={{ display: mediaLoading ? 'none' : 'block' }}
                                >
                                </audio>
                            </div>
                        ):(
                            <div className='w-100 d-flex justify-content-center align-items-center'>
                                <audio controls 
                                    src={`${mediaPath}/audio/${materialData.AUDIO}`} 
                                    onCanPlay={handleMediaLoaded}
                                    style={{ display: mediaLoading ? 'none' : 'block' }}
                                >
                                </audio>
                            </div>
                        )
                    )}
                </Modal.Body>
            </Modal>  

            <ModalOperation
                show={showLoader}
                handleClose={handleCloseLoader}
                title={loaderState.title}
                description={loaderState.description}
                loading={loaderState.loading}
                successMessage={loaderState.successMessage}
                confirmAction={loaderState.confirmAction}
                handleConfirm={loaderState.handleConfirm}
            />
        </div>
    );
};

export default UpdateMaterials;
