import React, { useState, useEffect } from 'react';
import {
    Card,
    Row,
    Col,
    Button,
    Typography,
    Space,
    Alert,
    Modal,
    Statistic,
    Skeleton,
    Badge,
    Progress,
    Tooltip,
    Timeline,
    Empty,
    Spin,
    Tag,
    Switch
} from 'antd';
import {
    LockOutlined,
    UnlockOutlined,
    CloudUploadOutlined,
    SecurityScanOutlined,
    CodeOutlined,
    SyncOutlined,
    CheckCircleOutlined,
    ExclamationCircleOutlined,
    InfoCircleOutlined,
    SafetyCertificateOutlined,
    BugOutlined,
    ApiOutlined,
    HeartOutlined,
    AlertOutlined
} from '@ant-design/icons';
import Layout from '../layout/Layout';
import HardeningSettings from '../settings/HardeningSettings';
import WebhookSettings from '../settings/WebhookSettings';

const { Title, Text, Paragraph } = Typography;

// Custom styles
const styles = {
    dashboardContainer: {
        padding: '24px',
        background: '#fff',
        minHeight: 'calc(100vh - 64px)'
    },
    pageTitle: {
        marginBottom: '24px',
        color: '#2c3e50',
        borderBottom: '1px solid #eee',
        paddingBottom: '12px',
        fontSize: '20px',
        fontWeight: '500'
    },
    card: {
        height: '100%',
        border: '1px solid #e8e8e8',
        transition: 'all 0.3s ease'
    },
    cardTitle: {
        color: '#2c3e50',
        fontSize: '16px',
        fontWeight: '500',
        marginBottom: '0'
    },
    statTitle: {
        fontSize: '14px',
        color: '#666',
        marginBottom: '8px'
    },
    statValue: {
        fontSize: '20px',
        fontWeight: '500'
    },
    button: {
        marginTop: '16px',
        width: '100%',
        height: '32px'
    },
    tag: {
        padding: '4px 8px',
        fontSize: '12px'
    },
    alertMessage: {
        fontSize: '14px',
        fontWeight: '500'
    },
    alertDescription: {
        fontSize: '13px'
    }
};

const Dashboard = () => {
    const [systemStatus, setSystemStatus] = useState(null);
    const [loading, setLoading] = useState(true);
    const [actionInProgress, setActionInProgress] = useState(false);
    const [panicEnabled, setPanicEnabled] = useState(false);
    const [panicLoading, setPanicLoading] = useState(false);

    // Defensive check for wpApiSettings
    if (!window.wpApiSettings || !window.wpApiSettings.root) {
        console.error('wpApiSettings or root is not defined!');
        // Optionally, you could render a user-friendly error message here
    }

    useEffect(() => {
        fetchSystemStatus();
        fetchPanicStatus();
    }, []);

    const fetchPanicStatus = async () => {
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/security-features/panic-mode`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            });
            const data = await response.json();
            setPanicEnabled(data.enabled);
        } catch (error) {
            console.error('Error fetching panic status:', error);
        }
    };

    const handlePanicToggle = async () => {
        if (!panicEnabled) {
            // Confirm before enabling
            Modal.confirm({
                title: 'Enable Panic Mode?',
                icon: <AlertOutlined style={{ color: 'red' }} />,
                content: 'This will lock down your site. Only administrators will be able to access it. A "Service Unavailable" page will be shown to visitors.',
                okText: 'Yes, Lock Down Site',
                okType: 'danger',
                onOk: executePanicToggle
            });
        } else {
            executePanicToggle();
        }
    };

    const executePanicToggle = async () => {
        setPanicLoading(true);
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/security-features/panic-mode`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ enabled: !panicEnabled })
            });
            const data = await response.json();
            if (data.success) {
                setPanicEnabled(data.enabled);
                message.success(data.message);
            }
        } catch (error) {
            message.error('Failed to toggle Panic Mode');
        } finally {
            setPanicLoading(false);
        }
    };


    const fetchSystemStatus = async () => {
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/system/status`, {
                headers: {
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            });
            const result = await response.json();
            if (result.success) {
                console.log('System Status:', result.data); // Debug log
                setSystemStatus(result.data);
            }
        } catch (error) {
            console.error('Error fetching system status:', error);
        } finally {
            setLoading(false);
        }
    };

    const calculateOverallHealth = () => {
        if (!systemStatus) return 0;

        let score = 100;
        const checks = [
            { condition: !systemStatus.ssl?.enabled, deduction: 30 },
            { condition: systemStatus.ssl?.mixed_content, deduction: 15 },
            { condition: !systemStatus.php?.is_recommended, deduction: 20 },
            { condition: !systemStatus.php?.is_supported, deduction: 35 },
            { condition: systemStatus.wordpress?.needs_update, deduction: 25 }
        ];

        checks.forEach(check => {
            if (check.condition) score -= check.deduction;
        });

        return Math.max(0, score);
    };

    const getHealthStatus = (score) => {
        if (score >= 90) return { text: 'Excellent', color: '#52c41a' };
        if (score >= 70) return { text: 'Good', color: '#1890ff' };
        if (score >= 50) return { text: 'Fair', color: '#faad14' };
        return { text: 'Poor', color: '#ff4d4f' };
    };

    const getHealthColor = (score) => {
        if (score >= 90) return '#52c41a';
        if (score >= 70) return '#1890ff';
        if (score >= 50) return '#faad14';
        return '#ff4d4f';
    };

    const handleForceSSL = async (enable = true) => {
        try {
            setActionInProgress(true);
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/system/force-ssl`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ enable })
            });

            const data = await response.json();
            if (data.success) {
                Modal.success({
                    title: enable ? 'HTTPS Enforced' : 'HTTPS Enforcement Disabled',
                    content: data.message,
                });
                await fetchSystemStatus(); // Refresh the status after change
            } else {
                throw new Error(data.message || 'Operation failed');
            }
        } catch (error) {
            Modal.error({
                title: 'Error',
                content: error.message || `Failed to ${enable ? 'enable' : 'disable'} HTTPS enforcement. Please try again.`,
            });
        } finally {
            setActionInProgress(false);
        }
    };

    const handleWordPressUpdate = async () => {
        Modal.confirm({
            title: 'Update WordPress Core',
            icon: <ExclamationCircleOutlined />,
            content: (
                <div>
                    <Timeline items={[
                        {
                            color: 'blue',
                            children: (
                                <div>
                                    <Text strong>Pre-Update Checklist</Text>
                                    <ul className="checklist">
                                        <li>Backup your entire website</li>
                                        <li>Check plugin compatibility</li>
                                        <li>Verify theme compatibility</li>
                                        <li>Test in staging environment if possible</li>
                                    </ul>
                                </div>
                            ),
                        },
                        {
                            color: 'gold',
                            children: (
                                <div>
                                    <Text strong>During Update</Text>
                                    <ul className="checklist">
                                        <li>Do not close your browser</li>
                                        <li>Avoid making any changes</li>
                                    </ul>
                                </div>
                            ),
                        },
                        {
                            color: 'green',
                            children: (
                                <div>
                                    <Text strong>Post-Update</Text>
                                    <ul className="checklist">
                                        <li>Test core functionality</li>
                                        <li>Check for plugin/theme issues</li>
                                    </ul>
                                </div>
                            ),
                        },
                    ]} />
                    <Alert
                        message="Are you ready to proceed with the update?"
                        type="warning"
                        showIcon
                        style={{ marginTop: 16 }}
                    />
                </div>
            ),
            onOk: async () => {
                try {
                    setActionInProgress(true);
                    const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/system/update-wordpress`, {
                        method: 'POST',
                        headers: {
                            'X-WP-Nonce': window.wpApiSettings.nonce
                        }
                    });

                    const data = await response.json();
                    if (data.success) {
                        Modal.success({
                            title: 'WordPress Updated',
                            content: 'WordPress core has been successfully updated.',
                        });
                        fetchSystemStatus();
                    }
                } catch (error) {
                    Modal.error({
                        title: 'Update Failed',
                        content: 'Failed to update WordPress. Please try again or update manually.',
                    });
                } finally {
                    setActionInProgress(false);
                }
            }
        });
    };

    if (loading) {
        return (
            <Layout>
                <Row gutter={[24, 24]}>
                    <Col xs={24}>
                        <Card>
                            <Skeleton active />
                        </Card>
                    </Col>
                </Row>
            </Layout>
        );
    }

    return (
        <Layout>
            <div style={styles.dashboardContainer}>
                <Row gutter={[16, 16]}>
                    <Col xs={24} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                        <Title level={3} style={{ marginBottom: 0, borderBottom: 'none' }}>
                            System Status
                        </Title>
                        <Button
                            type={panicEnabled ? "primary" : "primary"}
                            danger={!panicEnabled}
                            icon={<AlertOutlined />}
                            onClick={handlePanicToggle}
                            loading={panicLoading}
                            style={{
                                backgroundColor: panicEnabled ? '#52c41a' : '#ff4d4f',
                                borderColor: panicEnabled ? '#52c41a' : '#ff4d4f',
                                fontWeight: 'bold'
                            }}
                        >
                            {panicEnabled ? 'Disable Panic Mode' : 'Panic Mode'}
                        </Button>
                    </Col>
                </Row>

                {/* Health Score Section */}
                <Row gutter={[16, 16]}>
                    <Col xs={24} lg={8}>
                        <Card className="dashboard-card" style={styles.card}>
                            <Statistic
                                title={<Title level={4} style={styles.cardTitle}>Overall Health</Title>}
                                value={calculateOverallHealth()}
                                suffix="%"
                                valueStyle={{
                                    color: getHealthColor(calculateOverallHealth()),
                                    ...styles.statValue,
                                    fontSize: '28px'
                                }}
                                prefix={<HeartOutlined style={{ fontSize: '20px' }} />}
                            />
                            <Progress
                                percent={calculateOverallHealth()}
                                status={getHealthStatus(calculateOverallHealth())}
                                style={{ marginTop: '16px' }}
                                size={[null, 8]}
                            />
                        </Card>
                    </Col>
                    <Col xs={24} lg={8}>
                        <Card className="dashboard-card" style={styles.card}>
                            <Statistic
                                title={<Title level={4} style={styles.cardTitle}>SSL Status</Title>}
                                value={systemStatus?.ssl?.enabled ? "Secure" : "Not Secure"}
                                valueStyle={{
                                    color: systemStatus?.ssl?.enabled ? '#27ae60' : '#c0392b',
                                    ...styles.statValue
                                }}
                                prefix={
                                    systemStatus?.ssl?.enabled ?
                                        <LockOutlined style={{ fontSize: '20px' }} /> :
                                        <UnlockOutlined style={{ fontSize: '20px' }} />
                                }
                            />
                            <Button
                                type={systemStatus?.ssl?.enabled ? "default" : "primary"}
                                icon={<SecurityScanOutlined />}
                                onClick={() => handleForceSSL(!systemStatus?.ssl?.enabled)}
                                loading={actionInProgress}
                                style={styles.button}
                            >
                                {systemStatus?.ssl?.enabled ? 'Disable HTTPS' : 'Enable HTTPS'}
                            </Button>
                        </Card>
                    </Col>
                    <Col xs={24} lg={8}>
                        <Card className="dashboard-card" style={styles.card}>
                            <Statistic
                                title={<Title level={4} style={styles.cardTitle}>WordPress Version</Title>}
                                value={systemStatus?.wordpress?.current_version || 'N/A'}
                                valueStyle={{
                                    ...styles.statValue,
                                    color: '#2c3e50'
                                }}
                                prefix={<CodeOutlined style={{ fontSize: '20px' }} />}
                            />
                            {systemStatus?.wordpress?.needs_update && (
                                <Button
                                    type="primary"
                                    icon={<SyncOutlined />}
                                    onClick={handleWordPressUpdate}
                                    loading={actionInProgress}
                                    style={styles.button}
                                >
                                    Update to {systemStatus?.wordpress?.latest_version}
                                </Button>
                            )}
                        </Card>
                    </Col>
                </Row>

                {/* System Details Section */}
                <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                    <Col xs={24} lg={12}>
                        <Card className="dashboard-card" title={<span style={styles.cardTitle}>PHP Information</span>} style={styles.card}>
                            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                                <Statistic
                                    title={<span style={styles.statTitle}>Current Version</span>}
                                    value={systemStatus?.php?.current_version || 'N/A'}
                                    valueStyle={styles.statValue}
                                    prefix={<ApiOutlined style={{ fontSize: '16px' }} />}
                                />
                                <Statistic
                                    title={<span style={styles.statTitle}>Recommended Version</span>}
                                    value={systemStatus?.php?.recommended_version || 'N/A'}
                                    valueStyle={styles.statValue}
                                    prefix={<ApiOutlined style={{ fontSize: '16px' }} />}
                                />
                                <Tag color={systemStatus?.php?.is_recommended ? 'success' : 'warning'} style={styles.tag}>
                                    {systemStatus?.php?.is_recommended ? 'Recommended Version' : 'Update Recommended'}
                                </Tag>
                            </Space>
                        </Card>
                    </Col>
                    <Col xs={24} lg={12}>
                        <Card className="dashboard-card" title={<span style={styles.cardTitle}>Server Information</span>} style={styles.card}>
                            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                                <Statistic
                                    title={<span style={styles.statTitle}>Server Software</span>}
                                    value={systemStatus?.server?.software || 'N/A'}
                                    valueStyle={styles.statValue}
                                    prefix={<ApiOutlined style={{ fontSize: '16px' }} />}
                                />
                                <Statistic
                                    title={<span style={styles.statTitle}>Operating System</span>}
                                    value={systemStatus?.server?.operating_system || 'N/A'}
                                    valueStyle={styles.statValue}
                                    prefix={<ApiOutlined style={{ fontSize: '16px' }} />}
                                />
                                <Statistic
                                    title={<span style={styles.statTitle}>PHP Memory Limit</span>}
                                    value={systemStatus?.server?.memory_limit || 'N/A'}
                                    valueStyle={styles.statValue}
                                    prefix={<ApiOutlined style={{ fontSize: '16px' }} />}
                                />
                            </Space>
                        </Card>
                    </Col>
                </Row>

                {/* Alerts Section */}
                <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                    <Col xs={24}>
                        <Card className="dashboard-card" title={<span style={styles.cardTitle}>System Alerts</span>} style={{ border: '1px solid #e8e8e8' }}>
                            <Space direction="vertical" size="small" style={{ width: '100%' }}>
                                {systemStatus?.ssl?.mixed_content && (
                                    <Alert
                                        message={<span style={styles.alertMessage}>Mixed Content Detected</span>}
                                        description={<span style={styles.alertDescription}>Your site contains mixed content which may affect security and SSL status.</span>}
                                        type="warning"
                                        showIcon
                                    />
                                )}
                                {systemStatus?.php?.is_supported === false && (
                                    <Alert
                                        message={<span style={styles.alertMessage}>PHP Version Alert</span>}
                                        description={<span style={styles.alertDescription}>Your PHP version is no longer supported. Please upgrade to a supported version.</span>}
                                        type="error"
                                        showIcon
                                    />
                                )}
                                {systemStatus?.php?.is_recommended === false && (
                                    <Alert
                                        message={<span style={styles.alertMessage}>PHP Version Notice</span>}
                                        description={<span style={styles.alertDescription}>Your PHP version is not recommended. Consider upgrading to the latest version.</span>}
                                        type="warning"
                                        showIcon
                                    />
                                )}
                                {systemStatus?.ssl?.enabled === false && (
                                    <Alert
                                        message={<span style={styles.alertMessage}>SSL Not Enabled</span>}
                                        description={<span style={styles.alertDescription}>Your site is not using HTTPS. Enable SSL to secure your website.</span>}
                                        type="warning"
                                        showIcon
                                    />
                                )}
                            </Space>
                        </Card>
                    </Col>
                </Row>

                {/* New Security Features Section */}
                <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
                    <Col xs={24} lg={12}>
                        <HardeningSettings />
                    </Col>
                    <Col xs={24} lg={12}>
                        <WebhookSettings />
                    </Col>
                </Row>
            </div>
        </Layout>
    );
};

export default Dashboard;