import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { useMhubAdmin } from '../../App/MhubAdminContext';

/**
 * MhubNotice Component
 * 
 * A premium administrative notice component with modern styling and persistence support.
 */
const MhubNotice = ({ notices }) => {
    const { addDismissedNotice } = useMhubAdmin();
    const [dismissingId, setDismissingId] = useState(null);
    const [showOptionsFor, setShowOptionsFor] = useState(null);

    const displayNotices = notices || [];

    if (displayNotices.length === 0) return null;

    const getNoticeContent = (notice) => {
        // If the notice from PHP already has content, use it!
        if (notice.title && notice.message) {
            return {
                title: notice.title,
                message: notice.message,
                linkText: notice.hasOwnProperty('linkText') ? notice.linkText : __('View Settings', 'meetinghub'),
                link: notice.link || '#/',
            };
        }

        const id = notice.id;
        const state = notice.state;

        const contents = {
            zoom_oauth: {
                unprepared: {
                    title: __('Zoom Integration Required', 'meetinghub'),
                    message: __('Configure your Server-to-Server OAuth credentials to enable Zoom meeting creation.', 'meetinghub'),
                },
                unconnected: {
                    title: __('Zoom Not Connected', 'meetinghub'),
                    message: __('Your credentials are saved, but the account is not connected. Please authorize from the "Connect" tab.', 'meetinghub'),
                }
            },
            zoom_sdk: {
                unprepared: {
                    title: __('Join In Browser Not Configured', 'meetinghub'),
                    message: __('To allow joining meetings directly on your site, please configure the Zoom Meeting SDK credentials.', 'meetinghub'),
                }
            },
            webex: {
                unprepared: {
                    title: __('Webex Integration Required', 'meetinghub'),
                    message: __('Configure your Webex Auth credentials to start creating Webex meetings.', 'meetinghub'),
                },
                unconnected: {
                    title: __('Webex Not Connected', 'meetinghub'),
                    message: __('Your Webex credentials are saved, but the account is not connected. Please authorize from the "Connect" tab.', 'meetinghub'),
                }
            },
            msteams: {
                unprepared: {
                    title: __('MS Teams Integration Required', 'meetinghub'),
                    message: __('Configure your Microsoft Teams credentials to enable meeting creation.', 'meetinghub'),
                },
                unconnected: {
                    title: __('MS Teams Not Connected', 'meetinghub'),
                    message: __('Your MS Teams credentials are saved, but the account is not connected. Please authorize from the "Connect" tab.', 'meetinghub'),
                }
            },
            google: {
                unprepared: {
                    title: __('Google Meet Integration Required', 'meetinghub'),
                    message: __('Upload your Google Cloud credential JSON file to enable Google Meet sessions.', 'meetinghub'),
                },
                unconnected: {
                    title: __('Google Meet Not Connected', 'meetinghub'),
                    message: __('Your credentials are loaded, but the account is not authorized. Please authorize from the "Connect" tab.', 'meetinghub'),
                }
            },
            legacy_redirect: {
                unprepared: {
                    title: __('Update Redirect URIs', 'meetinghub'),
                    message: __('We have updated the Redirect URIs for Zoom, Webex, and Google Meet to a new standard format. Please check each platform\'s "Connect" tab and update your app settings as shown in the tutorials.', 'meetinghub'),
                    linkText: '',
                    link: '',
                }
            }
        };

        return contents[id]?.[state] || {
            title: __('Notice', 'meetinghub'),
            message: __('Action required.', 'meetinghub'),
            linkText: '',
            link: '',
        };
    };

    const handleDismiss = (id, duration) => {
        setDismissingId(id);
        setShowOptionsFor(null);

        const data = new FormData();
        data.append('action', 'mhub_dismiss_notice');
        data.append('nonce', mhubMeetingsData.nonce);
        data.append('notice_id', id);
        data.append('duration', duration);

        fetch(mhubMeetingsData.ajax_url, {
            method: 'POST',
            body: data,
        })
            .then(response => response.json())
            .then(res => {
                if (res.success) {
                    // Update global state for reactive UI
                    const expiryTime = duration === 'forever' ? -1 : (Date.now() / 1000) + (parseInt(duration) * 86400);
                    addDismissedNotice(id, expiryTime);
                }
                setDismissingId(null);
            })
            .catch(() => {
                setDismissingId(null);
            });
    };

    const toggleOptions = (id) => {
        setShowOptionsFor(prev => prev === id ? null : id);
    };

    return (
        <div className="mhub-notices-container" style={{ marginBottom: '20px' }}>
            {displayNotices.map((notice, index) => {
                const content = getNoticeContent(notice);
                const isWarning = notice.type === 'warning';
                const optionsVisible = showOptionsFor === notice.id;

                return (
                    <div
                        key={notice.id}
                        className={`mhub-modern-notice ${notice.type}`}
                        style={{
                            marginTop: index === 0 ? '10px' : '0',
                            animation: 'slideDown 0.3s ease-out'
                        }}
                    >
                        <div className="mhub-notice-inner">
                            <div className="mhub-notice-icon-wrapper">
                                <div className="notice-icon">
                                    <span className={`dashicons dashicons-${isWarning ? 'warning' : 'info'}`}></span>
                                </div>
                            </div>
                            <div className="mhub-notice-content">
                                <h4>{content.title}</h4>
                                <p>{content.message}</p>
                            </div>
                        </div>

                        <div className="dismiss-logic">
                            <button
                                className="mhub-notice-close"
                                onClick={() => toggleOptions(notice.id)}
                            >
                                <span className={`dashicons dashicons-${optionsVisible ? 'arrow-up-alt2' : 'no-alt'}`}></span>

                                {optionsVisible && (
                                    <div className="dropdown-menu" onClick={(e) => e.stopPropagation()}>
                                        <div className="dropdown-header">
                                            {__('Dismiss for...', 'meetinghub')}
                                        </div>
                                        {[
                                            { label: __('7 Days', 'meetinghub'), value: '7' },
                                            { label: __('14 Days', 'meetinghub'), value: '14' },
                                            { label: __('1 Month', 'meetinghub'), value: '30' },
                                            { label: __('Don\'t show again', 'meetinghub'), value: 'forever' }
                                        ].map(opt => (
                                            <div
                                                key={opt.value}
                                                className="dropdown-item"
                                                onClick={() => handleDismiss(notice.id, opt.value)}
                                            >
                                                {opt.label}
                                                <span className="dashicons dashicons-arrow-right-alt2"></span>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </button>
                        </div>
                    </div>
                );
            })}
        </div>
    );
};

export default MhubNotice;
