import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Progress, Tree, Button, Space, Badge, Typography, Tooltip, message, Statistic, Table, Tabs } from 'antd';
import {
    FileOutlined,
    FolderOutlined,
    SafetyCertificateOutlined,
    WarningOutlined,
    CheckCircleOutlined,
    SyncOutlined,
    LockOutlined,
    SecurityScanOutlined,
    TableOutlined,
    ApartmentOutlined
} from '@ant-design/icons';
import apiFetch from '@wordpress/api-fetch';
import Layout from '../layout/Layout';

const { Title, Text, Paragraph } = Typography;
const { DirectoryTree } = Tree;

const riskLevelColors = {
    secure: '#52c41a',    // Green
    low: '#95de64',       // Light Green
    moderate: '#faad14',  // Yellow
    high: '#ff4d4f',      // Red
    critical: '#cf1322',  // Dark Red
    error: '#595959'      // Gray
};

const badgeIcons = {
    platinum: '🏆',
    gold: '🥇',
    silver: '🥈',
    bronze: '🥉',
    none: '🔒'
};

const FilePermissions = () => {
    const [scanResults, setScanResults] = useState(null);
    const [loading, setLoading] = useState(false);
    const [selectedFile, setSelectedFile] = useState(null);
    const [treeData, setTreeData] = useState([]);
    const [loadingFix, setLoadingFix] = useState(false);
    const [activeTab, setActiveTab] = useState('1');

    const columns = [
        {
            title: 'File Name',
            dataIndex: 'path',
            key: 'path',
            render: (text, record) => (
                <Space>
                    {record.is_directory ? <FolderOutlined /> : <FileOutlined />}
                    {text}
                </Space>
            )
        },
        {
            title: 'Current Permission',
            dataIndex: 'current_perms_display',
            key: 'current_perms',
            render: (text, record) => (
                <Tooltip title={`${record.message} (${record.current_perms})`}>
                    <Text>{text}</Text>
                </Tooltip>
            )
        },
        {
            title: 'Recommended',
            dataIndex: 'recommended_perms_display',
            key: 'recommended_perms'
        },
        {
            title: 'Status',
            key: 'status',
            render: (_, record) => (
                <Badge
                    status={getBadgeStatus(record.level)}
                    text={record.message}
                    style={{ color: riskLevelColors[record.level] }}
                />
            )
        },
        {
            title: 'Last Modified',
            dataIndex: 'last_modified',
            key: 'last_modified',
            render: (text, record) => (
                <Tooltip title={`Modified by: ${record.last_modified_by}`}>
                    <Text>{text}</Text>
                </Tooltip>
            )
        },
        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                record.can_modify && (
                    <Button
                        type="primary"
                        size="small"
                        icon={<LockOutlined />}
                        onClick={() => handleFixPermissions(record.path)}
                        loading={loadingFix}
                    >
                        Fix Now
                    </Button>
                )
            )
        }
    ];

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

    const performScan = async () => {
        setLoading(true);
        setScanResults(null);
        try {
            const response = await apiFetch({
                path: '/safe-sites/v1/security/scan-permissions',
                method: 'GET'
            });

            setScanResults(response);
            generateTreeData(response.scan_results);
            message.success('File permissions scan completed');
        } catch (error) {
            message.error('Failed to scan file permissions');
            console.error('Scan error:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFixPermissions = async (path) => {
        setLoadingFix(true);
        try {
            const response = await apiFetch({
                path: '/safe-sites/v1/security/fix-permissions',
                method: 'POST',
                data: { path }
            });

            if (response.success) {
                message.success('Permissions fixed successfully');
                performScan();
            } else {
                message.error(response.message || 'Failed to fix permissions');
            }
        } catch (error) {
            message.error('Failed to fix permissions');
            console.error('Fix error:', error);
        } finally {
            setLoadingFix(false);
        }
    };

    const generateTreeData = (results) => {
        const tree = [];
        results.forEach(result => {
            const pathParts = result.path.split('/');
            let currentLevel = tree;

            pathParts.forEach((part, index) => {
                const isLast = index === pathParts.length - 1;
                const existing = currentLevel.find(node => node.key === part);

                if (!existing) {
                    const newNode = {
                        title: (
                            <Tooltip title={
                                <div>
                                    <p><strong>Current:</strong> {result.current_perms_display}</p>
                                    <p><strong>Recommended:</strong> {result.recommended_perms_display}</p>
                                    <p><strong>Last Modified:</strong> {result.last_modified}</p>
                                    <p><strong>Status:</strong> {result.message}</p>
                                </div>
                            }>
                                <Space>
                                    <Text>{part}</Text>
                                    {isLast && (
                                        <Badge
                                            status={getBadgeStatus(result.level)}
                                            text={`${result.score}%`}
                                            style={{
                                                color: riskLevelColors[result.level],
                                                backgroundColor: `${riskLevelColors[result.level]}15`,
                                                padding: '2px 8px',
                                                borderRadius: '12px'
                                            }}
                                        />
                                    )}
                                </Space>
                            </Tooltip>
                        ),
                        key: part,
                        isLeaf: isLast && !result.is_directory,
                        icon: isLast ? (
                            result.is_directory ?
                                <FolderOutlined style={{ color: riskLevelColors[result.level] }} /> :
                                <FileOutlined style={{ color: riskLevelColors[result.level] }} />
                        ) : null,
                        data: isLast ? result : null,
                        children: isLast ? null : []
                    };
                    currentLevel.push(newNode);
                    currentLevel = newNode.children;
                } else {
                    currentLevel = existing.children;
                }
            });
        });
        setTreeData(tree);
    };

    const getBadgeStatus = (level) => {
        switch (level) {
            case 'secure': return 'success';
            case 'low': return 'processing';
            case 'moderate': return 'warning';
            case 'high': case 'critical': return 'error';
            default: return 'default';
        }
    };

    const onSelect = (selectedKeys, info) => {
        setSelectedFile(info.node.data);
    };

    const items = [
        {
            key: '1',
            label: (
                <Space>
                    <ApartmentOutlined />
                    Tree View
                </Space>
            ),
            children: (
                <DirectoryTree
                    treeData={treeData}
                    onSelect={onSelect}
                    defaultExpandAll
                    style={{ background: '#fff', padding: '12px', borderRadius: '8px' }}
                />
            )
        },
        {
            key: '2',
            label: (
                <Space>
                    <TableOutlined />
                    Table View
                </Space>
            ),
            children: (
                <Table
                    dataSource={scanResults?.scan_results || []}
                    columns={columns}
                    rowKey="path"
                    size="middle"
                    pagination={{ pageSize: 10 }}
                    onRow={(record) => ({
                        onClick: () => setSelectedFile(record)
                    })}
                />
            )
        }
    ];

    return (
        <Layout>
            <div className="page-header" style={{ marginBottom: '24px' }}>
                <Row gutter={[16, 16]} align="middle" justify="space-between">
                    <Col>
                        <Space direction="vertical" size={0}>
                            <Title level={2} style={{ marginBottom: '8px' }}>
                                <SecurityScanOutlined /> File Permissions Scanner
                            </Title>
                            <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                                Monitor and manage file permissions to enhance your website's security
                            </Paragraph>
                        </Space>
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            icon={<SyncOutlined spin={loading} />}
                            onClick={performScan}
                            loading={loading}
                            size="large"
                            style={{
                                background: '#2271b1',
                                borderColor: '#2271b1',
                            }}
                            className="hover:bg-[#135e96] hover:border-[#135e96] transition-all duration-300"
                        >
                            {loading ? 'Scanning...' : 'Scan Now'}
                        </Button>
                    </Col>
                </Row>
            </div>

            <Row gutter={[16, 16]}>
                <Col xs={24} lg={8}>
                    <Card
                        title={<Space><SafetyCertificateOutlined /> Security Score</Space>}
                        className="dashboard-card"
                        bordered={false}
                        loading={loading}
                    >
                        <div style={{ textAlign: 'center', padding: '20px 0' }}>
                            <Progress
                                type="circle"
                                percent={scanResults?.overall_score || 0}
                                status={scanResults?.overall_score >= 90 ? 'success' : 'active'}
                                format={percent => (
                                    <div style={{ textAlign: 'center' }}>
                                        <div style={{ fontSize: '28px', fontWeight: 'bold' }}>{percent}%</div>
                                        <div style={{
                                            fontSize: '14px',
                                            color: percent >= 90 ? '#52c41a' :
                                                percent >= 70 ? '#1890ff' :
                                                    percent >= 50 ? '#faad14' : '#ff4d4f'
                                        }}>
                                            {percent >= 90 ? 'Excellent' :
                                                percent >= 70 ? 'Good' :
                                                    percent >= 50 ? 'Fair' : 'Poor'}
                                        </div>
                                    </div>
                                )}
                            />
                        </div>
                        {scanResults?.badge_earned && (
                            <div style={{
                                textAlign: 'center',
                                marginTop: '16px',
                                animation: 'fadeIn 0.5s ease-in-out'
                            }}>
                                <Badge
                                    count={badgeIcons[scanResults.badge_type]}
                                    style={{
                                        backgroundColor: '#52c41a',
                                        transition: 'all 0.3s ease'
                                    }}
                                >
                                    <Text strong>Security Badge Earned!</Text>
                                </Badge>
                            </div>
                        )}
                    </Card>

                    <Card
                        title={<Space><WarningOutlined /> Risk Distribution</Space>}
                        className="dashboard-card"
                        bordered={false}
                        style={{ marginTop: '16px' }}
                        loading={loading}
                    >
                        {scanResults?.scan_results && (
                            <Space direction="vertical" style={{ width: '100%' }}>
                                {Object.entries(
                                    scanResults.scan_results.reduce((acc, result) => {
                                        acc[result.level] = (acc[result.level] || 0) + 1;
                                        return acc;
                                    }, {})
                                ).map(([level, count], index) => (
                                    <Card
                                        key={level}
                                        size="small"
                                        bordered={false}
                                        style={{
                                            background: '#fafafa',
                                            animation: `slideIn 0.3s ease-out ${index * 0.1}s`,
                                            borderRadius: '8px'
                                        }}
                                    >
                                        <Statistic
                                            title={
                                                <Space>
                                                    {level === 'secure' ? <CheckCircleOutlined /> : <WarningOutlined />}
                                                    {level.charAt(0).toUpperCase() + level.slice(1)}
                                                </Space>
                                            }
                                            value={count}
                                            valueStyle={{
                                                color: riskLevelColors[level],
                                                fontSize: '20px'
                                            }}
                                        />
                                    </Card>
                                ))}
                            </Space>
                        )}
                    </Card>
                </Col>

                <Col xs={24} lg={16}>
                    <Card
                        title={<Space><FolderOutlined /> File Explorer</Space>}
                        className="dashboard-card"
                        bordered={false}
                        loading={loading}
                        extra={
                            selectedFile?.can_modify && (
                                <Button
                                    type="primary"
                                    icon={<LockOutlined />}
                                    onClick={() => handleFixPermissions(selectedFile.path)}
                                    loading={loadingFix}
                                    size="small"
                                    style={{
                                        background: '#2271b1',
                                        borderColor: '#2271b1',
                                    }}
                                    className="hover:bg-[#135e96] hover:border-[#135e96] transition-all duration-300"
                                >
                                    Fix Now
                                </Button>
                            )
                        }
                    >
                        <Tabs
                            activeKey={activeTab}
                            onChange={setActiveTab}
                            items={items}
                            className="custom-tabs"
                        />

                        {selectedFile && (
                            <div style={{
                                marginTop: '16px',
                                padding: '16px',
                                background: '#fafafa',
                                borderRadius: '8px',
                                border: '1px solid #f0f0f0',
                                animation: 'slideUp 0.3s ease-out'
                            }}>
                                <Title level={5}>File Details</Title>
                                <Space direction="vertical" style={{ width: '100%' }}>
                                    <Row>
                                        <Col span={8}><Text type="secondary">Path:</Text></Col>
                                        <Col span={16}><Text copyable>{selectedFile.path}</Text></Col>
                                    </Row>
                                    <Row>
                                        <Col span={8}><Text type="secondary">Current Permissions:</Text></Col>
                                        <Col span={16}><Text code copyable>{selectedFile.current_perms}</Text></Col>
                                    </Row>
                                    <Row>
                                        <Col span={8}><Text type="secondary">Recommended:</Text></Col>
                                        <Col span={16}><Text code copyable>{selectedFile.recommended_perms}</Text></Col>
                                    </Row>
                                    <Row>
                                        <Col span={8}><Text type="secondary">Status:</Text></Col>
                                        <Col span={16}>
                                            <Badge
                                                status={getBadgeStatus(selectedFile.level)}
                                                text={selectedFile.message}
                                                style={{
                                                    color: riskLevelColors[selectedFile.level],
                                                    fontWeight: 500
                                                }}
                                            />
                                        </Col>
                                    </Row>
                                </Space>
                            </div>
                        )}
                    </Card>
                </Col>
            </Row>

            <style jsx global>{`
                @keyframes fadeIn {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                
                @keyframes slideIn {
                    from { 
                        opacity: 0;
                        transform: translateX(-20px);
                    }
                    to { 
                        opacity: 1;
                        transform: translateX(0);
                    }
                }
                
                @keyframes slideUp {
                    from { 
                        opacity: 0;
                        transform: translateY(20px);
                    }
                    to { 
                        opacity: 1;
                        transform: translateY(0);
                    }
                }
                
                .dashboard-card {
                    box-shadow: 0 1px 2px rgba(0,0,0,0.03);
                    transition: all 0.3s ease;
                }
                
                .dashboard-card:hover {
                    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
                }

                .custom-tabs .ant-tabs-nav {
                    margin-bottom: 16px;
                }

                .custom-tabs .ant-tabs-tab {
                    padding: 8px 16px;
                    transition: all 0.3s ease;
                }

                .custom-tabs .ant-tabs-tab:hover {
                    color: #1890ff;
                }

                .custom-tabs .ant-tabs-tab-active {
                    background: #e6f7ff;
                    border-radius: 4px;
                }

                .custom-tabs .ant-tabs-ink-bar {
                    background: #1890ff;
                    height: 3px;
                    border-radius: 3px;
                }
            `}</style>
        </Layout>
    );
};

export default FilePermissions;
