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


function ZoomDailyReports({ dailyReportData, 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 [modalDate, setModalDate]     = useState('');
    const [modalUserId, setModalUserId] = useState('');

    // Resolve the first active Zoom user ID from localized data.
    const getZoomUserId = () => {
        const users = (window.mhubMeetingsData && window.mhubMeetingsData.zoom_users) || [];
        if (Array.isArray(users) && users.length > 0) {
            return users[0].id || users[0].email || '';
        }
        if (typeof users === 'object' && !Array.isArray(users)) {
            const keys = Object.keys(users);
            if (keys.length > 0) return users[keys[0]].id || users[keys[0]].email || keys[0];
        }
        return 'me';
    };

    const handleViewParticipants = (date) => {
        setModalDate(date);
        setModalUserId(getZoomUserId());
        setModalOpen(true);
    };


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

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

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

        const sortedData = [...dailyReportData].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 'date':
                return item.date;
            case 'meetings':
                return item.meetings;
            case 'new_users':
                return item.new_users;
            case 'participants':
                return item.participants;
            case 'meeting_minutes':
                return item.meeting_minutes;
            default:
                return '';
        }
    };

    const filteredData = getSortedData().filter(item =>
        item.date.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.meetings.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.new_users.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.participants.toString().toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.meeting_minutes.toString().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">
                    {dailyReportData.length ? (
                        <div className="search-container">
                            <input
                                type="text"
                                placeholder={langString('search')}
                                value={searchQuery}
                                onChange={handleSearchChange}
                                className="search-input"
                            />
                        </div>
                    ) : ''}

                    <div className={`${dailyReportData.length ? 'mhub-has-data-lists' : 'mhub-has-no-data'}`}>
                        {dailyReportData.length ? (
                            <div className="table-container">
                                <table className="meeting-hub-table">
                                    <thead>
                                        <tr>
                                            <th onClick={() => handleSort('date')} className={sortBy === 'date' ? `sortable ${sortOrder}` : 'sortable'}>{langString('date')}</th>
                                            <th onClick={() => handleSort('meetings')} className={sortBy === 'meetings' ? `sortable ${sortOrder}` : 'sortable'}>{langString('meetings')}</th>
                                            <th onClick={() => handleSort('new_users')} className={sortBy === 'new_users' ? `sortable ${sortOrder}` : 'sortable'}>{langString('new_users')}</th>
                                            <th onClick={() => handleSort('participants')} className={sortBy === 'participants' ? `sortable ${sortOrder}` : 'sortable'}>{langString('participants')}</th>
                                            <th onClick={() => handleSort('meeting_minutes')} className={sortBy === 'meeting_minutes' ? `sortable ${sortOrder}` : 'sortable'}>{langString('meeting_minutes')}</th>
                                            <th className="mhub-action-col">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {currentData.map((item, index) => (
                                            <tr key={index}>
                                                <td>{item.date}</td>
                                                <td>{item.meetings > 0 ? <strong style={{ color: '#4300FF', fontSize: '16px' }}>{item.meetings}</strong> : 0}</td>
                                                <td>{item.new_users > 0 ? <strong style={{ color: '#00A1B5', fontSize: '16px' }}>{item.new_users}</strong> : 0}</td>
                                                <td>
                                                    {item.participants > 0
                                                        ? <strong style={{ color: '#00AF00', 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 className="mhub-action-col">
                                                    {item.participants > 0 ? (
                                                        proActive ? (
                                                            <button
                                                                className="mhub-report-action-btn"
                                                                onClick={() => handleViewParticipants(item.date)}
                                                            >
                                                                <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 && dailyReportData.length ? (
                        <div className="empty-meeting-wrapper">
                          <p>{langString('no_records')}</p>
                        </div>
                    ) : ''}

                    {dailyReportData.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}
            date={modalDate}
            label={modalDate}
        />
        </>
    );
}

export default ZoomDailyReports;
