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


function ZoomAccountReports({ accountReportData, fromDate, toDate, proActive, openProModal }) {
    const [loading, setLoading] = useState(true);
    const [sortBy, setSortBy] = useState('');
    const [sortOrder, setSortOrder] = useState('asc');
    const [currentPage, setCurrentPage] = useState(1);
    const [searchQuery, setSearchQuery] = useState('');
    const itemsPerPage = 10;

    // Participant modal state.
    const [modalOpen, setModalOpen]     = useState(false);
    const [modalUserId, setModalUserId] = useState('');
    const [modalLabel, setModalLabel]   = useState('');

    const handleViewParticipants = (email) => {
        setModalUserId(email);
        setModalLabel(email);
        setModalOpen(true);
    };


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

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

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

        const sortedData = [...accountReportData].sort((a, b) => {
            const aValue = getSortableValue(a, sortBy);
            const bValue = getSortableValue(b, sortBy);

            if (sortOrder === 'asc') {
                return aValue > bValue ? 1 : -1;
            } else {
                return aValue < bValue ? 1 : -1;
            }
        });

        return sortedData;
    };

    const getSortableValue = (item, column) => {
        switch (column) {
            case 'email':
                return item.email;
            case 'meetings':
                return item.meetings;
            case 'participants':
                return item.participants;
            case 'meeting_minutes':
                return item.meeting_minutes;
            case 'last_login_time':
                return new Date(item.last_login_time).getTime();
            default:
                return '';
        }
    };

    const filteredData = getSortedData().filter(item =>
        item.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.meetings.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.participants.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.meeting_minutes.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.last_login_time.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);
    };

    return (
        <>
        <div id="meeting_hub">
            <div className="mhub-common-dashboard">
                <div className="mhub-table-wrapper">
                    {accountReportData.length ? (
                        <div className="search-container">
                            <input
                                type="text"
                                placeholder={langString('search')}
                                value={searchQuery}
                                onChange={handleSearchChange}
                                className="search-input"
                            />
                        </div>
                    ) : ''}

                    <div className={`${accountReportData.length ? 'mhub-has-data-lists' : 'mhub-has-no-data'}`}>
                        {accountReportData.length ? (
                            <div className="table-container">
                                <table className="meeting-hub-table">
                                    <thead>
                                        <tr>
                                            <th onClick={() => handleSort('email')} className={sortBy === 'email' ? `sortable ${sortOrder}` : 'sortable'}>{langString('email')}</th>
                                            <th onClick={() => handleSort('meetings')} className={sortBy === 'meetings' ? `sortable ${sortOrder}` : 'sortable'}>{langString('meetings_held') }</th>
                                            <th onClick={() => handleSort('participants')} className={sortBy === 'participants' ? `sortable ${sortOrder}` : 'sortable'}>{langString('total_participants') }</th>
                                            <th onClick={() => handleSort('meeting_minutes')} className={sortBy === 'meeting_minutes' ? `sortable ${sortOrder}` : 'sortable'}>{langString('total_minutes')}</th>
                                            <th onClick={() => handleSort('last_login_time')} className={sortBy === 'last_login_time' ? `sortable ${sortOrder}` : 'sortable'}>{langString('last_login_time')}</th>
                                            <th className="mhub-action-col">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {currentData.map((item, index) => (
                                            <tr key={index}>
                                                <td>{item.email}</td>
                                                <td>{item.meetings > 0 ? <strong style={{ color: '#4300FF', fontSize: '16px' }}>{item.meetings}</strong> : 0}</td>
                                                <td>
                                                    {item.participants > 0
                                                        ? <strong style={{ color: '#00A1B5', fontSize: '16px' }}>{item.participants}</strong>
                                                        : <span style={{color:'#999'}}>0</span>
                                                    }
                                                </td>
                                                <td>{item.meeting_minutes > 0 ? <strong style={{ color: 'red', fontSize: '16px' }}>{item.meeting_minutes}</strong> : 0}</td>
                                                <td>{new Date(item.last_login_time).toLocaleString()}</td>
                                                <td className="mhub-action-col">
                                                    {item.participants > 0 ? (
                                                        proActive ? (
                                                            <button
                                                                className="mhub-report-action-btn"
                                                                onClick={() => handleViewParticipants(item.email)}
                                                            >
                                                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                                                    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
                                                                    <path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
                                                                </svg>
                                                                View Participants
                                                            </button>
                                                        ) : (
                                                            <button
                                                                className="mhub-report-action-btn mhub-report-action-btn--locked"
                                                                onClick={openProModal}
                                                                title="Upgrade to Pro"
                                                            >
                                                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                                                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                                                                </svg>
                                                                View Participants
                                                                <span className="mhub-pro-tag" style={{marginLeft:'4px',fontSize:'10px',padding:'1px 6px'}}>PRO</span>
                                                            </button>
                                                        )
                                                    ) : (
                                                        <span className="mhub-action-na">—</span>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : (
                            <div className="empty-user-wrapper">
                                <h1>{langString('no_report_data')}</h1>
                            </div>
                        )}
                    </div>

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

                    {accountReportData.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>

        {/* Participant Modal */}
        <ZoomParticipantsModal
            isOpen={modalOpen}
            onClose={() => setModalOpen(false)}
            userId={modalUserId}
            fromDate={fromDate}
            toDate={toDate}
            label={modalLabel}
        />
        </>
    );
}

export default ZoomAccountReports;
