import React, { useState, useEffect } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import ZoomParticipantsModal from './ZoomParticipantsModal';

function ZoomParticipantsByMeeting() {
    const [zoomUsers, setZoomUsers]             = useState([]);
    const [selectedUser, setSelectedUser]       = useState('');
    const [fromDate, setFromDate]               = useState(null);
    const [toDate, setToDate]                   = useState(null);
    const [meetings, setMeetings]               = useState([]);
    const [loadingMeetings, setLoadingMeetings] = useState(false);
    const [meetingsError, setMeetingsError]     = useState('');
    const [modalOpen, setModalOpen]             = useState(false);
    const [activeRow, setActiveRow]             = useState(null);
    const [searched, setSearched]               = useState(false);
    const [searchQuery, setSearchQuery]         = useState('');

    useEffect(() => {
        const users = (window.mhubMeetingsData && window.mhubMeetingsData.zoom_users) || [];
        let userList = [];
        if (Array.isArray(users))                          userList = users;
        else if (typeof users === 'object')                userList = Object.values(users);
        setZoomUsers(userList);
        if (userList.length > 0)
            setSelectedUser(userList[0].id || userList[0].email || 'me');

        const now  = new Date();
        const past = new Date();
        past.setDate(now.getDate() - 30);
        setToDate(now);
        setFromDate(past);
    }, []);

    const totalParticipants = meetings.reduce((s, m) => s + (m.participant_count || 0), 0);

    const filteredMeetings = meetings.filter(m =>
        !searchQuery ||
        (m.meeting_topic || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
        String(m.meeting_id).includes(searchQuery)
    );

    const handleFetchMeetings = async () => {
        if (!selectedUser || !fromDate || !toDate) return;
        setLoadingMeetings(true);
        setMeetingsError('');
        setMeetings([]);
        setSearched(true);
        setSearchQuery('');

        const fromStr = fromDate.toISOString().split('T')[0];
        const toStr   = toDate.toISOString().split('T')[0];

        try {
            const path = `meetinghub/v2/zoom/reports/participants?userId=${encodeURIComponent(selectedUser)}&fromDate=${fromStr}&toDate=${toStr}`;
            const res  = await wp.apiFetch({ path, method: 'GET' });

            if (res && res.success === false) {
                setMeetingsError(res.message || 'Error fetching meetings.');
            } else if (res && res.participants) {
                const meetingMap = {};
                res.participants.forEach(p => {
                    const key = p.meeting_id;
                    if (!meetingMap[key]) {
                        meetingMap[key] = {
                            meeting_id:       p.meeting_id,
                            meeting_topic:    p.meeting_topic || `Meeting ${key}`,
                            meeting_start:    p.meeting_start || '',
                            participant_count: 0,
                        };
                    }
                    meetingMap[key].participant_count++;
                });
                const list = Object.values(meetingMap);
                if (list.length === 0) setMeetingsError('No meetings found for the selected period.');
                else setMeetings(list);
            }
        } catch (err) {
            setMeetingsError('An error occurred while fetching meetings.');
        } finally {
            setLoadingMeetings(false);
        }
    };

    const handleViewParticipants = (meeting) => {
        setActiveRow(meeting);
        setModalOpen(true);
    };

    const formatDate = (iso) => {
        if (!iso) return '—';
        return new Date(iso).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' });
    };

    /** Initials + colour for meeting topic avatar */
    const topicColors = ['#7c3aed','#0ea5e9','#10b981','#f59e0b','#ef4444','#8b5cf6','#0891b2'];
    const topicColor  = (s) => topicColors[s.charCodeAt(0) % topicColors.length];
    const topicInitial = (s) => (s || '?')[0].toUpperCase();

    return (
        <div className="mhub-pmt-wrap">

            {/* ── Filter card ── */}
            <div className="mhub-pmt-filter-card">
                <div className="mhub-pmt-filter-card-head">
                    <div className="mhub-pmt-filter-head-icon">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                            <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>
                        </svg>
                    </div>
                    <div>
                        <div className="mhub-pmt-filter-head-title">Filter Meetings</div>
                        <div className="mhub-pmt-filter-head-sub">Choose a Zoom host and date range to list meetings</div>
                    </div>
                </div>

                <div className="mhub-pmt-filter-fields">
                    {/* Zoom user */}
                    {zoomUsers.length > 0 && (
                        <div className="mhub-pmt-field">
                            <label className="mhub-pmt-label">
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
                                </svg>
                                Zoom User
                            </label>
                            <select
                                className="mhub-pmt-select"
                                value={selectedUser}
                                onChange={e => setSelectedUser(e.target.value)}
                            >
                                {zoomUsers.map((u, i) => (
                                    <option key={i} value={u.id || u.email || 'me'}>
                                        {u.email || u.id || 'me'}
                                    </option>
                                ))}
                            </select>
                        </div>
                    )}

                    {/* From */}
                    <div className="mhub-pmt-field">
                        <label className="mhub-pmt-label">
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                            </svg>
                            From
                        </label>
                        <DatePicker
                            selected={fromDate}
                            onChange={(date) => setFromDate(date)}
                            dateFormat="MM/dd/yyyy"
                            className="mhub-pmt-date"
                            placeholderText="From date"
                            portalId="mhub-datepicker-portal"
                            popperPlacement="bottom-start"
                        />
                    </div>

                    {/* To */}
                    <div className="mhub-pmt-field">
                        <label className="mhub-pmt-label">
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                            </svg>
                            To
                        </label>
                        <DatePicker
                            selected={toDate}
                            onChange={(date) => setToDate(date)}
                            dateFormat="MM/dd/yyyy"
                            className="mhub-pmt-date"
                            placeholderText="To date"
                            portalId="mhub-datepicker-portal"
                            popperPlacement="bottom-start"
                        />
                    </div>

                    <button
                        className="mhub-pmt-search-btn"
                        onClick={handleFetchMeetings}
                        disabled={loadingMeetings || !fromDate || !toDate}
                    >
                        {loadingMeetings ? (
                            <><span className="mhub-pmt-spinner" /> Loading…</>
                        ) : (
                            <>
                                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
                                    <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                                </svg>
                                Show Meetings
                            </>
                        )}
                    </button>
                </div>
            </div>

            {/* ── Error ── */}
            {meetingsError && (
                <div className="mhub-pmt-error-banner">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" 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>
                        <strong>Unable to load meetings</strong>
                        <p>{meetingsError}</p>
                    </div>
                </div>
            )}

            {/* ── Summary pills ── */}
            {meetings.length > 0 && (
                <div className="mhub-pmt-summary">
                    <div className="mhub-pmt-summary-pill mhub-pmt-pill-purple">
                        <span className="mhub-pmt-pill-value">{meetings.length}</span>
                        <span className="mhub-pmt-pill-label">Meetings</span>
                    </div>
                    <div className="mhub-pmt-summary-arrow">→</div>
                    <div className="mhub-pmt-summary-pill mhub-pmt-pill-green">
                        <span className="mhub-pmt-pill-value">{totalParticipants}</span>
                        <span className="mhub-pmt-pill-label">Total Participants</span>
                    </div>
                    <div className="mhub-pmt-summary-arrow">·</div>
                    <span className="mhub-pmt-summary-range">
                        {fromDate ? fromDate.toLocaleDateString() : ''} → {toDate ? toDate.toLocaleDateString() : ''}
                    </span>

                    {/* Search within results */}
                    <div className="mhub-pmt-table-search-wrap">
                        <svg width="14" height="14" 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-pmt-table-search"
                            placeholder="Filter topics…"
                            value={searchQuery}
                            onChange={e => setSearchQuery(e.target.value)}
                        />
                        {searchQuery && (
                            <button className="mhub-pmt-search-clear" onClick={() => setSearchQuery('')}>✕</button>
                        )}
                    </div>
                </div>
            )}

            {/* ── Meeting table ── */}
            {meetings.length > 0 && (
                <div className="mhub-pmt-table-card">
                    <table className="mhub-pmt-table">
                        <thead>
                            <tr>
                                <th className="mhub-pmt-th-idx">#</th>
                                <th>Meeting Topic</th>
                                <th>Start Time</th>
                                <th>Meeting ID</th>
                                <th>Participants</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredMeetings.length === 0 ? (
                                <tr>
                                    <td colSpan="6" className="mhub-pmt-no-filter">
                                        No meetings match "<strong>{searchQuery}</strong>"
                                    </td>
                                </tr>
                            ) : filteredMeetings.map((m, i) => (
                                <tr key={m.meeting_id}>
                                    <td className="mhub-pmt-td-idx">{i + 1}</td>
                                    <td>
                                        <div className="mhub-pmt-topic-cell">
                                            <div
                                                className="mhub-pmt-topic-avatar"
                                                style={{ background: topicColor(m.meeting_topic) }}
                                            >
                                                {topicInitial(m.meeting_topic)}
                                            </div>
                                            <span className="mhub-pmt-topic-name">{m.meeting_topic}</span>
                                        </div>
                                    </td>
                                    <td className="mhub-pmt-td-time">{formatDate(m.meeting_start)}</td>
                                    <td>
                                        <code className="mhub-pmt-code">{m.meeting_id}</code>
                                    </td>
                                    <td>
                                        <span className={`mhub-pmt-count-badge ${m.participant_count >= 50 ? 'mhub-pmt-badge-hot' : ''}`}>
                                            {m.participant_count}
                                        </span>
                                    </td>
                                    <td>
                                        <button
                                            className="mhub-pmt-view-btn"
                                            onClick={() => handleViewParticipants(m)}
                                        >
                                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
                                            </svg>
                                            View Participants
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* ── Empty / initial state ── */}
            {!loadingMeetings && !meetingsError && meetings.length === 0 && (
                <div className="mhub-pmt-empty-state">
                    <div className="mhub-pmt-empty-rings">
                        <div className="mhub-pmt-empty-ring r1"/>
                        <div className="mhub-pmt-empty-ring r2"/>
                        <div className="mhub-pmt-empty-ring r3"/>
                        <div className="mhub-pmt-empty-icon-wrap">
                            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
                                <polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/>
                            </svg>
                        </div>
                    </div>
                    <h3>{searched ? 'No Meetings Found' : 'Select a Date Range'}</h3>
                    <p>
                        {searched
                            ? 'No meetings were held in the selected period. Try a wider date range.'
                            : 'Configure the filters above and click Show Meetings to see per-meeting participant data.'
                        }
                    </p>
                </div>
            )}

            {/* ── Participant Modal ── */}
            {activeRow && (
                <ZoomParticipantsModal
                    isOpen={modalOpen}
                    onClose={() => { setModalOpen(false); setActiveRow(null); }}
                    userId={selectedUser}
                    fromDate={activeRow.meeting_start ? activeRow.meeting_start.split('T')[0] : (fromDate ? fromDate.toISOString().split('T')[0] : '')}
                    toDate={activeRow.meeting_start   ? activeRow.meeting_start.split('T')[0] : (toDate   ? toDate.toISOString().split('T')[0]   : '')}
                    label={activeRow.meeting_topic}
                />
            )}
        </div>
    );
}

export default ZoomParticipantsByMeeting;
