import React, { useState, useEffect } from 'react';
import {
    Card,
    Typography,
    Button,
    Steps,
    Input,
    Alert,
    Result,
    Spin,
    Row,
    Col,
    Divider,
    Space,
    Statistic,
    message,
    Modal,
    Tabs,
    Checkbox,
    Form,
    Tag
} from 'antd';
import {
    LockOutlined,
    SafetyCertificateOutlined,
    MobileOutlined,
    CheckCircleOutlined,
    CopyOutlined,
    SettingOutlined,
    InfoCircleOutlined,
    CheckCircleTwoTone,
    ExclamationCircleTwoTone
} from '@ant-design/icons';
import Layout from '../layout/Layout';

const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;

const styles = {
    container: {
        padding: '24px',
        background: '#fff',
        minHeight: 'calc(100vh - 64px)',
    },
    pageTitle: {
        marginBottom: '8px',
        color: '#2c3e50',
        fontSize: '24px',
        fontWeight: '600',
        display: 'flex',
        alignItems: 'center',
        gap: 12
    },
    subtitle: {
        color: '#888',
        marginBottom: 24
    },
    card: {
        border: '1px solid #e8e8e8',
        borderRadius: 8,
        marginBottom: 24,
        background: '#fff',
        boxShadow: '0 2px 8px #f0f1f2'
    },
    statusCard: {
        background: '#f6ffed',
        border: '1px solid #b7eb8f',
        borderRadius: 8,
        marginBottom: 24,
        padding: 24,
        display: 'flex',
        alignItems: 'center',
        gap: 24
    },
    statusIcon: {
        fontSize: 36
    }
};

const TwoFactorAuth = () => {
    const [loading, setLoading] = useState(true);
    const [status, setStatus] = useState(null);
    const [setupMode, setSetupMode] = useState(false);
    const [currentStep, setCurrentStep] = useState(0);
    const [setupData, setSetupData] = useState(null);
    const [verificationCode, setVerificationCode] = useState('');
    const [verifying, setVerifying] = useState(false);
    const [backupCodes, setBackupCodes] = useState([]);

    // Admin Settings State
    const [settingsForm] = Form.useForm();
    const [savingSettings, setSavingSettings] = useState(false);

    useEffect(() => {
        fetchStatus();
    }, []);

    const fetchStatus = async () => {
        try {
            setLoading(true);
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/2fa/status`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            });
            const data = await response.json();
            setStatus(data);
            if (data.settings && data.settings.forced_roles) {
                settingsForm.setFieldsValue({
                    forced_roles: data.settings.forced_roles
                });
            }
        } catch (error) {
            console.error('Error fetching 2FA status:', error);
            message.error('Failed to load 2FA status');
        } finally {
            setLoading(false);
        }
    };

    const startSetup = async () => {
        setSetupMode(true);
        setCurrentStep(0);
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/2fa/setup`, {
                method: 'POST',
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            });
            const data = await response.json();
            setSetupData(data);
            setCurrentStep(1);
        } catch (error) {
            message.error('Failed to start setup');
            setSetupMode(false);
        }
    };

    const verifySetup = async () => {
        if (!verificationCode) return;
        setVerifying(true);
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/2fa/verify`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({
                    code: verificationCode,
                    secret: setupData.secret
                })
            });
            const data = await response.json();

            if (data.success) {
                setBackupCodes(data.backup_codes);
                setCurrentStep(2);
                fetchStatus();
            } else {
                message.error(data.message || 'Invalid code. Please try again.');
            }
        } catch (error) {
            message.error(error.message || 'Verification failed. Please check your code.');
        } finally {
            setVerifying(false); // Ensure logic runs even on error
        }
    };

    const disable2FA = async () => {
        Modal.confirm({
            title: 'Disable Two-Factor Authentication?',
            content: 'This will make your account less secure.',
            okText: 'Disable',
            okType: 'danger',
            onOk: async () => {
                try {
                    const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/2fa/disable`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': window.wpApiSettings.nonce
                        },
                        body: JSON.stringify({ method: 'all' })
                    });
                    const data = await response.json();
                    if (data.success) {
                        message.success('2FA Disabled');
                        fetchStatus();
                    }
                } catch (error) {
                    message.error('Failed to disable 2FA');
                }
            }
        });
    };

    const saveSettings = async (values) => {
        setSavingSettings(true);
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/2fa/settings`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(values)
            });
            const data = await response.json();
            if (data.success) {
                message.success('Settings saved');
            } else {
                message.error('Failed to save settings');
            }
        } catch (error) {
            message.error('Error saving settings');
        } finally {
            setSavingSettings(false);
        }
    };

    const copyToClipboard = (text) => {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text)
                .then(() => message.success('Copied to clipboard'))
                .catch(() => fallbackCopy(text));
        } else {
            fallbackCopy(text);
        }
    };

    const fallbackCopy = (text) => {
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.position = "fixed"; // Avoid scrolling to bottom
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
            const successful = document.execCommand('copy');
            if (successful) {
                message.success('Copied to clipboard');
            } else {
                message.error('Failed to copy');
            }
        } catch (err) {
            message.error('Failed to copy');
        }
        document.body.removeChild(textArea);
    };

    const generateBackupCodes = async (sendEmail = false) => {
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/2fa/backup-codes`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ send_email: sendEmail })
            });
            const data = await response.json();
            if (data.success) {
                setBackupCodes(data.codes);
                fetchStatus();
                if (sendEmail) {
                    message.success('New codes generated and sent to your email');
                } else {
                    message.success('New backup codes generated');
                }

                Modal.info({
                    title: 'New Backup Codes',
                    content: (
                        <div>
                            <p>Save these codes in a safe place. Previous codes are now invalid.</p>
                            {sendEmail && <p><strong>A copy has been sent to your email.</strong></p>}
                            <div style={{ background: '#f5f5f5', padding: 10, fontFamily: 'monospace' }}>
                                {data.codes.join('\n')}
                            </div>
                        </div>
                    ),
                    onOk() { }
                });
            } else {
                message.error('Failed to generate codes');
            }
        } catch (error) {
            message.error('Error generating codes');
        }
    };

    if (loading && !status) {
        return (
            <Layout>
                <div style={styles.container}>
                    <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />
                </div>
            </Layout>
        );
    }

    const My2FAContent = (
        <div style={{ marginTop: 24 }}>
            {status?.enabled ? (
                <div style={styles.statusCard}>
                    <CheckCircleTwoTone twoToneColor="#52c41a" style={styles.statusIcon} />
                    <div>
                        <Title level={4} style={{ margin: 0, color: '#52c41a' }}>Two-Factor Authentication is Enabled</Title>
                        <Text type="secondary">Your account is secure.</Text>
                    </div>
                </div>
            ) : (
                <div style={{ ...styles.statusCard, background: '#fffbe6', border: '1px solid #ffe58f' }}>
                    <ExclamationCircleTwoTone twoToneColor="#faad14" style={styles.statusIcon} />
                    <div>
                        <Title level={4} style={{ margin: 0, color: '#faad14' }}>Two-Factor Authentication is Disabled</Title>
                        <Text type="secondary">Enable it to add an extra layer of security.</Text>
                    </div>
                </div>
            )}

            <Row gutter={[24, 24]}>
                <Col xs={24} md={12}>
                    <Card title="Manage 2FA" style={styles.card}>
                        {status?.enabled ? (
                            <div>
                                <p>Two-factor authentication is currently enabled for your account.</p>
                                <Button danger onClick={disable2FA}>Disable 2FA</Button>
                            </div>
                        ) : (
                            <div>
                                <p>Protect your account with an extra layer of security. Once configured, you'll be required to enter both your password and an authentication code.</p>
                                <Button type="primary" onClick={startSetup}>Enable 2FA</Button>
                            </div>
                        )}
                    </Card>
                </Col>

                {status?.enabled && (
                    <Col xs={24} md={12}>
                        <Card title="Backup Codes" style={styles.card}>
                            <Statistic title="Available Codes" value={status.backup_codes_count} />
                            <Paragraph style={{ marginTop: 16 }}>
                                Backup codes can be used to access your account if you lose your device.
                            </Paragraph>
                            <Space wrap>
                                <Button type="primary" onClick={() => generateBackupCodes(false)}>Generate New Codes</Button>
                                <Button onClick={() => generateBackupCodes(true)}>Generate & Email Me</Button>
                            </Space>
                        </Card>
                    </Col>
                )}



                <Col span={24}>
                    <Card title="Recent Activity" style={styles.card}>
                        <div style={{ maxHeight: 300, overflowY: 'auto' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                <thead>
                                    <tr style={{ background: '#f5f5f5', textAlign: 'left' }}>
                                        <th style={{ padding: 8 }}>Time</th>
                                        <th style={{ padding: 8 }}>Event</th>
                                        <th style={{ padding: 8 }}>Status</th>
                                        <th style={{ padding: 8 }}>IP Address</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {status?.activity_log?.map((log, idx) => (
                                        <tr key={idx} style={{ borderBottom: '1px solid #eee' }}>
                                            <td style={{ padding: 8 }}>{log.time}</td>
                                            <td style={{ padding: 8 }}>{log.event}</td>
                                            <td style={{ padding: 8 }}>
                                                <Tag color={log.status === 'success' ? 'green' : 'red'}>{log.status}</Tag>
                                            </td>
                                            <td style={{ padding: 8 }}>{log.ip}</td>
                                        </tr>
                                    ))}
                                    {!status?.activity_log?.length && (
                                        <tr><td colSpan={4} style={{ padding: 20, textAlign: 'center', color: '#999' }}>No activity recorded yet</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </Card>
                </Col>
            </Row>
        </div>
    );

    // Check if user is admin (simple check via roles)
    const isAdmin = status?.user_roles?.includes('administrator');

    const SettingsContent = (
        <div style={{ marginTop: 24 }}>
            <Card title="Role Enforcement" style={styles.card}>
                <Alert
                    message="Enforce 2FA for specific user roles"
                    description="Users in the selected roles will be required to set up Two-Factor Authentication before accessing the dashboard."
                    type="info"
                    showIcon
                    style={{ marginBottom: 24 }}
                />
                <Form
                    form={settingsForm}
                    onFinish={saveSettings}
                    layout="vertical"
                >
                    <Form.Item name="forced_roles" label="Select Roles">
                        <Checkbox.Group style={{ width: '100%' }}>
                            <Row gutter={[8, 8]}>
                                {status?.available_roles && Object.entries(status.available_roles).map(([slug, name]) => (
                                    <Col span={8} key={slug}>
                                        <Checkbox value={slug}>{name}</Checkbox>
                                    </Col>
                                ))}
                            </Row>
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={savingSettings}>Save Settings</Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );

    const items = [
        {
            key: '1',
            label: <span><MobileOutlined /> My 2FA</span>,
            children: My2FAContent,
        },
    ];

    if (isAdmin) {
        items.push({
            key: '2',
            label: <span><SettingOutlined /> Global Settings</span>,
            children: SettingsContent,
        });
    }

    return (
        <Layout>
            <div style={styles.container}>
                <div style={styles.pageTitle}>
                    <LockOutlined style={{ color: '#1890ff', fontSize: 32 }} />
                    Two-Factor Authentication
                </div>
                <div style={styles.subtitle}>
                    <Text type="secondary">
                        Secure your account with two-step verification.
                    </Text>
                </div>

                <Tabs defaultActiveKey="1" items={items} />

                <Modal
                    title="Setup Two-Factor Authentication"
                    open={setupMode}
                    onCancel={() => { if (currentStep !== 2) setSetupMode(false); }}
                    footer={null}
                    width={600}
                    maskClosable={false}
                >
                    <Steps current={currentStep} style={{ marginBottom: 24 }}>
                        <Step title="Configure" icon={<MobileOutlined />} />
                        <Step title="Verify" icon={<CheckCircleOutlined />} />
                        <Step title="Complete" icon={<SafetyCertificateOutlined />} />
                    </Steps>

                    {currentStep === 1 && setupData && (
                        <div style={{ textAlign: 'center' }}>
                            <Paragraph>Scan this QR code with your authenticator app (e.g. Google Authenticator, Authy).</Paragraph>
                            <div style={{ background: '#f0f2f5', padding: 16, display: 'inline-block', borderRadius: 8 }}>
                                <img src={setupData.qr_code_url} alt="QR Code" style={{ maxWidth: '200px' }} />
                            </div>
                            <Paragraph style={{ marginTop: 16 }}>Or manually enter this <strong>Secret Key</strong> into your Authenticator App:</Paragraph>
                            <Alert
                                message={setupData.secret}
                                type="info"
                                action={
                                    <Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyToClipboard(setupData.secret)} />
                                }
                                style={{ maxWidth: 300, margin: '0 auto' }}
                            />

                            <Divider />

                            <Paragraph>Enter the 6-digit code from your app:</Paragraph>
                            <Space>
                                <Input
                                    placeholder="000 000"
                                    value={verificationCode}
                                    onChange={e => setVerificationCode(e.target.value)}
                                    maxLength={6}
                                    style={{ width: 150, textAlign: 'center', fontSize: '18px', letterSpacing: '4px' }}
                                    onPressEnter={verifySetup}
                                />
                                <Button type="primary" onClick={verifySetup} loading={verifying}>Verify & Activate</Button>
                            </Space>
                        </div>
                    )}

                    {currentStep === 2 && (
                        <div style={{ textAlign: 'center' }}>
                            <Result
                                status="success"
                                title="Two-Factor Authentication Enabled!"
                                subTitle="Your account is now more secure."
                            />

                            <div style={{ textAlign: 'left', background: '#f9f9f9', padding: 20, borderRadius: 8, marginBottom: 24 }}>
                                <Title level={4}>Save your backup codes</Title>
                                <Paragraph>
                                    If you lose your device, you can use these codes to log in. Each code can only be used once.
                                    <Text strong> Save them in a safe place.</Text>
                                </Paragraph>
                                <Row gutter={[16, 16]}>
                                    {backupCodes.map((code, idx) => (
                                        <Col span={12} key={idx}>
                                            <div style={{ fontFamily: 'monospace', background: '#fff', padding: 8, border: '1px solid #eee', textAlign: 'center' }}>
                                                {code}
                                            </div>
                                        </Col>
                                    ))}
                                </Row>
                                <Button type="dashed" block icon={<CopyOutlined />} style={{ marginTop: 16 }} onClick={() => copyToClipboard(backupCodes.join('\n'))}>
                                    Copy All Codes
                                </Button>
                            </div>

                            <Button type="primary" size="large" onClick={() => { setSetupMode(false); fetchStatus(); }}>
                                Done
                            </Button>
                        </div>
                    )}
                </Modal>
            </div>
        </Layout>
    );
};

export default TwoFactorAuth;
