import React, { useEffect, useState } from "react";
import Spinner from "../common/Spinner";
const { __ } = wp.i18n;
import { langString } from "../../Helpers";

function ZoomRecordings({ recordingsData }) {
    const [loading, setLoading] = useState(true);
    const [sortBy, setSortBy] = useState('');
    const [sortOrder, setSortOrder] = useState('asc');
    const [currentPage, setCurrentPage] = useState(1);
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedRecordingFiles, setSelectedRecordingFiles] = useState({});
    const [expandedRecordings, setExpandedRecordings] = useState({});
    const [errorMessage, setErrorMessage] = useState('');
    const itemsPerPage = 10;

    useEffect(() => {
        setLoading(false);
    }, [recordingsData]);

    const handleSort = (column) => {
        if (sortBy === column) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            setSortBy(column);
            setSortOrder('asc');
        }
    };

    const getSortedData = () => {
        if (!Array.isArray(recordingsData)) return [];

        return [...recordingsData].sort((a, b) => {
            const aValue = getSortableValue(a, sortBy);
            const bValue = getSortableValue(b, sortBy);
            return sortOrder === 'asc' ? (aValue > bValue ? 1 : -1) : (aValue < bValue ? 1 : -1);
        });
    };

    const getSortableValue = (item, column) => {
        switch (column) {
            case 'meeting_id': return item.id;
            case 'topic': return item.topic;
            case 'duration': return item.duration;
            case 'recorded': return new Date(item.start_time).getTime();
            case 'size': return item.total_size;
            default: return '';
        }
    };

    const filteredData = getSortedData().filter(item =>
        item.id.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.topic.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.duration.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.total_size.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        new Date(item.start_time).toLocaleString().toLowerCase().includes(searchQuery.toLowerCase())
    );

    const indexOfLastItem = currentPage * itemsPerPage;
    const indexOfFirstItem = indexOfLastItem - itemsPerPage;
    const currentData = filteredData.slice(indexOfFirstItem, indexOfLastItem);

    const totalPages = Math.ceil(filteredData.length / itemsPerPage);

    const handlePageChange = (page) => {
        if (page < 1 || page > totalPages) return;
        setCurrentPage(page);
    };

    const handleSearchChange = (event) => {
        setSearchQuery(event.target.value);
        setCurrentPage(1);
    };

    const getUniqueRowId = (meetingId, index) => `${meetingId}_${index}`;

    const handleViewRecordings = (meetingId, rowIndex) => {
        const uniqueRowId = getUniqueRowId(meetingId, rowIndex);

        // Toggle expanded state
        setExpandedRecordings(prevState => ({
            ...prevState,
            [uniqueRowId]: !prevState[uniqueRowId]
        }));

        // Only store files if not already stored
        if (!selectedRecordingFiles[uniqueRowId]) {
            const matchedItem = recordingsData.find(item => item.id === meetingId);
            if (matchedItem && matchedItem.recording_files) {
                setSelectedRecordingFiles(prevState => ({
                    ...prevState,
                    [uniqueRowId]: matchedItem.recording_files
                }));
            }
        }
    };

    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'kB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };


    if (loading) return <Spinner />;

   // console.log(recordingsData);

    return (
        <div id="meeting_hub">
            <div className="mhub-common-dashboard">
                <div className="mhub-table-wrapper">
                    {errorMessage && (
                        <div className="error-message" style={{
                            backgroundColor: '#ffebee',
                            color: '#c62828',
                            padding: '10px',
                            marginBottom: '15px',
                            borderRadius: '5px',
                            border: '1px solid #e57373'
                        }}>
                            {errorMessage}
                        </div>
                    )}

                    {recordingsData.length > 0 && (
                        <div className="search-container">
                            <input
                                type="text"
                                placeholder={langString('search')}
                                value={searchQuery}
                                onChange={handleSearchChange}
                                className="search-input"
                            />
                        </div>
                    )}

                    <div className={recordingsData.length ? 'mhub-has-data-lists' : 'mhub-has-no-data'}>
                        {recordingsData.length ? (
                            <div className="table-container">
                                <table className="meeting-hub-table">
                                    <thead>
                                        <tr>
                                            <th onClick={() => handleSort('meeting_id')} className={sortBy === 'meeting_id' ? `sortable ${sortOrder}` : 'sortable'}>{langString('meeting_id')}</th>
                                            <th onClick={() => handleSort('topic')} className={sortBy === 'topic' ? `sortable ${sortOrder}` : 'sortable'}>{langString('topic')}</th>
                                            <th onClick={() => handleSort('duration')} className={sortBy === 'duration' ? `sortable ${sortOrder}` : 'sortable'}>{langString('duration')}</th>
                                            <th onClick={() => handleSort('recorded')} className={sortBy === 'recorded' ? `sortable ${sortOrder}` : 'sortable'}>{langString('recorded')}</th>
                                            <th onClick={() => handleSort('size')} className={sortBy === 'size' ? `sortable ${sortOrder}` : 'sortable'}>{langString('size')}</th>
                                            <th>{langString('action')}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {currentData.map((item, index) => {
                                            const uniqueRowId = getUniqueRowId(item.id, index);
                                            console.log( item.id);
                                            console.log( item.duration);

                                            return (
                                                <React.Fragment key={uniqueRowId}>
                                                    <tr>
                                                        <td>{item.id}</td>
                                                        <td>{item.topic}</td>
                                                        <td>{item.duration}</td>
                                                        <td>{new Date(item.start_time).toLocaleString()}</td>
                                                        <td>{formatFileSize(item.total_size)}</td>
                                                        <td>
                                                            <button
                                                                onClick={() => handleViewRecordings(item.id, index)}
                                                                className="view-recordings-btn"
                                                                style={{
                                                                    background: expandedRecordings[uniqueRowId] ? '#dc3545' : 'none',
                                                                    border: expandedRecordings[uniqueRowId] ? '1px solid #dc3545' : '1px solid #0073aa',
                                                                    color: expandedRecordings[uniqueRowId] ? 'white' : '#0073aa',
                                                                    padding: '5px 10px',
                                                                    cursor: 'pointer',
                                                                    borderRadius: '3px'
                                                                }}
                                                            >
                                                                {expandedRecordings[uniqueRowId] ? langString('hide_recordings') : langString('view_recordings')}
                                                            </button>
                                                        </td>
                                                    </tr>
                                                    {expandedRecordings[uniqueRowId] && (
                                                        <tr>
                                                            <td colSpan="6" style={{ padding: '10px', backgroundColor: '#f9f9f9' }}>
                                                                {selectedRecordingFiles[uniqueRowId]?.length > 0 ? (
                                                                    <div className="recording-files">
                                                                        <h4>{langString('recording_files')}</h4>
                                                                        {selectedRecordingFiles[uniqueRowId].map((file) => (
                                                                            <div key={file.id} style={{
                                                                                marginBottom: '15px',
                                                                                padding: '10px',
                                                                                border: '1px solid #ddd',
                                                                                borderRadius: '5px'
                                                                            }}>
                                                                                <div><strong>{langString('file_type')}: </strong>{file.file_type}</div>
                                                                                <div><strong>{langString('file_size')}: </strong>{ formatFileSize(file.file_size)}</div>
                                                                                <div style={{ marginTop: '10px' }}>
                                                                                    <a href={file.play_url} target="_blank" rel="noopener noreferrer" style={{
                                                                                        marginRight: '10px',
                                                                                        padding: '5px 10px',
                                                                                        backgroundColor: '#0073aa',
                                                                                        color: 'white',
                                                                                        textDecoration: 'none',
                                                                                        borderRadius: '3px',
                                                                                        display: 'inline-block'
                                                                                    }}>
                                                                                        {langString('play')}
                                                                                    </a>
                                                                                    <a href={file.download_url} target="_blank" rel="noopener noreferrer" style={{
                                                                                        padding: '5px 10px',
                                                                                        backgroundColor: '#46b450',
                                                                                        color: 'white',
                                                                                        textDecoration: 'none',
                                                                                        borderRadius: '3px',
                                                                                        display: 'inline-block'
                                                                                    }}>
                                                                                        {langString('download')}
                                                                                    </a>
                                                                                </div>
                                                                            </div>
                                                                        ))}
                                                                    </div>
                                                                ) : (
                                                                    <p>{langString('no_recordings')}</p>
                                                                )}
                                                            </td>
                                                        </tr>
                                                    )}
                                                </React.Fragment>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        ) : (
                            <div className="empty-user-wrapper">
                                <h1>{langString('no_report_data')}</h1>
                            </div>
                        )}
                    </div>

                    {!filteredData.length && recordingsData.length > 0 && (
                        <div className="empty-meeting-wrapper">
                            <p>{langString('no_records')}</p>
                        </div>
                    )}

                    {recordingsData.length > itemsPerPage && (
                        <div className="pagination">
                            <span className={`page-link ${currentPage === 1 ? 'disabled' : ''}`} onClick={() => handlePageChange(currentPage - 1)}>&lt; {langString('previous')}</span>
                            {[...Array(totalPages).keys()].map((page) => (
                                <span key={page + 1} className={`page-link ${currentPage === page + 1 ? 'active' : ''}`} onClick={() => handlePageChange(page + 1)}>{page + 1}</span>
                            ))}
                            <span className={`page-link ${currentPage === totalPages ? 'disabled' : ''}`} onClick={() => handlePageChange(currentPage + 1)}>{langString('next')} &gt;</span>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

export default ZoomRecordings;
