import React, { useState, useEffect, useCallback } from 'react';
import { langString } from '../../Helpers';

/**
 * ZoomParticipantsModal
 *
 * A professional slide-in modal that displays the participant list for a given
 * Zoom meeting date / date range. Supports search, pagination, and CSV export.
 *
 * Props:
 *   isOpen        {bool}   – show/hide the modal
 *   onClose       {func}   – called when the user closes the modal
 *   userId        {string} – Zoom user ID (host)
 *   date          {string} – 'YYYY-MM-DD' single day (Daily Report)
 *   fromDate      {string} – 'YYYY-MM-DD' range start (Account Report)
 *   toDate        {string} – 'YYYY-MM-DD' range end   (Account Report)
 *   label         {string} – header subtitle (e.g. "2026-03-02" or "admin@...")
 */
function ZoomParticipantsModal({ isOpen, onClose, userId, date, fromDate, toDate, label }) {
    const [loading, setLoading]           = useState(false);
    const [participants, setParticipants] = useState([]);
    const [errorMessage, setErrorMessage] = useState('');
    const [searchQuery, setSearchQuery]   = useState('');
    const [currentPage, setCurrentPage]   = useState(1);
    const [meetingCount, setMeetingCount] = useState(0);
    const itemsPerPage = 10;

    const fetchParticipants = useCallback(async () => {
        if (!userId) return;
        setLoading(true);
        setErrorMessage('');
        setParticipants([]);
        setCurrentPage(1);

        try {
            let path = `meetinghub/v2/zoom/reports/participants?userId=${encodeURIComponent(userId)}`;
            if (date) {
                path += `&date=${date}`;
            } else if (fromDate && toDate) {
                path += `&fromDate=${fromDate}&toDate=${toDate}`;
            }

            const response = await wp.apiFetch({ path, method: 'GET' });

            if (response) {
                if (response.success === false && response.message) {
                    setErrorMessage(response.message);
                } else {
                    setParticipants(response.participants || []);
                    setMeetingCount(response.meeting_count || 0);
                }
            }
        } catch (err) {
            setErrorMessage(langString('api_error') || 'An error occurred while fetching participants.');
        } finally {
            setLoading(false);
        }
    }, [userId, date, fromDate, toDate]);

    useEffect(() => {
        if (isOpen) {
            setSearchQuery('');
            fetchParticipants();
        }
    }, [isOpen, fetchParticipants]);

    // Close on Escape key.
    useEffect(() => {
        const handleKeyDown = (e) => { if (e.key === 'Escape') onClose(); };
        if (isOpen) document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, onClose]);

    // Prevent body scroll when open.
    useEffect(() => {
        document.body.style.overflow = isOpen ? 'hidden' : '';
        return () => { document.body.style.overflow = ''; };
    }, [isOpen]);

    /** ── Filtering ── */
    const filtered = participants.filter(p => {
        const q = searchQuery.toLowerCase();
        return (
            (p.name  || '').toLowerCase().includes(q) ||
            (p.email || '').toLowerCase().includes(q) ||
            (p.meeting_topic || '').toLowerCase().includes(q)
        );
    });

    const totalPages   = Math.max(1, Math.ceil(filtered.length / itemsPerPage));
    const safePage     = Math.min(currentPage, totalPages);
    const sliceStart   = (safePage - 1) * itemsPerPage;
    const currentData  = filtered.slice(sliceStart, sliceStart + itemsPerPage);

    /** ── Helpers ── */
    const formatTime = (iso) => {
        if (!iso) return '—';
        return new Date(iso).toLocaleString([], { dateStyle: 'short', timeStyle: 'short' });
    };

    const formatDuration = (secs) => {
        if (!secs) return '0 min';
        const m = Math.floor(secs / 60);
        const s = secs % 60;
        return s > 0 ? `${m}m ${s}s` : `${m} min`;
    };

    /** ── CSV Export ── */
    const handleExportCSV = () => {
        const headers = ['Name', 'Email', 'Meeting Topic', 'Join Time', 'Leave Time', 'Duration'];
        const rows = filtered.map(p => [
            p.name          || '',
            p.email         || '',
            p.meeting_topic || '',
            p.join_time  ? new Date(p.join_time).toLocaleString()  : '',
            p.leave_time ? new Date(p.leave_time).toLocaleString() : '',
            p.duration   ? formatDuration(p.duration) : '0 min',
        ]);

        const csvContent = [headers, ...rows]
            .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
            .join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url  = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href     = url;
        link.download = `zoom-participants-${label || date || fromDate}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    };

    /** ── Avatar initials ── */
    const getInitials = (name) => {
        if (!name) return '?';
        const parts = name.trim().split(' ');
        return parts.length >= 2
            ? (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
            : name.substring(0, 2).toUpperCase();
    };

    const avatarColors = ['#7c3aed','#0ea5e9','#10b981','#f59e0b','#ef4444','#8b5cf6','#06b6d4'];
    const getAvatarColor = (name) => {
        let hash = 0;
        for (let i = 0; i < (name || '').length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
        return avatarColors[Math.abs(hash) % avatarColors.length];
    };

    if (!isOpen) return null;

    /** ── Subtitle ── */
    const subtitle = date
        ? `Participants for ${date}`
        : `Participants from ${fromDate} to ${toDate}`;

    return (
        <div className="mhub-modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
            <div className="mhub-participants-modal">

                {/* ── Header ── */}
                <div className="mhub-pm-header">
                    <div className="mhub-pm-header-left">
                        <div className="mhub-pm-icon">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="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>
                        </div>
                        <div>
                            <h2 className="mhub-pm-title">Participant List</h2>
                            <p className="mhub-pm-subtitle">{subtitle}{label ? ` · ${label}` : ''}</p>
                        </div>
                    </div>
                    <button className="mhub-pm-close" onClick={onClose} aria-label="Close">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                        </svg>
                    </button>
                </div>

                {/* ── Stats bar ── */}
                {!loading && !errorMessage && (
                    <div className="mhub-pm-stats">
                        <div className="mhub-pm-stat">
                            <span className="mhub-pm-stat-value">{participants.length}</span>
                            <span className="mhub-pm-stat-label">Total Participants</span>
                        </div>
                        <div className="mhub-pm-stat-divider"/>
                        <div className="mhub-pm-stat">
                            <span className="mhub-pm-stat-value">{meetingCount}</span>
                            <span className="mhub-pm-stat-label">Meetings</span>
                        </div>
                        {filtered.length !== participants.length && (
                            <>
                                <div className="mhub-pm-stat-divider"/>
                                <div className="mhub-pm-stat">
                                    <span className="mhub-pm-stat-value">{filtered.length}</span>
                                    <span className="mhub-pm-stat-label">Filtered</span>
                                </div>
                            </>
                        )}
                    </div>
                )}

                {/* ── Toolbar ── */}
                {!loading && !errorMessage && participants.length > 0 && (
                    <div className="mhub-pm-toolbar">
                        <div className="mhub-pm-search-wrap">
                            <svg className="mhub-pm-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                            </svg>
                            <input
                                type="text"
                                className="mhub-pm-search"
                                placeholder="Search by name, email or meeting…"
                                value={searchQuery}
                                onChange={(e) => { setSearchQuery(e.target.value); setCurrentPage(1); }}
                            />
                            {searchQuery && (
                                <button className="mhub-pm-search-clear" onClick={() => { setSearchQuery(''); setCurrentPage(1); }}>✕</button>
                            )}
                        </div>
                        <button className="mhub-pm-export-btn" onClick={handleExportCSV}>
                            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                <polyline points="7 10 12 15 17 10"/>
                                <line x1="12" y1="15" x2="12" y2="3"/>
                            </svg>
                            Export CSV
                        </button>
                    </div>
                )}

                {/* ── Body ── */}
                <div className="mhub-pm-body">

                    {/* Loading */}
                    {loading && (
                        <div className="mhub-pm-loading">
                            <div className="mhub-pm-spinner"/>
                            <p>Fetching participants from Zoom…</p>
                        </div>
                    )}

                    {/* Error */}
                    {!loading && errorMessage && (
                        <div className="mhub-pm-error">
                            <div className="mhub-pm-error-icon">
                                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
                                    <circle cx="12" cy="12" r="10"/>
                                    <line x1="12" y1="8" x2="12" y2="12"/>
                                    <line x1="12" y1="16" x2="12.01" y2="16"/>
                                </svg>
                            </div>
                            <h3>Unable to Load Participants</h3>
                            <p>{errorMessage}</p>
                            <button className="mhub-pm-retry-btn" onClick={fetchParticipants}>Try Again</button>
                        </div>
                    )}

                    {/* Empty */}
                    {!loading && !errorMessage && participants.length === 0 && (
                        <div className="mhub-pm-empty">
                            <div className="mhub-pm-empty-icon">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" 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>
                            </div>
                            <h3>No Participants Found</h3>
                            <p>No meetings or participants were found for this period.</p>
                        </div>
                    )}

                    {/* No search results */}
                    {!loading && !errorMessage && participants.length > 0 && filtered.length === 0 && (
                        <div className="mhub-pm-empty">
                            <div className="mhub-pm-empty-icon">
                                <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round">
                                    <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                                </svg>
                            </div>
                            <h3>No Results</h3>
                            <p>No participants match "<strong>{searchQuery}</strong>".</p>
                        </div>
                    )}

                    {/* Table */}
                    {!loading && !errorMessage && filtered.length > 0 && (
                        <div className="mhub-pm-table-wrap">
                            <table className="mhub-pm-table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Participant</th>
                                        <th>Meeting</th>
                                        <th>Join Time</th>
                                        <th>Leave Time</th>
                                        <th>Duration</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {currentData.map((p, i) => (
                                        <tr key={`${p.email}-${i}`}>
                                            <td className="mhub-pm-td-num">{sliceStart + i + 1}</td>
                                            <td>
                                                <div className="mhub-pm-participant-cell">
                                                    <div
                                                        className="mhub-pm-avatar"
                                                        style={{ background: getAvatarColor(p.name) }}
                                                    >
                                                        {getInitials(p.name)}
                                                    </div>
                                                    <div className="mhub-pm-participant-info">
                                                        <span className="mhub-pm-name">{p.name || '—'}</span>
                                                        {p.email && <span className="mhub-pm-email">{p.email}</span>}
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                {p.meeting_topic
                                                    ? <span className="mhub-pm-topic-badge">{p.meeting_topic}</span>
                                                    : <span className="mhub-pm-na">—</span>
                                                }
                                            </td>
                                            <td className="mhub-pm-td-time">{formatTime(p.join_time)}</td>
                                            <td className="mhub-pm-td-time">{formatTime(p.leave_time)}</td>
                                            <td>
                                                <span className="mhub-pm-duration-badge">
                                                    {formatDuration(p.duration)}
                                                </span>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>

                {/* ── Pagination ── */}
                {!loading && !errorMessage && totalPages > 1 && (
                    <div className="mhub-pm-footer">
                        <span className="mhub-pm-page-info">
                            Showing {sliceStart + 1}–{Math.min(sliceStart + itemsPerPage, filtered.length)} of {filtered.length}
                        </span>
                        <div className="mhub-pm-pagination">
                            <button
                                className="mhub-pm-page-btn"
                                disabled={safePage === 1}
                                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                            >‹</button>
                            {[...Array(totalPages).keys()].map(n => (
                                <button
                                    key={n + 1}
                                    className={`mhub-pm-page-btn${safePage === n + 1 ? ' active' : ''}`}
                                    onClick={() => setCurrentPage(n + 1)}
                                >{n + 1}</button>
                            ))}
                            <button
                                className="mhub-pm-page-btn"
                                disabled={safePage === totalPages}
                                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                            >›</button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

export default ZoomParticipantsModal;
