/**
 * External dependencies.
 */
import { useState, useEffect } from '@wordpress/element';
import {
    Card,
    Button,
    Space,
    Tag,
    Typography,
    Divider,
    Empty,
    Spin,
    Alert,
    Badge,
    Tooltip,
    Switch,
    Progress,
    Skeleton,
    message,
    Statistic,
    Row,
    Col,
    Segmented,
    Modal,
    Popconfirm,
    Timeline,
    List,
    Collapse,
    Table
} from 'antd';
import {
    AppstoreOutlined,
    UnorderedListOutlined,
    CheckCircleOutlined,
    WarningOutlined,
    SecurityScanOutlined,
    CloudUploadOutlined,
    SafetyCertificateOutlined,
    ExclamationCircleOutlined,
    SyncOutlined,
    DeleteOutlined,
    BugOutlined,
    ApiOutlined,
    FileTextOutlined,
    FileSearchOutlined,
    FolderOpenOutlined,
    InfoCircleOutlined,
    CheckCircleTwoTone,
    ExclamationCircleTwoTone,
    QuestionCircleTwoTone,
    CloseCircleTwoTone,
    HistoryOutlined,
    RollbackOutlined,
    DiffOutlined
} from '@ant-design/icons';

/**
 * Internal dependencies.
 */
import { showPromiseToast } from '../../utils';
import { fetchPlugins, updatePluginStatus } from '../../api/plugins';
import Layout from '../layout/Layout';

const { Title, Text, Paragraph } = Typography;
const { Meta } = Card;

const PluginManager = () => {
    const [loading, setLoading] = useState(true);
    const [plugins, setPlugins] = useState([]);
    const [error, setError] = useState(null);
    const [viewMode, setViewMode] = useState('modern');
    const [updatingPlugins, setUpdatingPlugins] = useState({});
    const [stats, setStats] = useState({
        total: 0,
        active: 0,
        secure: 0
    });
    const [safetyCheckModal, setSafetyCheckModal] = useState({
        visible: false,
        loading: false,
        plugin: null,
        results: null,
        error: null
    });
    const [signingPlugins, setSigningPlugins] = useState({});
    const [signedFilesModal, setSignedFilesModal] = useState({
        visible: false,
        loading: false,
        plugin: null,
        files: [],
        error: null
    });
    const [historyModal, setHistoryModal] = useState({
        visible: false,
        loading: false,
        plugin: null,
        history: [],
        error: null
    });
    const [diffModal, setDiffModal] = useState({
        visible: false,
        loading: false,
        plugin: null,
        file: null,
        diff: null,
        error: null
    });



    // Defensive check for wpApiSettings
    if (!window.wpApiSettings || !window.wpApiSettings.root) {
        console.error('wpApiSettings or root is not defined!');
    }

    const renderHistoryModal = () => (
        <Modal
            title={<Space><HistoryOutlined /> Signature Time Machine</Space>}
            open={historyModal.visible}
            onCancel={() => setHistoryModal({ ...historyModal, visible: false })}
            footer={null}
            width={700}
            centered
        >
            <Alert
                message="How Time Machine Works"
                description={<span style={{ fontSize: 13 }}>Every time you protect a plugin, we save a backup. Use the timeline below to roll back to a previous safe state or delete old backups.</span>}
                type="info"
                showIcon
                style={{ marginBottom: 24 }}
            />

            {historyModal.loading ? <div style={{ textAlign: 'center', padding: 40 }}><Spin tip="Loading history..." /></div> : (
                <div style={{ padding: '0 20px' }}>
                    <Timeline mode="left">
                        {historyModal.history.map(item => (
                            <Timeline.Item label={<span style={{ color: '#888', fontSize: 12 }}>{item.date}</span>} key={item.timestamp}>
                                <Card size="small" bodyStyle={{ padding: '12px' }} style={{ marginLeft: 10, marginTop: -6, borderRadius: 8, border: '1px solid #f0f0f0' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <div>
                                            <div style={{ fontWeight: 600, color: '#333' }}>Signature Backup</div>
                                            <div style={{ fontSize: 11, color: '#999', marginTop: 2 }}>ID: {item.timestamp}</div>
                                        </div>
                                        <div style={{ display: 'flex', gap: 8 }}>
                                            <Popconfirm
                                                title="Rollback Signatures"
                                                description="Are you sure you want to revert to this version?"
                                                onConfirm={() => handleRollback(historyModal.plugin, item.timestamp)}
                                                okText="Yes, Rollback"
                                                cancelText="Cancel"
                                            >
                                                <Button
                                                    size="small"
                                                    icon={<RollbackOutlined />}
                                                >
                                                    Rollback
                                                </Button>
                                            </Popconfirm>
                                            <Popconfirm
                                                title="Delete Backup"
                                                description="Are you sure? This cannot be undone."
                                                onConfirm={() => handleDeleteHistory(historyModal.plugin, item.timestamp)}
                                                okText="Delete"
                                                cancelText="Cancel"
                                                okButtonProps={{ danger: true }}
                                            >
                                                <Button
                                                    size="small"
                                                    danger
                                                    icon={<DeleteOutlined />}
                                                />
                                            </Popconfirm>
                                        </div>
                                    </div>
                                </Card>
                            </Timeline.Item>
                        ))}
                    </Timeline>
                    {historyModal.history.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="No backup history available." />}
                </div>
            )}
        </Modal>
    );

    const renderDiffModal = () => (
        <Modal
            title={<Space><DiffOutlined /> File Changes: {diffModal.file}</Space>}
            open={diffModal.visible}
            onCancel={() => setDiffModal({ ...diffModal, visible: false })}
            footer={null}
            width={1000}
            centered
            styles={{ body: { padding: 0 } }}
            zIndex={1002}
        >
            {diffModal.loading ? <div style={{ padding: 40, textAlign: 'center' }}><Spin size="large" /></div> : (
                diffModal.diff ? (
                    <div style={{
                        height: '65vh',
                        overflowY: 'auto',
                        backgroundColor: '#fff',
                        fontFamily: 'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',
                        fontSize: '13px',
                        lineHeight: '1.5',
                        borderBottom: '1px solid #f0f0f0'
                    }}>
                        <div
                            style={{ padding: 16 }}
                            dangerouslySetInnerHTML={{ __html: diffModal.diff }}
                            className="diff-content"
                        />
                        <style>{`
                            .diff-content table.diff { width: 100%; border-collapse: collapse; border: 1px solid #e8e8e8; }
                            .diff-content table.diff td { padding: 4px 8px; border: none; vertical-align: top; }
                            .diff-content table.diff td.diff-deletedline { background-color: #ffeef0; text-decoration: none; }
                            .diff-content table.diff td.diff-addedline { background-color: #e6ffed; text-decoration: none; }
                            .diff-content table.diff td.diff-context { background-color: #fff; color: #666; }
                            .diff-content del { text-decoration: none; background-color: #ffcccc; }
                            .diff-content ins { text-decoration: none; background-color: #ccffcc; }
                        `}</style>
                    </div>
                ) : <Empty description="No diff available (File might be binary or too large)" style={{ padding: 40 }} />
            )}
        </Modal>
    );

    const updateStats = (pluginsList) => {
        setStats({
            total: pluginsList.length,
            active: pluginsList.filter(p => p.status === 'active').length,
            secure: pluginsList.filter(p => p.securityStatus === 'safe').length
        });
    };

    const handlePluginAction = async (pluginId, action) => {
        if (updatingPlugins[pluginId]) {
            return;
        }

        setUpdatingPlugins(prev => ({ ...prev, [pluginId]: true }));

        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/plugins/update-status`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ pluginId, action })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.message || `Failed to ${action} plugin`);
            }

            // Show success message
            message.success(`Plugin ${action} successful`);

            // Update local state
            setPlugins(prevPlugins => prevPlugins.map(p => {
                if (p.id === pluginId) {
                    return {
                        ...p,
                        status: action === 'activate' ? 'active' : 'inactive'
                    };
                }
                return p;
            }));

            // Update statistics
            updateStats(plugins);
        } catch (error) {
            console.error('Error performing plugin action:', error);

            // Extract error message from WordPress error response
            let errorMessage = error.message;
            if (error.message.includes('<p>')) {
                // Parse HTML error message
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = error.message;
                errorMessage = tempDiv.textContent || tempDiv.innerText || 'An error occurred';
            }

            message.error(errorMessage || `Failed to ${action} plugin`);

            // Refresh the list to ensure UI consistency
            await fetchPluginsList();
        } finally {
            setUpdatingPlugins(prev => ({ ...prev, [pluginId]: false }));
        }
    };

    const checkPluginSafety = async (plugin) => {
        try {
            setSafetyCheckModal({
                visible: true,
                loading: true,
                plugin: plugin,
                results: null,
                error: null
            });

            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/plugins/check-safety`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ pluginFile: plugin.id })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.message || 'Failed to check plugin safety');
            }

            setSafetyCheckModal({
                visible: true,
                loading: false,
                plugin: plugin,
                results: data.data,
                error: null
            });

        } catch (error) {
            console.error('Error checking plugin safety:', error);
            message.error(error.message);
            setSafetyCheckModal(prev => ({
                ...prev,
                loading: false,
                error: error.message
            }));
        }
    };

    const renderSafetyResults = (results) => {
        if (!results) return null;

        const getStatusColor = (status) => status ? '#52c41a' : '#ff4d4f';
        const getScoreColor = (score) => {
            if (score >= 90) return '#52c41a';
            if (score >= 70) return '#faad14';
            if (score >= 50) return '#fa8c16';
            return '#ff4d4f';
        };

        return (
            <div className="safety-results">
                <div className="safety-score" style={{ marginBottom: 24, textAlign: 'center' }}>
                    <Progress
                        type="circle"
                        percent={results.safety_score.score}
                        strokeColor={getScoreColor(results.safety_score.score)}
                    />
                    <h3 style={{ marginTop: 16 }}>
                        Safety Score: {results.safety_score.rating.toUpperCase()}
                    </h3>
                    <p>{results.safety_score.message}</p>
                </div>

                <Collapse defaultActiveKey={['1']}>
                    <Collapse.Panel header="Version Compatibility" key="1">
                        <List
                            size="small"
                            dataSource={[
                                {
                                    title: 'WordPress Compatibility',
                                    ...results.wordpress_compatibility
                                },
                                {
                                    title: 'PHP Compatibility',
                                    ...results.php_compatibility
                                }
                            ]}
                            renderItem={item => (
                                <List.Item>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                                        <span>{item.title}</span>
                                        <Tag color={item.status ? 'success' : 'error'}>
                                            {item.message}
                                        </Tag>
                                    </div>
                                </List.Item>
                            )}
                        />
                    </Collapse.Panel>

                    <Collapse.Panel header="Security Scan Results" key="2">
                        <List
                            size="small"
                            dataSource={[
                                {
                                    title: 'Vulnerability Check',
                                    ...results.vulnerabilities
                                },
                                {
                                    title: 'File Integrity',
                                    ...results.file_integrity
                                },
                                {
                                    title: 'Malware Scan',
                                    ...results.malware_scan
                                }
                            ]}
                            renderItem={item => (
                                <List.Item>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                                        <span>{item.title}</span>
                                        <Tag color={item.status ? 'success' : 'error'}>
                                            {item.message}
                                        </Tag>
                                    </div>
                                </List.Item>
                            )}
                        />
                    </Collapse.Panel>


                </Collapse>

                {results.malware_scan.detected_patterns.length > 0 && (
                    <Alert
                        message="Security Warning"
                        description="Suspicious code patterns were detected. Please review the plugin code carefully."
                        type="error"
                        showIcon
                        style={{ marginTop: 16 }}
                    />
                )}
            </div>
        );
    };

    const fetchPluginsList = async () => {
        try {
            setLoading(true);
            setError(null);
            const data = await fetchPlugins();
            setPlugins(data);
            updateStats(data);
        } catch (err) {
            console.error('Error fetching plugins:', err);
            setError('Failed to load plugins list');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchPluginsList();
    }, []);

    const getStatusBadge = (status) => {
        const config = {
            active: {
                color: '#52c41a', // Green
                icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
                text: 'Active'
            },
            inactive: {
                color: '#ff4d4f', // Red
                icon: <WarningOutlined style={{ color: '#ff4d4f' }} />,
                text: 'Inactive'
            }
        };
        const { color, icon, text } = config[status] || config.inactive;

        return (
            <Tag style={{
                color: color,
                borderColor: color,
                backgroundColor: `${color}10`
            }}>
                {icon}
                <span className="ml-1">{text}</span>
            </Tag>
        );
    };

    const getSecurityBadge = (status) => {
        const config = {
            safe: {
                icon: <SafetyCertificateOutlined />,
                color: 'success',
                text: 'Secure'
            },
            vulnerable: {
                icon: <ExclamationCircleOutlined />,
                color: 'error',
                text: 'Vulnerable'
            }
        };
        const { icon, color, text } = config[status] || config.vulnerable;

        return (
            <Tooltip title={`Security Status: ${status}`}>
                <Badge
                    status={color}
                    text={<Space>{icon}{text}</Space>}
                />
            </Tooltip>
        );
    };

    // Add a top info alert
    const renderInfoAlert = () => (
        <Alert
            type="info"
            showIcon
            message={<b>Protect your plugins to detect any unauthorized changes.</b>}
            description={<span>Click <b>Protect</b> to save a secure fingerprint of all plugin files. If a file changes, you’ll know instantly. <a href="https://en.wikipedia.org/wiki/Code_signing" target="_blank" rel="noopener noreferrer">Learn more</a>.</span>}
            style={{ marginBottom: 20, fontSize: 16 }}
        />
    );

    // Add a badge/tag for signed status
    const getSignedBadge = (plugin) => {
        if (plugin.signed) {
            return (
                <Tooltip title="This plugin is protected. If any file changes, you’ll be alerted.">
                    <Tag color="green" icon={<SafetyCertificateOutlined />}>Protected</Tag>
                </Tooltip>
            );
        } else {
            return (
                <Tooltip title="This plugin is not yet protected. Click 'Protect' to enable file change detection.">
                    <Tag color="warning">Not Protected</Tag>
                </Tooltip>
            );
        }
    };

    const renderStats = () => (
        <Row gutter={16} className="mb-6">
            <Col span={6}>
                <Card size="small" bordered={false} style={{ backgroundColor: '#f6ffed' }}>
                    <Statistic
                        title={<Text strong>Total Plugins</Text>}
                        value={stats.total}
                        prefix={<AppstoreOutlined style={{ color: '#52c41a' }} />}
                        valueStyle={{ color: '#52c41a' }}
                    />
                </Card>
            </Col>
            <Col span={6}>
                <Card size="small" bordered={false} style={{ backgroundColor: '#f6ffed' }}>
                    <Statistic
                        title={<Text strong>Active Plugins</Text>}
                        value={stats.active}
                        prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                        valueStyle={{ color: '#52c41a' }}
                    />
                </Card>
            </Col>

            <Col span={6}>
                <Card size="small" bordered={false} style={{ backgroundColor: stats.secure === stats.total ? '#f6ffed' : '#fff1f0' }}>
                    <Statistic
                        title={<Text strong>Secure Plugins</Text>}
                        value={`${stats.secure}/${stats.total}`}
                        prefix={<SafetyCertificateOutlined style={{
                            color: stats.secure === stats.total ? '#52c41a' : '#ff4d4f'
                        }} />}
                        valueStyle={{
                            color: stats.secure === stats.total ? '#52c41a' : '#ff4d4f'
                        }}
                    />
                </Card>
            </Col>
        </Row>
    );

    const renderModernView = () => (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {plugins.map((plugin) => (
                <Card
                    key={plugin.id}
                    hoverable
                    className="h-full shadow-md"
                    loading={updatingPlugins[plugin.id]}
                    title={
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
                            <Text strong style={{ fontSize: 16, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={plugin.name}>
                                {plugin.name}
                            </Text>
                            {getStatusBadge(plugin.status)}
                        </div>
                    }
                    styles={{ body: { display: 'flex', flexDirection: 'column', height: '100%' } }}
                >
                    <div >
                        <div style={{ marginBottom: 16 }}>
                            <Text type="secondary" className="line-clamp-2" style={{ height: 44, display: 'block' }}>
                                {plugin.description || 'No description available.'}
                            </Text>
                        </div>

                        <Divider style={{ margin: '12px 0' }} orientation="left" plain><Text type="secondary" style={{ fontSize: 12 }}>SECURITY</Text></Divider>

                        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
                            <Tooltip title={plugin.signed ? "Plugin is protected. Click to re-scan." : "Protect this plugin against tampering."}>
                                <Button
                                    icon={<SafetyCertificateOutlined />}
                                    type="primary"
                                    onClick={() => handleSignPlugin(plugin)}
                                    loading={updatingPlugins[plugin.id]}
                                    style={{ flex: 1, backgroundColor: plugin.signed ? undefined : '#1890ff' }}
                                    ghost={plugin.signed}
                                >
                                    {plugin.signed ? 'Re-protect' : 'Protect'}
                                </Button>
                            </Tooltip>

                            <Tooltip title="View File Changes">
                                <Button
                                    icon={<FileSearchOutlined />}
                                    onClick={() => handleViewSignedFiles(plugin)}
                                    disabled={!plugin.signed}
                                />
                            </Tooltip>

                            <Tooltip title="View History">
                                <Button
                                    icon={<HistoryOutlined />}
                                    onClick={() => handleViewHistory(plugin)}
                                    disabled={!plugin.signed}
                                />
                            </Tooltip>
                        </div>

                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            {plugin.signed ? (
                                <Tag color="success" icon={<CheckCircleOutlined />}>Safe</Tag>
                            ) : (
                                <Tag color="warning" icon={<ExclamationCircleOutlined />}>Unprotected</Tag>
                            )}
                        </div>
                    </div>

                    <Divider style={{ margin: '16px 0 12px 0' }} />

                    <div style={{ display: 'flex', gap: 10, justifyContent: 'space-between' }}>
                        {plugin.status === 'active' ? (
                            <Button
                                danger
                                type="dashed"
                                block
                                onClick={() => handlePluginAction(plugin.id, 'deactivate')}
                                loading={updatingPlugins[plugin.id]}
                            >
                                Deactivate
                            </Button>
                        ) : (
                            <Button
                                type="primary"
                                block
                                style={{ backgroundColor: '#52c41a', borderColor: '#52c41a' }}
                                onClick={() => handlePluginAction(plugin.id, 'activate')}
                                loading={updatingPlugins[plugin.id]}
                            >
                                Activate
                            </Button>
                        )}

                        {plugin.status === 'inactive' && (
                            <Popconfirm
                                title="Delete Plugin"
                                description="Are you sure? This cannot be undone."
                                onConfirm={() => handlePluginAction(plugin.id, 'delete')}
                                okText="Yes, Delete"
                                okButtonProps={{ danger: true }}
                                cancelText="Cancel"
                            >
                                <Button danger type="dashed" icon={<DeleteOutlined />} loading={updatingPlugins[plugin.id]} />
                            </Popconfirm>
                        )}
                    </div>
                </Card>
            ))}
        </div>
    );

    const renderClassicView = () => (
        <Card className="shadow-sm" styles={{ body: { padding: 0 } }}>
            <Table
                dataSource={plugins}
                rowKey="id"
                pagination={false}
                columns={[
                    {
                        title: 'Plugin',
                        dataIndex: 'name',
                        key: 'name',
                        width: '30%',
                        render: (text, record) => (
                            <div>
                                <Text strong>{text}</Text>
                                <div style={{ fontSize: 12, color: '#888', maxWidth: 300 }} className="line-clamp-1">
                                    {record.description}
                                </div>
                            </div>
                        )
                    },
                    {
                        title: 'Status',
                        key: 'status',
                        width: '15%',
                        render: (_, record) => getStatusBadge(record.status)
                    },
                    {
                        title: 'Security',
                        key: 'security',
                        width: '25%',
                        render: (_, record) => (
                            <Space>
                                {record.signed ? (
                                    <Tag color="success" icon={<CheckCircleOutlined />}>Protected</Tag>
                                ) : (
                                    <Tag color="warning">Unprotected</Tag>
                                )}
                                {record.signed && (
                                    <Tooltip title="View History">
                                        <Button size="small" icon={<HistoryOutlined />} onClick={() => handleViewHistory(record)} />
                                    </Tooltip>
                                )}
                            </Space>
                        )
                    },
                    {
                        title: 'Actions',
                        key: 'actions',
                        render: (_, record) => (
                            <Space>
                                <Tooltip title={record.signed ? "Re-protect" : "Protect Now"}>
                                    <Button
                                        type="primary"
                                        size="small"
                                        ghost={record.signed}
                                        icon={<SafetyCertificateOutlined />}
                                        onClick={() => handleSignPlugin(record)}
                                        loading={updatingPlugins[record.id]}
                                    />
                                </Tooltip>

                                {record.status === 'active' ? (
                                    <Button
                                        size="small"
                                        danger
                                        onClick={() => handlePluginAction(record.id, 'deactivate')}
                                        loading={updatingPlugins[record.id]}
                                    >
                                        Deactivate
                                    </Button>
                                ) : (
                                    <Button
                                        size="small"
                                        type="primary"
                                        style={{ backgroundColor: '#52c41a', borderColor: '#52c41a' }}
                                        onClick={() => handlePluginAction(record.id, 'activate')}
                                        loading={updatingPlugins[record.id]}
                                    >
                                        Activate
                                    </Button>
                                )}

                                {record.status === 'inactive' && (
                                    <Popconfirm
                                        title="Delete Plugin?"
                                        onConfirm={() => handlePluginAction(record.id, 'delete')}
                                        okText="Delete"
                                        okButtonProps={{ danger: true }}
                                    >
                                        <Button size="small" type="text" danger icon={<DeleteOutlined />} loading={updatingPlugins[record.id]} />
                                    </Popconfirm>
                                )}
                            </Space>
                        )
                    }
                ]}
            />
        </Card>
    );

    // Sign a plugin
    const handleSignPlugin = async (plugin) => {
        setSigningPlugins(prev => ({ ...prev, [plugin.id]: true }));
        try {
            const resp = await fetch(`${window.wpApiSettings.root}safe-sites/v1/plugins/sign`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ pluginFile: plugin.id })
            });
            const data = await resp.json();
            if (!resp.ok || !data.success) throw new Error(data.message || 'Failed to sign plugin');
            message.success('Plugin signed successfully');
        } catch (err) {
            message.error(err.message);
        } finally {
            setSigningPlugins(prev => ({ ...prev, [plugin.id]: false }));
        }
    };

    // View signed files for a plugin
    const handleViewSignedFiles = async (plugin) => {
        setSignedFilesModal({
            visible: true,
            loading: true,
            plugin,
            files: [],
            error: null
        });

        try {
            // Construct the URL with proper encoding
            const url = new URL(`${window.wpApiSettings.root}safe-sites/v1/plugins/signature-status`);
            url.searchParams.append('pluginFile', plugin.id);

            const resp = await fetch(url.toString(), {
                headers: {
                    'X-WP-Nonce': window.wpApiSettings.nonce,
                    'Content-Type': 'application/json'
                }
            });

            if (!resp.ok) {
                const errorData = await resp.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP error! status: ${resp.status}`);
            }

            const data = await resp.json();

            // Ensure we have an array of files
            const files = Array.isArray(data) ? data : [];

            setSignedFilesModal({
                visible: true,
                loading: false,
                plugin,
                files,
                error: null
            });
        } catch (err) {
            console.error('Error viewing file status:', err);
            message.error(err.message);
            setSignedFilesModal(prev => ({
                ...prev,
                loading: false,
                error: err.message
            }));
        }
    };

    // History & Rollback Handlers
    const handleViewHistory = async (plugin) => {
        setHistoryModal({
            visible: true,
            loading: true,
            plugin,
            history: [],
            error: null
        });

        try {
            const url = new URL(`${window.wpApiSettings.root}safe-sites/v1/codesigner/history`);
            url.searchParams.append('slug', plugin.id.split('/')[0]); // Assuming slug is dirname

            const resp = await fetch(url.toString(), {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            });
            const data = await resp.json();

            if (resp.ok) {
                setHistoryModal({
                    visible: true,
                    loading: false,
                    plugin,
                    history: data,
                    error: null
                });
            } else {
                throw new Error(data.message || 'Failed to fetch history');
            }
        } catch (err) {
            message.error(err.message);
            setHistoryModal(prev => ({ ...prev, loading: false, error: err.message }));
        }
    };

    const handleRollback = async (plugin, timestamp) => {
        try {
            const resp = await fetch(`${window.wpApiSettings.root}safe-sites/v1/codesigner/rollback`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({
                    slug: plugin.id.split('/')[0],
                    timestamp
                })
            });
            const data = await resp.json();

            if (resp.ok && data.success) {
                message.success('Signatures restored successfully');
                setHistoryModal(prev => ({ ...prev, visible: false }));
                // Refresh status
                handleViewSignedFiles(plugin);
            } else {
                throw new Error(data.message || 'Rollback failed');
            }
        } catch (err) {
            message.error(err.message);
        }
    };

    const handleDeleteHistory = async (plugin, timestamp) => {
        try {
            const url = new URL(`${window.wpApiSettings.root}safe-sites/v1/codesigner/history`);
            url.searchParams.append('slug', plugin.id.split('/')[0]);
            url.searchParams.append('timestamp', timestamp);

            const resp = await fetch(url.toString(), {
                method: 'DELETE',
                headers: {
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            });
            const data = await resp.json();

            if (resp.ok && data.success) {
                message.success('Backup deleted successfully');
                setHistoryModal(prev => ({ ...prev, history: data.history }));
            } else {
                throw new Error(data.message || 'Failed to delete backup');
            }
        } catch (err) {
            message.error(err.message);
        }
    };

    // Diff Handler
    const handleViewDiff = async (plugin, file) => {
        setDiffModal({
            visible: true,
            loading: true,
            plugin,
            file,
            diff: null,
            error: null
        });

        try {
            const url = new URL(`${window.wpApiSettings.root}safe-sites/v1/codesigner/diff`);
            url.searchParams.append('slug', plugin.id.split('/')[0]);
            url.searchParams.append('file', file);

            const resp = await fetch(url.toString(), {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            });
            const data = await resp.json();

            if (resp.ok) {
                setDiffModal({
                    visible: true,
                    loading: false,
                    plugin,
                    file,
                    diff: data.diff,
                    error: null
                });
            } else {
                throw new Error(data.message || 'Failed to fetch diff');
            }
        } catch (err) {
            message.error(err.message);
            setDiffModal(prev => ({ ...prev, visible: false }));
        }
    };

    // Render signed files modal
    const renderSignedFilesModal = () => {
        // Sort files: Tampered first, then Missing, then Unsigned, then Verified
        const statusOrder = { 'Tampered': 0, 'Missing': 1, 'Unsigned': 2, 'Verified': 3 };
        const sortedFiles = [...(signedFilesModal.files || [])].sort((a, b) => {
            return (statusOrder[a.status] ?? 99) - (statusOrder[b.status] ?? 99);
        });

        // Count statuses for summary
        const counts = sortedFiles.reduce((acc, f) => {
            acc[f.status] = (acc[f.status] || 0) + 1;
            return acc;
        }, {});

        // Status legend
        const statusLegend = [
            {
                status: 'Tampered',
                icon: <ExclamationCircleTwoTone twoToneColor="#ff4d4f" />,
                label: 'Changed (Unexpected)',
                desc: 'File content has changed since last signing. Review or re-sign if trusted.'
            },
            {
                status: 'Missing',
                icon: <CloseCircleTwoTone twoToneColor="#faad14" />,
                label: 'Missing',
                desc: 'File was present when signed, but is now missing.'
            },
            {
                status: 'Unsigned',
                icon: <QuestionCircleTwoTone twoToneColor="#d9d9d9" />,
                label: 'Not Yet Protected',
                desc: 'File was not included in the last signing.'
            },
            {
                status: 'Verified',
                icon: <CheckCircleTwoTone twoToneColor="#52c41a" />,
                label: 'Safe',
                desc: 'File is unchanged and safe.'
            }
        ];

        // User-friendly status rendering
        const renderStatus = (status) => {
            const legend = statusLegend.find(l => l.status === status);
            return legend ? (
                <Tooltip title={legend.desc} placement="top">
                    <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        {legend.icon}
                        <span style={{ fontWeight: 500 }}>{legend.label}</span>
                    </span>
                </Tooltip>
            ) : status;
        };

        // Row class for highlighting
        const rowClassName = (record) => {
            if (record.status === 'Tampered') return 'row-tampered';
            if (record.status === 'Missing') return 'row-missing';
            if (record.status === 'Unsigned') return 'row-unsigned';
            return '';
        };

        // Summary bar with border and spacing
        const summaryBar = (
            <div style={{ display: 'flex', alignItems: 'center', gap: 32, marginBottom: 20, flexWrap: 'wrap', border: '1px solid #e8e8e8', borderRadius: 8, padding: '12px 20px', background: '#fafbfc' }}>
                {statusLegend.map(l => (
                    <span key={l.status} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 17 }}>
                        {l.icon}
                        <span style={{ fontWeight: 600 }}>{l.label}:</span>
                        <span style={{ fontWeight: 600 }}>{counts[l.status] || 0}</span>
                    </span>
                ))}
            </div>
        );

        // Guidance message
        let guidance = null;
        if (counts['Tampered'] > 0 || counts['Missing'] > 0) {
            guidance = (
                <Alert
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message={<b>Attention Needed</b>}
                    description={
                        <span>
                            Some files have changed or are missing. If you trust these changes, click <b>Re-sign</b> for this plugin. Otherwise, review the files for possible issues.
                        </span>
                    }
                />
            );
        } else if (counts['Verified'] > 0 && !counts['Tampered'] && !counts['Missing']) {
            guidance = (
                <Alert
                    type="success"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message={<b>All files are safe!</b>}
                    description="All signed files are unchanged and verified."
                />
            );
        }

        const columns = [
            {
                title: 'File',
                dataIndex: 'file',
                key: 'file',
                render: text => <Text code style={{ wordBreak: 'break-all', whiteSpace: 'normal' }}>{text}</Text>,
                width: '50%'
            },
            {
                title: 'Status',
                key: 'status',
                render: (_, record) => (
                    renderStatus(record.status)
                )
            },
            {
                title: 'Last Verified',
                dataIndex: 'lastVerified',
                key: 'lastVerified',
            },
            {
                title: 'Action',
                key: 'action',
                render: (_, record) => {
                    if (record.status === 'Tampered') {
                        return (
                            <Button
                                type="link"
                                size="small"
                                icon={<DiffOutlined />}
                                onClick={() => handleViewDiff(signedFilesModal.plugin, record.file)}
                            >
                                View Changes
                            </Button>
                        );
                    }
                    return null;
                }
            }
        ];

        return (
            <Modal
                title={
                    <Space>
                        <FolderOpenOutlined style={{ color: '#1890ff' }} />
                        <span>Signed Files for {signedFilesModal.plugin?.name}</span>
                        <Tooltip title="This table shows the status of each file in the plugin. If you see any changes you don't trust, investigate before re-signing."><InfoCircleOutlined style={{ color: '#888' }} /></Tooltip>
                    </Space>
                }
                open={signedFilesModal.visible}
                onCancel={() => setSignedFilesModal({ ...signedFilesModal, visible: false })}
                footer={null}
                width={1000}
                styles={{ body: { padding: 24 } }}
            >
                {summaryBar}
                {guidance}

                <Table
                    dataSource={sortedFiles}
                    columns={columns}
                    pagination={{ pageSize: 10 }}
                    rowClassName={rowClassName}
                    rowKey="file"
                    size="small"
                    scroll={{ x: 800 }}
                />
            </Modal>
        );
    };


    return (
        <Layout>
            <Card className="shadow-sm">
                <Space direction="vertical" className="w-full">
                    <div className="flex justify-between items-center mb-4">
                        <Title level={4} style={{ margin: 0 }}>Installed Plugins</Title>
                        <Space>
                            <Text type="secondary">View:</Text>
                            <Segmented
                                value={viewMode}
                                onChange={setViewMode}
                                options={[
                                    {
                                        value: 'modern',
                                        icon: <AppstoreOutlined />,
                                        label: 'Modern'
                                    },
                                    {
                                        value: 'classic',
                                        icon: <UnorderedListOutlined />,
                                        label: 'Classic'
                                    }
                                ]}
                            />
                        </Space>
                    </div>

                    {renderInfoAlert()}
                    {!loading && !error && renderStats()}

                    {loading ? (
                        <>
                            <Skeleton active />
                            <Skeleton active />
                            <Skeleton active />
                        </>
                    ) : error ? (
                        <Alert
                            message="Error Loading Plugins"
                            description={error}
                            type="error"
                            showIcon
                            action={
                                <Button size="small" danger onClick={fetchPluginsList}>
                                    Try Again
                                </Button>
                            }
                        />
                    ) : plugins.length > 0 ? (
                        viewMode === 'modern' ? renderModernView() : renderClassicView()
                    ) : (
                        <Empty
                            description="No plugins found"
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                        />
                    )}
                </Space>
            </Card>

            <Modal
                title={
                    <Space>
                        <SafetyCertificateOutlined style={{ color: '#1890ff' }} />
                        <span>Plugin Safety Check</span>
                    </Space>
                }
                open={safetyCheckModal.visible}
                onCancel={() => setSafetyCheckModal(prev => ({ ...prev, visible: false }))}
                footer={null}
                width={800}
            >
                {safetyCheckModal.loading ? (
                    <div className="text-center p-4">
                        <Spin size="large" />
                        <div className="mt-4">
                            <Text>Performing safety checks...</Text>
                        </div>
                    </div>
                ) : safetyCheckModal.error ? (
                    <Alert
                        message="Error Checking Plugin Safety"
                        description={safetyCheckModal.error}
                        type="error"
                        showIcon
                    />
                ) : (
                    renderSafetyResults(safetyCheckModal.results)
                )}
            </Modal>
            {renderSignedFilesModal()}
            {renderHistoryModal()}
            {renderDiffModal()}
            {/* Add custom row highlight styles */}
            <style>{`
                .row-tampered td { background: #fff1f0 !important; }
                .row-missing td { background: #fffbe6 !important; }
                .row-unsigned td { background: #f5f5f5 !important; }
            `}</style>
        </Layout>
    );
};

export default PluginManager;
