import React, { useEffect, useState } from "react";
import './../scss/zoom/zoom_reports.scss';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import ZoomDailyReports from "../components/zoom_reports/ZoomDailyReports";
import Spinner from "../components/common/Spinner";
import ZoomAccountReports from "../components/zoom_reports/ZoomAccountReports";
import ZoomParticipantsByMeeting from "../components/zoom_reports/ZoomParticipantsByMeeting";
import GetProModal from "../components/common/GetProModal";
import { useMhubAdmin } from "./MhubAdminContext";
const { __ } = wp.i18n;
import { langString, isProActive } from "../Helpers";

const proActive = isProActive();

function ZoomReportsApp() {
    const { openProModal } = useMhubAdmin();
    const [activeTab, setActiveTab] = useState('daily');
    const [loading, setLoading] = useState(false);
    const [dailyMonthYear, setDailyMonthYear] = useState(new Date());
    const [dailyReportData, setDailyReportData] = useState({});
    const [accountReportData, setAccountReportData] = useState({});
    const [accountFromDate, setAccountFromDate] = useState(new Date());
    const [accountToDate, setAccountToDate] = useState(new Date());
    const [errorMessage, setErrorMessage] = useState('');

    const handleTabClick = (tab) => {
        setErrorMessage("");
        setActiveTab(tab);
    };

    const maxYear = new Date().getFullYear();
    const maxDate = new Date(maxYear, 11, 31);

    const handleDailyReportData = async () => {
        setLoading(true);
        setErrorMessage("");
        try {
            const month = dailyMonthYear.getMonth() + 1; // Months are zero-indexed in JS
            const year = dailyMonthYear.getFullYear();
            const response = await wp.apiFetch({
                path: `meetinghub/v2/zoom/reports?month=${month}&year=${year}`,
                method: 'GET',
            });

            if (response) {
                if (response.hasOwnProperty('error')) {
                    setErrorMessage(response.error.message);
                }

                if (response.hasOwnProperty('message')) {
                    setErrorMessage(response.message);
                }

                if (response.hasOwnProperty('dates')) {
                    setDailyReportData(response.dates);
                    setErrorMessage("");
                }
            }
            // Save the response data
        } catch (error) {
            console.error( langString('api_error'), error);
        } finally {
            setLoading(false);
        }
    };

    const handleAccountReportData = async () => {
        setLoading(true);
        setErrorMessage("");
    
        try {
            const fromDateFormatted = accountFromDate.toISOString().split('T')[0];
            const toDateFormatted = accountToDate.toISOString().split('T')[0];
    
            const response = await wp.apiFetch({
                path: `meetinghub/v2/zoom/reports/account?fromDate=${fromDateFormatted}&toDate=${toDateFormatted}`,
                method: 'GET',
            });

            if (response) {
                if (response.hasOwnProperty('error')) {
                    setErrorMessage(response.error.message);
                }
    
                if (response.hasOwnProperty('message')) {
                    setErrorMessage(response.message);
                }
    
                if (response.hasOwnProperty('users')) {
                    setAccountReportData(response.users);
                    setErrorMessage("");
                }
            }
        } catch (error) {
            console.error( langString('api_error'), error);
        } finally {
            setLoading(false);
        }
    };

    const handleCloseError = () => {
        setErrorMessage('');
    };

    return (
        <>
        <div id="mhub_zoom_reports">
            <div className="tabs-wrapper">
                <div className="tabs">
                    <div className={`tab-item ${activeTab === 'daily' ? 'active' : ''}`} onClick={() => handleTabClick('daily')}>
                        {langString('daily_report')}
                    </div>
                    <div className={`tab-item ${activeTab === 'account' ? 'active' : ''}`} onClick={() => handleTabClick('account')}>
                        {langString('account_report')}
                    </div>
                    <div className={`tab-item ${activeTab === 'per_meeting' ? 'active' : ''}`} onClick={() => handleTabClick('per_meeting')}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{marginRight:'5px',verticalAlign:'middle'}}>
                            <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>
                        Per-Meeting Report
                        <span className="mhub-new-tag mhub-tag-addon" style={{marginLeft:'8px',verticalAlign:'middle',backgroundColor:'#059669',color:'#ffffff'}}>{langString('new') || 'New'}</span>
                    </div>
                </div>
                {errorMessage && (
                    <div className="mhub_zoom_error error">
                        <h3>{errorMessage}</h3>
                        <span className="close-icon" onClick={handleCloseError}>✕</span>
                    </div>
                )}
                <div className="tab-content">
                    {activeTab === 'daily' && (
                        <div className="daily-report">
                            <div className="mhub-form-group reports-mhub-form-group">
                                <label>{langString('enter_date')}</label>
                                <div className="input-wrapper">
                                    <DatePicker
                                        selected={dailyMonthYear}
                                        onChange={(date) => setDailyMonthYear(date)}
                                        dateFormat="MM/yyyy"
                                        showMonthYearPicker
                                        className="form-control"
                                        maxDate={maxDate}
                                    />
                                </div>
                                <button className='report-show-btn' onClick={handleDailyReportData} disabled={loading}>{ langString('show')}
                                </button>
                            </div>
                        </div>
                    )}
                    {activeTab === 'account' && (
                        <div className="account-report">
                            <div className="mhub-form-group reports-mhub-form-group">
                                <label>{langString('get_account_report')}</label>
                                <div className="input-wrapper">
                                    <DatePicker
                                        selected={accountFromDate}
                                        onChange={(date) => setAccountFromDate(date)}
                                        dateFormat="MM/dd/yyyy"
                                    />
                                </div>
                                <label className="mrl-10">{langString('to')}</label>
                                <div className="input-wrapper">
                                    <DatePicker
                                        selected={accountToDate}
                                        onChange={(date) => setAccountToDate(date)}
                                        dateFormat="MM/dd/yyyy"
                                    />
                                </div>
                                <button className='report-show-btn' onClick={handleAccountReportData} disabled={loading}>{ langString('show')}
                                </button>
                            </div>
                        </div>
                    )}
                    {activeTab === 'per_meeting' && (
                        <div className="per-meeting-report">
                        </div>
                    )}
                </div>
            </div>

            {loading ? (
                <Spinner />
            ) : (
                activeTab === 'daily' ? (
                    dailyReportData.length > 0 ? (
                        <ZoomDailyReports dailyReportData={dailyReportData} proActive={proActive} openProModal={openProModal} />
                    ) : (
                        <div className='mhub-report-info'>
                            <div className="report-info-wrapper">
                                <p>{langString('select_date')}</p>
                            </div>
                        </div>
                    )
                ) : activeTab === 'per_meeting' ? (
                    <div className="mhub-pro-gate-wrapper">
                        <ZoomParticipantsByMeeting />
                        {!proActive && (
                            <div className="mhub-pro-overlay">
                                <div className="pro-overlay-content">
                                    <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="#7856fb" strokeWidth="1.8" 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>
                                    <div style={{textAlign:'center'}}>
                                        <div className="pro-overlay-title">{langString('pro_feature') || 'Pro Feature'}</div>
                                        <div className="pro-overlay-desc">Upgrade to Pro to access Per-Meeting Participant Reports</div>
                                    </div>
                                    <div className="mhub-upgrade-btn" onClick={openProModal} style={{marginTop: '10px'}}>
                                        <i className="dashicons dashicons-lock"></i> {langString('upgrade_to_pro')}
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                ) : activeTab === 'account' && (
                    accountReportData.length > 0 ? (
                        <ZoomAccountReports
                            accountReportData={accountReportData}
                            fromDate={accountFromDate.toISOString().split('T')[0]}
                            toDate={accountToDate.toISOString().split('T')[0]}
                            proActive={proActive}
                            openProModal={openProModal}
                        />
                    ) : (
                        <div className='mhub-report-info'>
                            <div className="report-info-wrapper">
                                <p>{langString('select_valid_range')}</p>
                            </div>
                        </div>
                    )
                )
            )}
        </div>
        <GetProModal />
        </>
    );
}

export default ZoomReportsApp;
