import {useState, useEffect} from '@wordpress/element'
import {
    Card,
    CardBody,
    SelectControl,
    Spinner,
    Button,
    TextControl,
    Modal
} from '@wordpress/components';
import {formatDate} from '../helpers/formatting';
import { __, sprintf } from '@wordpress/i18n';

const SecurityLogs = ({settings}) => {
    const [logs, setLogs] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [logType, setLogType] = useState('');
    const [statusFilter, setStatusFilter] = useState('');
    const [usernameFilter, setUsernameFilter] = useState('');
    const [ipFilter, setIpFilter] = useState('');
    const [dateFrom, setDateFrom] = useState('');
    const [dateTo, setDateTo] = useState('');
    const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const [perPage] = useState(20);
    const [isClearingLogs, setIsClearingLogs] = useState(false);
    const [logSummary, setLogSummary] = useState({
        total: 0,
        success: 0,
        failure: 0,
        warning: 0
    });
    const [activeRow, setActiveRow] = useState(null);
    const [selectedMonth, setSelectedMonth] = useState('');
    const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [isDeletingByDate, setIsDeletingByDate] = useState(false);

    const years = Array.from({length: 6}, (_, i) => {
        const year = new Date().getFullYear() - i;
        return { label: year.toString(), value: year.toString() };
    });

    const months = [
        { label: __('Select Month', 'iron-security'), value: '' },
        { label: __('January', 'iron-security'), value: '01' },
        { label: __('February', 'iron-security'), value: '02' },
        { label: __('March', 'iron-security'), value: '03' },
        { label: __('April', 'iron-security'), value: '04' },
        { label: __('May', 'iron-security'), value: '05' },
        { label: __('June', 'iron-security'), value: '06' },
        { label: __('July', 'iron-security'), value: '07' },
        { label: __('August', 'iron-security'), value: '08' },
        { label: __('September', 'iron-security'), value: '09' },
        { label: __('October', 'iron-security'), value: '10' },
        { label: __('November', 'iron-security'), value: '11' },
        { label: __('December', 'iron-security'), value: '12' }
    ];

    useEffect(() => {
        fetchLogs();
    }, [logType, page]);

    const fetchLogs = () => {
        setIsLoading(true);

        const data = new FormData();
        data.append('action', 'iron_security_get_logs');
        data.append('nonce', settings.nonce);
        data.append('log_type', logType);
        data.append('status', statusFilter);
        data.append('search', usernameFilter);
        data.append('ip_address', ipFilter);
        data.append('date_from', dateFrom);
        data.append('date_to', dateTo);
        data.append('page', page);
        data.append('per_page', perPage);

        fetch(settings.ajaxurl, {
            method: 'POST',
            body: data,
            credentials: 'same-origin'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    setLogs(data.data.logs || []);
                    setTotalPages(data.data.pages || 1);
                    setLogSummary(data.data.summary || {
                        total: data.data.total || 0,
                        success: 0,
                        failure: 0,
                        warning: 0
                    });
                } else {
                    console.error('Error fetching logs:', data.data);
                    setLogs([]);
                    setLogSummary({
                        total: 0,
                        success: 0,
                        failure: 0,
                        warning: 0
                    });
                }
                setIsLoading(false);
            })
            .catch(error => {
                console.error('Error fetching logs:', error);
                setIsLoading(false);
                setLogs([]);
                setLogSummary({
                    total: 0,
                    success: 0,
                    failure: 0,
                    warning: 0
                });
            });
    };

    const applyFilters = () => {
        setPage(1);
        fetchLogs();
    };

    const resetFilters = () => {
        setLogType('');
        setStatusFilter('');
        setUsernameFilter('');
        setIpFilter('');
        setDateFrom('');
        setDateTo('');
        setPage(1);
        setTimeout(() => fetchLogs(), 0);
    };

    const clearLogs = () => {
        if (!confirm(
            sprintf(
                __('Are you sure you want to clear %s? This action cannot be undone.', 'iron-security'),
                logType ? sprintf(__('%s logs', 'iron-security'), getLogTypeLabel(logType)) : __('all logs', 'iron-security')
            )
        )) {
            return;
        }

        setIsClearingLogs(true);

        const data = new FormData();
        data.append('action', 'iron_security_clear_logs');
        data.append('nonce', settings.nonce);
        data.append('log_type', logType);

        fetch(settings.ajaxurl, {
            method: 'POST',
            body: data,
            credentials: 'same-origin'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {

                    alert(data.data.message || __('Logs cleared successfully', 'iron-security'));
                    

                    setPage(1);

                    setTimeout(() => {
                        fetchLogs();
                    }, 500);
                } else {
                    console.error('Error clearing logs:', data.data);
                    alert(sprintf(__('Error clearing logs: %s', 'iron-security'), data.data || __('Unknown error', 'iron-security')));
                }
                setIsClearingLogs(false);
            })
            .catch(error => {
                console.error('Error clearing logs:', error);
                alert(sprintf(__('Error clearing logs: %s', 'iron-security'), error.message));
                setIsClearingLogs(false);
            });
    };

    const exportLogs = () => {

        const data = new FormData();
        data.append('action', 'iron_security_export_logs');
        data.append('nonce', settings.nonce);
        data.append('log_type', logType);
        data.append('status', statusFilter);
        data.append('search', usernameFilter);
        data.append('ip_address', ipFilter);
        data.append('date_from', dateFrom);
        data.append('date_to', dateTo);


        const form = document.createElement('form');
        form.method = 'POST';
        form.action = settings.ajaxurl;
        form.style.display = 'none';


        for (const [key, value] of data.entries()) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = value;
            form.appendChild(input);
        }

        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
    };

    const deleteLogsByDate = () => {
        if (!selectedMonth) {
            alert(__('Please select a month.', 'iron-security'));
            return;
        }

        setIsDeletingByDate(true);

        const data = new FormData();
        data.append('action', 'iron_security_delete_logs_by_date');
        data.append('nonce', settings.nonce);
        data.append('month', selectedMonth);
        data.append('year', selectedYear);

        fetch(settings.ajaxurl, {
            method: 'POST',
            body: data,
            credentials: 'same-origin'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    setIsDeleteModalOpen(false);
                    alert(
                        sprintf(
                            __('Successfully deleted %1$s logs from %2$s %3$s.', 'iron-security'),
                            data.data.deleted_count,
                            months.find(m => m.value === selectedMonth).label,
                            selectedYear
                        )
                    );
                    
                    fetchLogs();
                } else {
                    console.error('Error deleting logs:', data.data);
                    alert(__('Error deleting logs. Please try again.', 'iron-security'));
                }
                setIsDeletingByDate(false);
            })
            .catch(error => {
                console.error('Error deleting logs:', error);
                alert(__('Error deleting logs. Please try again.', 'iron-security'));
                setIsDeletingByDate(false);
            });
    };

    const getLogTypeLabel = (type) => {
        const logTypes = {
            'login': __('Successful Login', 'iron-security'),
            'failed_login': __('Failed Login', 'iron-security'),
            'lockout': __('Lockout', 'iron-security'),
            'two_factor_auth': __('Two-Factor Auth', 'iron-security'),
            'settings_change': __('Settings Change', 'iron-security'),
            'file_change': __('File Change', 'iron-security'),
            'user_enumeration': __('User Enumeration', 'iron-security'),
            'rest_api': __('REST API Access', 'iron-security'),
            'xml_rpc': __('XML-RPC Access', 'iron-security'),
            'security': __('Security Event', 'iron-security'),
            'admin_action': __('Admin Action', 'iron-security'),
            'user_created': __('User Creation', 'iron-security'),
            'user_modified': __('User Modification', 'iron-security'),
            'plugin_action': __('Plugin Action', 'iron-security'),
            'malicious_request': __('Malicious Request', 'iron-security'),
            'role_change': __('Role Change', 'iron-security'),
            'clickjack_attempt': __('Clickjack Attempt', 'iron-security'),
            'api_request': __('API Request', 'iron-security'),
            'suspicious_behavior': __('Suspicious Behavior', 'iron-security'),
            'http_error': __('HTTP Error', 'iron-security'),
            'core_update': __('Core Update', 'iron-security'),
            'theme_action': __('Theme Action', 'iron-security')
        };

        return logTypes[type] || type;
    };

    const getStatusBadge = (status) => {
        const statusClasses = {
            'success': 'success',
            'failure': 'error',
            'warning': 'warning',
            'info': 'info'
        };

        const className = `log-status-badge ${statusClasses[status] || 'default'}`;
        return <span className={className}>{status}</span>;
    };

    const handlePageChange = (newPage) => {
        setPage(newPage);
    };

    const formatDateForInput = (dateString) => {
        if (!dateString) return '';

        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '';

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        return `${year}-${month}-${day}`;
    };

    const handleRowClick = (id) => {
        setActiveRow(activeRow === id ? null : id);
    };

    const renderSummaryCards = () => {
        return (
            <div className="log-summary-cards">
                <div className="log-summary-card total">
                    <div className="card-icon">
                        <span className="dashicons dashicons-list-view"></span>
                    </div>
                    <div className="card-content">
                        <h3>{__('Total Logs', 'iron-security')}</h3>
                        <div className="card-value">{logSummary.total.toLocaleString()}</div>
                    </div>
                </div>

                <div className="log-summary-card success">
                    <div className="card-icon">
                        <span className="dashicons dashicons-yes-alt"></span>
                    </div>
                    <div className="card-content">
                        <h3>{__('Successful Events', 'iron-security')}</h3>
                        <div className="card-value">{logSummary.success.toLocaleString()}</div>
                    </div>
                </div>

                <div className="log-summary-card error">
                    <div className="card-icon">
                        <span className="dashicons dashicons-dismiss"></span>
                    </div>
                    <div className="card-content">
                        <h3>{__('Failed Events', 'iron-security')}</h3>
                        <div className="card-value">{logSummary.failure.toLocaleString()}</div>
                    </div>
                </div>

                <div className="log-summary-card warning">
                    <div className="card-icon">
                        <span className="dashicons dashicons-warning"></span>
                    </div>
                    <div className="card-content">
                        <h3>{__('Warnings', 'iron-security')}</h3>
                        <div className="card-value">{logSummary.warning.toLocaleString()}</div>
                    </div>
                </div>
            </div>
        );
    };

    const renderExtraData = (log) => {
        if (!log.extra_data || Object.keys(log.extra_data).length === 0) {
            return null;
        }


        let extraData = log.extra_data;


        if (typeof extraData === 'string' &&
            (extraData.match(/^[asbidONCo]:\d+:/) || extraData.match(/^a:\d+:{/))) {
            try {
                try {
                    extraData = JSON.parse(extraData);
                } catch (e) {

                    const formattedData = {};
                    const keyValueRegex = /s:\d+:"([^"]+)";[sbidON]:[^;]*;|s:\d+:"([^"]+)";s:\d+:"([^"]*)";/g;
                    let match;

                    while ((match = keyValueRegex.exec(extraData)) !== null) {

                        const key = match[1] || match[2];

                        if (match[3] !== undefined) {
                            formattedData[key] = match[3];
                        } else {

                            const valueMatch = extraData.substring(match.index + match[0].length).match(/^[sbidON]:([^;]*);/);
                            if (valueMatch) {
                                formattedData[key] = valueMatch[1];
                            } else {
                                formattedData[key] = 'Complex value';
                            }
                        }
                    }

                    if (Object.keys(formattedData).length === 0) {
                        formattedData['serialized_data'] = 'Additional data is stored in serialized format. View in database for details.';
                    }

                    extraData = formattedData;
                }
            } catch (error) {

                extraData = {
                    error: 'Could not parse serialized data',
                    raw_data: extraData.substring(0, 100) + (extraData.length > 100 ? '...' : '')
                };
            }
        }

        return (
            <div className="log-extra-data">
                <h4>{__('Additional Details', 'iron-security')}</h4>
                <table className="extra-data-table">
                    <tbody>
                    {Object.entries(extraData).map(([key, value]) => (
                        <tr key={key}>
                            <th>{key.replace(/_/g, ' ')}</th>
                            <td>
                                {typeof value === 'object'
                                    ? JSON.stringify(value, null, 2)
                                    : String(value)}
                            </td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
        );
    };


    const Pagination = ({ currentPage, totalPages, onPageChange }) => {
        const getPageNumbers = () => {
            const pages = [];
            const maxPagesToShow = 5;

            pages.push(1);

            let startPage = Math.max(2, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(totalPages - 1, startPage + maxPagesToShow - 3);
            

            if (startPage > 2) {
                pages.push('...');
            }
            

            for (let i = startPage; i <= endPage; i++) {
                pages.push(i);
            }
            

            if (endPage < totalPages - 1) {
                pages.push('...');
            }
            

            if (totalPages > 1) {
                pages.push(totalPages);
            }
            
            return pages;
        };

        if (totalPages <= 1) return null;

        return (
            <div className="iron-security-pagination">
                <button 
                    className="pagination-button prev-button"
                    onClick={() => onPageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                >
                    <span className="dashicons dashicons-arrow-left-alt2"></span>
                </button>
                
                <div className="pagination-numbers">
                    {getPageNumbers().map((pageNum, index) => (
                        pageNum === '...' ? (
                            <span key={`ellipsis-${index}`} className="pagination-ellipsis">...</span>
                        ) : (
                            <button
                                key={`page-${pageNum}`}
                                className={`pagination-number ${pageNum === currentPage ? 'active' : ''}`}
                                onClick={() => onPageChange(pageNum)}
                                disabled={pageNum === currentPage}
                            >
                                {pageNum}
                            </button>
                        )
                    ))}
                </div>
                
                <button 
                    className="pagination-button next-button"
                    onClick={() => onPageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                >
                    <span className="dashicons dashicons-arrow-right-alt2"></span>
                </button>
            </div>
        );
    };

    return (
        <div className="security-logs-container">
            {/* Summary Cards */}
            {!isLoading && renderSummaryCards()}

            <Card className="security-logs-card">
                <CardBody>
                    <div className="filters-section">
                        <div className="primary-filters">
                            <div className="filter-row">
                                <SelectControl
                                    label={__("Log Type", "iron-security")}
                                    value={logType}
                                    options={[
                                        {label: __('All Logs', 'iron-security'), value: ''},
                                        {label: __('Successful Logins', 'iron-security'), value: 'login'},
                                        {label: __('Failed Logins', 'iron-security'), value: 'failed_login'},
                                        {label: __('Lockouts', 'iron-security'), value: 'lockout'},
                                        {label: __('Two-Factor Authentication', 'iron-security'), value: 'two_factor_auth'},
                                        {label: __('Settings Changes', 'iron-security'), value: 'settings_change'},
                                        {label: __('File Changes', 'iron-security'), value: 'file_change'},
                                        {label: __('User Enumeration Attempts', 'iron-security'), value: 'user_enumeration'},
                                        {label: __('REST API Access', 'iron-security'), value: 'rest_api'},
                                        {label: __('XML-RPC Access', 'iron-security'), value: 'xml_rpc'},
                                        {label: __('Security Events', 'iron-security'), value: 'security'},
                                        {label: __('Admin Actions', 'iron-security'), value: 'admin_action'},
                                        {label: __('User Creation', 'iron-security'), value: 'user_created'},
                                        {label: __('User Modification', 'iron-security'), value: 'user_modified'},
                                        {label: __('Plugin Actions', 'iron-security'), value: 'plugin_action'},
                                        {label: __('Malicious Requests', 'iron-security'), value: 'malicious_request'},
                                        {label: __('Role Changes', 'iron-security'), value: 'role_change'},
                                        {label: __('Clickjack Attempts', 'iron-security'), value: 'clickjack_attempt'},
                                        {label: __('API Requests', 'iron-security'), value: 'api_request'},
                                        {label: __('Suspicious Behavior', 'iron-security'), value: 'suspicious_behavior'},
                                        {label: __('HTTP Errors', 'iron-security'), value: 'http_error'},
                                        {label: __('Core Updates', 'iron-security'), value: 'core_update'},
                                        {label: __('Theme Actions', 'iron-security'), value: 'theme_action'}
                                    ]}
                                    onChange={setLogType}
                                />

                                <SelectControl
                                    label={__("Status", "iron-security")}
                                    value={statusFilter}
                                    options={[
                                        {label: __('All Statuses', 'iron-security'), value: ''},
                                        {label: __('Success', 'iron-security'), value: 'success'},
                                        {label: __('Failure', 'iron-security'), value: 'failure'},
                                        {label: __('Warning', 'iron-security'), value: 'warning'},
                                        {label: __('Info', 'iron-security'), value: 'info'}
                                    ]}
                                    onChange={setStatusFilter}
                                />
                            </div>

                            <div className="filter-row">
                                <div className="date-filter">
                                    <label htmlFor="search-username-message">{__("Search (Username or Message)", "iron-security")}</label>
                                    <input
                                        type="text"
                                        style={{width:"100%"}}
                                        id="search-username-message"
                                        value={usernameFilter}
                                        onChange={setUsernameFilter}
                                    />
                                </div>
                                <div className="date-filter">
                                    <label htmlFor="search-ip-address">{__("IP Address", "iron-security")}</label>
                                    <input
                                        type="text"
                                        style={{width:"100%"}}
                                        id="search-ip-address"
                                        value={ipFilter}
                                        onChange={setIpFilter}
                                    />
                                </div>
                            </div>

                            <div className="filter-row date-filters">
                                <div className="date-filter">
                                    <label htmlFor="date-from">{__('From Date', 'iron-security')}</label>
                                    <input
                                        type="date"
                                        id="date-from"
                                        value={dateFrom}
                                        onChange={(e) => setDateFrom(e.target.value)}
                                    />
                                </div>

                                <div className="date-filter">
                                    <label htmlFor="date-to">{__('To Date', 'iron-security')}</label>
                                    <input
                                        type="date"
                                        id="date-to"
                                        value={dateTo}
                                        onChange={(e) => setDateTo(e.target.value)}
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="filter-actions">
                            <Button
                                className="button button-primary"
                                variant="primary"
                                onClick={applyFilters}
                                disabled={isLoading}
                            >
                                {__('Apply Filters', 'iron-security')}
                            </Button>

                            <Button
                                className="button button"
                                onClick={resetFilters}
                                disabled={isLoading}
                            >
                                {__('Reset Filters', 'iron-security')}
                            </Button>

                            <Button
                                className="button button-secondary clear-logs-button"
                                onClick={clearLogs}
                                disabled={isLoading || isClearingLogs}
                                isBusy={isClearingLogs}
                            >
                                {isClearingLogs ? __('Deleting...', 'iron-security') : __('Delete All Logs', 'iron-security')}
                            </Button>

                        </div>
                    </div>

                    {isLoading ? (
                        <div className="logs-loading">
                            <Spinner/>
                            <p>{__('Loading logs...', 'iron-security')}</p>
                        </div>
                    ) : logs.length === 0 ? (
                        <div className="no-logs">
                            <div className="no-logs-icon">
                                <span className="dashicons dashicons-list-view"></span>
                            </div>
                            <p>{__('No logs found matching your filters.', 'iron-security')}</p>
                            <Button
                                variant="secondary"
                                onClick={resetFilters}
                                icon="undo"
                            >
                                {__('Reset Filters', 'iron-security')}
                            </Button>
                        </div>
                    ) : (
                        <>
                            <div className="logs-table-container">
                                <table className="logs-table">
                                    <thead>
                                    <tr>
                                        <th className="column-date">{__('Date', 'iron-security')}</th>
                                        <th className="column-type">{__('Type', 'iron-security')}</th>
                                        <th className="column-username">{__('Username', 'iron-security')}</th>
                                        <th className="column-ip">{__('IP Address', 'iron-security')}</th>
                                        <th className="column-message">{__('Message', 'iron-security')}</th>
                                        <th className="column-status">{__('Status', 'iron-security')}</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {logs.map(log => (
                                        <React.Fragment key={log.id}>
                                            <tr
                                                className={`log-row log-status-${log.status} ${activeRow === log.id ? 'active' : ''}`}
                                                onClick={() => handleRowClick(log.id)}
                                            >
                                                <td>{formatDate(log.date_created)}</td>
                                                <td>
                                                    <span
                                                        className="log-type-label">{getLogTypeLabel(log.log_type)}</span>
                                                </td>
                                                <td>{log.username || '-'}</td>
                                                <td>{log.ip_address}</td>
                                                <td>{log.message}</td>
                                                <td>{getStatusBadge(log.status)}</td>
                                            </tr>
                                            {activeRow === log.id && log.extra_data && Object.keys(log.extra_data).length > 0 && (
                                                <tr className="log-details-row">
                                                    <td colSpan="6">
                                                        {renderExtraData(log)}
                                                    </td>
                                                </tr>
                                            )}
                                        </React.Fragment>
                                    ))}
                                    </tbody>
                                </table>
                            </div>

                            <div className="logs-pagination-controls">
                                <div className="logs-info">
                                    {sprintf(__('Showing %1$s of %2$s logs', 'iron-security'), logs.length, logSummary.total)}
                                </div>
                            </div>
                            
                            <Pagination 
                                currentPage={page} 
                                totalPages={totalPages} 
                                onPageChange={handlePageChange} 
                            />
                        </>
                    )}
                </CardBody>
            </Card>

            {isDeleteModalOpen && (
                <Modal
                    title={__("Delete Logs by Month/Year", "iron-security")}
                    onRequestClose={() => setIsDeleteModalOpen(false)}
                    className="delete-logs-modal"
                >
                    <div className="delete-logs-form">
                        <p>{__('Select a month and year to delete logs from. This action cannot be undone.', 'iron-security')}</p>
                        
                        <div className="form-row">
                            <SelectControl
                                label="Month"
                                value={selectedMonth}
                                options={months}
                                onChange={setSelectedMonth}
                            />
                        </div>
                        
                        <div className="form-row">
                            <SelectControl
                                label="Year"
                                value={selectedYear}
                                options={years}
                                onChange={setSelectedYear}
                            />
                        </div>
                        
                        <div className="form-actions">
                            <Button
                                variant="primary"
                                onClick={deleteLogsByDate}
                                disabled={isDeletingByDate || !selectedMonth}
                                isBusy={isDeletingByDate}
                            >
                                {isDeletingByDate ? __('Deleting...', 'iron-security') : __('Delete Logs', 'iron-security')}
                            </Button>
                            
                            <Button
                                variant="secondary"
                                onClick={() => setIsDeleteModalOpen(false)}
                                disabled={isDeletingByDate}
                            >
                                {__('Cancel', 'iron-security')}
                            </Button>
                        </div>
                    </div>
                </Modal>
            )}
        </div>
    );
};

export default SecurityLogs; 